blob: 573738cedb9ebeb9187a850f7c92185ac1c2c784 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000040#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000041#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner8123a952008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattner9e979552008-04-12 23:52:44 +000049namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 public:
Mike Stump1eb44332009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000068 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000069 };
Chris Lattner8123a952008-04-10 02:22:51 +000070
Chris Lattner9e979552008-04-12 23:52:44 +000071 /// VisitExpr - Visit all of the children of this expression.
72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000074 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000075 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000076 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000077 }
78
Chris Lattner9e979552008-04-12 23:52:44 +000079 /// VisitDeclRefExpr - Visit a reference to a declaration, to
80 /// determine whether this declaration can be used in the default
81 /// argument expression.
82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000083 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000084 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85 // C++ [dcl.fct.default]p9
86 // Default arguments are evaluated each time the function is
87 // called. The order of evaluation of function arguments is
88 // unspecified. Consequently, parameters of a function shall not
89 // be used in default argument expressions, even if they are not
90 // evaluated. Parameters of a function declared before a default
91 // argument expression are in scope and can hide namespace and
92 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000093 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000095 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000096 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000097 // C++ [dcl.fct.default]p7
98 // Local variables shall not be used in default argument
99 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000100 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000101 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000103 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000104 }
Chris Lattner8123a952008-04-10 02:22:51 +0000105
Douglas Gregor3996f232008-11-04 13:41:56 +0000106 return false;
107 }
Chris Lattner9e979552008-04-12 23:52:44 +0000108
Douglas Gregor796da182008-11-04 14:32:21 +0000109 /// VisitCXXThisExpr - Visit a C++ "this" expression.
110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111 // C++ [dcl.fct.default]p8:
112 // The keyword this shall not be used in a default argument of a
113 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000114 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000115 diag::err_param_default_argument_references_this)
116 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000117 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000118
John McCall045d2522013-04-09 01:56:28 +0000119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120 bool Invalid = false;
121 for (PseudoObjectExpr::semantics_iterator
122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123 Expr *E = *i;
124
125 // Look through bindings.
126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127 E = OVE->getSourceExpr();
128 assert(E && "pseudo-object binding without source expression?");
129 }
130
131 Invalid |= Visit(E);
132 }
133 return Invalid;
134 }
135
Douglas Gregorf0459f82012-02-10 23:30:22 +0000136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137 // C++11 [expr.lambda.prim]p13:
138 // A lambda-expression appearing in a default argument shall not
139 // implicitly or explicitly capture any entity.
140 if (Lambda->capture_begin() == Lambda->capture_end())
141 return false;
142
143 return S->Diag(Lambda->getLocStart(),
144 diag::err_lambda_capture_default_arg);
145 }
Chris Lattner8123a952008-04-10 02:22:51 +0000146}
147
Richard Smith0b0ca472013-04-10 06:11:48 +0000148void
149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000151 // If we have an MSAny spec already, don't bother.
152 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000153 return;
154
155 const FunctionProtoType *Proto
156 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158 if (!Proto)
159 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000160
161 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162
163 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000164 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000165 ClearExceptions();
166 ComputedEST = EST;
167 return;
168 }
169
Richard Smith7a614d82011-06-11 17:19:42 +0000170 // FIXME: If the call to this decl is using any of its default arguments, we
171 // need to search them for potentially-throwing calls.
172
Sean Hunt001cad92011-05-10 00:49:42 +0000173 // If this function has a basic noexcept, it doesn't affect the outcome.
174 if (EST == EST_BasicNoexcept)
175 return;
176
177 // If we have a throw-all spec at this point, ignore the function.
178 if (ComputedEST == EST_None)
179 return;
180
181 // If we're still at noexcept(true) and there's a nothrow() callee,
182 // change to that specification.
183 if (EST == EST_DynamicNone) {
184 if (ComputedEST == EST_BasicNoexcept)
185 ComputedEST = EST_DynamicNone;
186 return;
187 }
188
189 // Check out noexcept specs.
190 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
198
199 // noexcept(false) -> no spec on the new function
200 if (NR == FunctionProtoType::NR_Throw) {
201 ClearExceptions();
202 ComputedEST = EST_None;
203 }
204 // noexcept(true) won't change anything either.
205 return;
206 }
207
208 assert(EST == EST_Dynamic && "EST case not considered earlier.");
209 assert(ComputedEST != EST_None &&
210 "Shouldn't collect exceptions when throw-all is guaranteed.");
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214 EEnd = Proto->exception_end();
215 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000217 Exceptions.push_back(*E);
218}
219
Richard Smith7a614d82011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithe6975e92012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssoned961f92009-08-25 02:29:20 +0000249bool
John McCall9ae2f072010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param)
343 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Anders Carlsson5e300d12009-06-12 16:51:40 +0000358 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000359}
360
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367 // C++ [dcl.fct.default]p3
368 // A default argument expression shall be specified only in the
369 // parameter-declaration-clause of a function declaration or in a
370 // template-parameter (14.1). It shall not be specified for a
371 // parameter pack. If it is specified in a
372 // parameter-declaration-clause, it shall not occur within a
373 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000378 if (MightBeFunction) {
379 // This is a function declaration. It can have default arguments, but
380 // keep looking in case its return type is a function type with default
381 // arguments.
382 MightBeFunction = false;
383 continue;
384 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000393 delete Toks;
394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000395 } else if (Param->getDefaultArg()) {
396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397 << Param->getDefaultArg()->getSourceRange();
398 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000399 }
400 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000403 }
404 }
405}
406
Craig Topper1a6eac82012-09-21 04:33:26 +0000407/// MergeCXXFunctionDecl - Merge two declarations of the same C++
408/// function, once we already know that they have the same
409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
410/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
412 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000413 bool Invalid = false;
414
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000416 // For non-template functions, default arguments can be added in
417 // later declarations of a function in the same
418 // scope. Declarations in different scopes have completely
419 // distinct sets of default arguments. That is, declarations in
420 // inner scopes do not acquire default arguments from
421 // declarations in outer scopes, and vice versa. In a given
422 // function declaration, all parameters subsequent to a
423 // parameter with a default argument shall have default
424 // arguments supplied in this or previous declarations. A
425 // default argument shall not be redefined by a later
426 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000427 //
428 // C++ [dcl.fct.default]p6:
429 // Except for member functions of class templates, the default arguments
430 // in a member function definition that appears outside of the class
431 // definition are added to the set of default arguments provided by the
432 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000433 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
434 ParmVarDecl *OldParam = Old->getParamDecl(p);
435 ParmVarDecl *NewParam = New->getParamDecl(p);
436
James Molloy9cda03f2012-03-13 08:55:35 +0000437 bool OldParamHasDfl = OldParam->hasDefaultArg();
438 bool NewParamHasDfl = NewParam->hasDefaultArg();
439
440 NamedDecl *ND = Old;
441 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
442 // Ignore default parameters of old decl if they are not in
443 // the same scope.
444 OldParamHasDfl = false;
445
446 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000447
Francois Pichet8d051e02011-04-10 03:03:52 +0000448 unsigned DiagDefaultParamID =
449 diag::err_param_default_argument_redefinition;
450
451 // MSVC accepts that default parameters be redefined for member functions
452 // of template class. The new default parameter's value is ignored.
453 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000454 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000455 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
456 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000457 // Merge the old default argument into the new parameter.
458 NewParam->setHasInheritedDefaultArg();
459 if (OldParam->hasUninstantiatedDefaultArg())
460 NewParam->setUninstantiatedDefaultArg(
461 OldParam->getUninstantiatedDefaultArg());
462 else
463 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000464 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000465 Invalid = false;
466 }
467 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000468
Francois Pichet8cf90492011-04-10 04:58:30 +0000469 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
470 // hint here. Alternatively, we could walk the type-source information
471 // for NewParam to find the last source location in the type... but it
472 // isn't worth the effort right now. This is the kind of test case that
473 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000474 // int f(int);
475 // void g(int (*fp)(int) = f);
476 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000477 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000478 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000479
480 // Look for the function declaration where the default argument was
481 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000482 for (FunctionDecl *Older = Old->getPreviousDecl();
483 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000484 if (!Older->getParamDecl(p)->hasDefaultArg())
485 break;
486
487 OldParam = Older->getParamDecl(p);
488 }
489
490 Diag(OldParam->getLocation(), diag::note_previous_definition)
491 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000492 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000493 // Merge the old default argument into the new parameter.
494 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000495 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000496 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000497 if (OldParam->hasUninstantiatedDefaultArg())
498 NewParam->setUninstantiatedDefaultArg(
499 OldParam->getUninstantiatedDefaultArg());
500 else
John McCall3d6c1782010-05-04 01:53:42 +0000501 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000502 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000503 if (New->getDescribedFunctionTemplate()) {
504 // Paragraph 4, quoted above, only applies to non-template functions.
505 Diag(NewParam->getLocation(),
506 diag::err_param_default_argument_template_redecl)
507 << NewParam->getDefaultArgRange();
508 Diag(Old->getLocation(), diag::note_template_prev_declaration)
509 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000510 } else if (New->getTemplateSpecializationKind()
511 != TSK_ImplicitInstantiation &&
512 New->getTemplateSpecializationKind() != TSK_Undeclared) {
513 // C++ [temp.expr.spec]p21:
514 // Default function arguments shall not be specified in a declaration
515 // or a definition for one of the following explicit specializations:
516 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000517 // - the explicit specialization of a member function template;
518 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000519 // template where the class template specialization to which the
520 // member function specialization belongs is implicitly
521 // instantiated.
522 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
523 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
524 << New->getDeclName()
525 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000526 } else if (New->getDeclContext()->isDependentContext()) {
527 // C++ [dcl.fct.default]p6 (DR217):
528 // Default arguments for a member function of a class template shall
529 // be specified on the initial declaration of the member function
530 // within the class template.
531 //
532 // Reading the tea leaves a bit in DR217 and its reference to DR205
533 // leads me to the conclusion that one cannot add default function
534 // arguments for an out-of-line definition of a member function of a
535 // dependent type.
536 int WhichKind = 2;
537 if (CXXRecordDecl *Record
538 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
539 if (Record->getDescribedClassTemplate())
540 WhichKind = 0;
541 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
542 WhichKind = 1;
543 else
544 WhichKind = 2;
545 }
546
547 Diag(NewParam->getLocation(),
548 diag::err_param_default_argument_member_template_redecl)
549 << WhichKind
550 << NewParam->getDefaultArgRange();
551 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000552 }
553 }
554
Richard Smithb8abff62012-11-28 03:45:24 +0000555 // DR1344: If a default argument is added outside a class definition and that
556 // default argument makes the function a special member function, the program
557 // is ill-formed. This can only happen for constructors.
558 if (isa<CXXConstructorDecl>(New) &&
559 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
560 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
561 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
562 if (NewSM != OldSM) {
563 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
564 assert(NewParam->hasDefaultArg());
565 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
566 << NewParam->getDefaultArgRange() << NewSM;
567 Diag(Old->getLocation(), diag::note_previous_declaration);
568 }
569 }
570
Richard Smithff234882012-02-20 23:28:05 +0000571 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000572 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000573 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000574 if (New->isConstexpr() != Old->isConstexpr()) {
575 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
576 << New << New->isConstexpr();
577 Diag(Old->getLocation(), diag::note_previous_declaration);
578 Invalid = true;
579 }
580
Douglas Gregore13ad832010-02-12 07:32:17 +0000581 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000582 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000583
Douglas Gregorcda9c672009-02-16 17:45:42 +0000584 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585}
586
Sebastian Redl60618fa2011-03-12 11:50:43 +0000587/// \brief Merge the exception specifications of two variable declarations.
588///
589/// This is called when there's a redeclaration of a VarDecl. The function
590/// checks if the redeclaration might have an exception specification and
591/// validates compatibility and merges the specs if necessary.
592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
593 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000594 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000595 return;
596
597 assert(Context.hasSameType(New->getType(), Old->getType()) &&
598 "Should only be called if types are otherwise the same.");
599
600 QualType NewType = New->getType();
601 QualType OldType = Old->getType();
602
603 // We're only interested in pointers and references to functions, as well
604 // as pointers to member functions.
605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
606 NewType = R->getPointeeType();
607 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
608 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
609 NewType = P->getPointeeType();
610 OldType = OldType->getAs<PointerType>()->getPointeeType();
611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
612 NewType = M->getPointeeType();
613 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
614 }
615
616 if (!NewType->isFunctionProtoType())
617 return;
618
619 // There's lots of special cases for functions. For function pointers, system
620 // libraries are hopefully not as broken so that we don't need these
621 // workarounds.
622 if (CheckEquivalentExceptionSpec(
623 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
624 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
625 New->setInvalidDecl();
626 }
627}
628
Chris Lattner3d1cee32008-04-08 05:04:30 +0000629/// CheckCXXDefaultArguments - Verify that the default arguments for a
630/// function declaration are well-formed according to C++
631/// [dcl.fct.default].
632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
633 unsigned NumParams = FD->getNumParams();
634 unsigned p;
635
636 // Find first parameter with a default argument
637 for (p = 0; p < NumParams; ++p) {
638 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000639 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 break;
641 }
642
643 // C++ [dcl.fct.default]p4:
644 // In a given function declaration, all parameters
645 // subsequent to a parameter with a default argument shall
646 // have default arguments supplied in this or previous
647 // declarations. A default argument shall not be redefined
648 // by a later declaration (not even to the same value).
649 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000650 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000652 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000653 if (Param->isInvalidDecl())
654 /* We already complained about this parameter. */;
655 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000656 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000657 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000658 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000659 else
Mike Stump1eb44332009-09-09 15:08:12 +0000660 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000661 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663 LastMissingDefaultArg = p;
664 }
665 }
666
667 if (LastMissingDefaultArg > 0) {
668 // Some default arguments were missing. Clear out all of the
669 // default arguments up to (and including) the last missing
670 // default argument, so that we leave the function parameters
671 // in a semantically valid state.
672 for (p = 0; p <= LastMissingDefaultArg; ++p) {
673 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000674 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000675 Param->setDefaultArg(0);
676 }
677 }
678 }
679}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000680
Richard Smith9f569cc2011-10-01 02:31:28 +0000681// CheckConstexprParameterTypes - Check whether a function's parameter types
682// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000683// diagnostic and return false.
684static bool CheckConstexprParameterTypes(Sema &SemaRef,
685 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000686 unsigned ArgIndex = 0;
687 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
688 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
689 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
690 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
691 SourceLocation ParamLoc = PD->getLocation();
692 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000693 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000694 diag::err_constexpr_non_literal_param,
695 ArgIndex+1, PD->getSourceRange(),
696 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000697 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000698 }
Joao Matos17d35c32012-08-31 22:18:20 +0000699 return true;
700}
701
702/// \brief Get diagnostic %select index for tag kind for
703/// record diagnostic message.
704/// WARNING: Indexes apply to particular diagnostics only!
705///
706/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000707static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000708 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000709 case TTK_Struct: return 0;
710 case TTK_Interface: return 1;
711 case TTK_Class: return 2;
712 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000713 }
Joao Matos17d35c32012-08-31 22:18:20 +0000714}
715
716// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
717// the requirements of a constexpr function definition or a constexpr
718// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000719// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000720//
Richard Smith86c3ae42012-02-13 03:54:03 +0000721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
722bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000723 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
724 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000725 // C++11 [dcl.constexpr]p4:
726 // The definition of a constexpr constructor shall satisfy the following
727 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000729 const CXXRecordDecl *RD = MD->getParent();
730 if (RD->getNumVBases()) {
731 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
732 << isa<CXXConstructorDecl>(NewFD)
733 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
734 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
735 E = RD->vbases_end(); I != E; ++I)
736 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000737 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000738 return false;
739 }
Richard Smith35340502012-01-13 04:54:00 +0000740 }
741
742 if (!isa<CXXConstructorDecl>(NewFD)) {
743 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000744 // The definition of a constexpr function shall satisfy the following
745 // constraints:
746 // - it shall not be virtual;
747 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
748 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000750
Richard Smith86c3ae42012-02-13 03:54:03 +0000751 // If it's not obvious why this function is virtual, find an overridden
752 // function which uses the 'virtual' keyword.
753 const CXXMethodDecl *WrittenVirtual = Method;
754 while (!WrittenVirtual->isVirtualAsWritten())
755 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
756 if (WrittenVirtual != Method)
757 Diag(WrittenVirtual->getLocation(),
758 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000759 return false;
760 }
761
762 // - its return type shall be a literal type;
763 QualType RT = NewFD->getResultType();
764 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000765 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000766 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000768 }
769
Richard Smith35340502012-01-13 04:54:00 +0000770 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000771 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000772 return false;
773
Richard Smith9f569cc2011-10-01 02:31:28 +0000774 return true;
775}
776
777/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000778/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000779///
Richard Smitha10b9782013-04-22 15:31:51 +0000780/// \return true if the body is OK (maybe only as an extension), false if we
781/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000782static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000783 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
784 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000785 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
786 // contain only
787 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
788 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
789 switch ((*DclIt)->getKind()) {
790 case Decl::StaticAssert:
791 case Decl::Using:
792 case Decl::UsingShadow:
793 case Decl::UsingDirective:
794 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000795 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 // - static_assert-declarations
797 // - using-declarations,
798 // - using-directives,
799 continue;
800
801 case Decl::Typedef:
802 case Decl::TypeAlias: {
803 // - typedef declarations and alias-declarations that do not define
804 // classes or enumerations,
805 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
806 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
807 // Don't allow variably-modified types in constexpr functions.
808 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
809 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
810 << TL.getSourceRange() << TL.getType()
811 << isa<CXXConstructorDecl>(Dcl);
812 return false;
813 }
814 continue;
815 }
816
817 case Decl::Enum:
818 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000819 // C++1y allows types to be defined, not just declared.
820 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
821 SemaRef.Diag(DS->getLocStart(),
822 SemaRef.getLangOpts().CPlusPlus1y
823 ? diag::warn_cxx11_compat_constexpr_type_definition
824 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000825 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000826 continue;
827
Richard Smitha10b9782013-04-22 15:31:51 +0000828 case Decl::EnumConstant:
829 case Decl::IndirectField:
830 case Decl::ParmVar:
831 // These can only appear with other declarations which are banned in
832 // C++11 and permitted in C++1y, so ignore them.
833 continue;
834
835 case Decl::Var: {
836 // C++1y [dcl.constexpr]p3 allows anything except:
837 // a definition of a variable of non-literal type or of static or
838 // thread storage duration or for which no initialization is performed.
839 VarDecl *VD = cast<VarDecl>(*DclIt);
840 if (VD->isThisDeclarationADefinition()) {
841 if (VD->isStaticLocal()) {
842 SemaRef.Diag(VD->getLocation(),
843 diag::err_constexpr_local_var_static)
844 << isa<CXXConstructorDecl>(Dcl)
845 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
846 return false;
847 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000848 if (!VD->getType()->isDependentType() &&
849 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000850 VD->getLocation(), VD->getType(),
851 diag::err_constexpr_local_var_non_literal_type,
852 isa<CXXConstructorDecl>(Dcl)))
853 return false;
854 if (!VD->hasInit()) {
855 SemaRef.Diag(VD->getLocation(),
856 diag::err_constexpr_local_var_no_init)
857 << isa<CXXConstructorDecl>(Dcl);
858 return false;
859 }
860 }
861 SemaRef.Diag(VD->getLocation(),
862 SemaRef.getLangOpts().CPlusPlus1y
863 ? diag::warn_cxx11_compat_constexpr_local_var
864 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000865 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000866 continue;
867 }
868
869 case Decl::NamespaceAlias:
870 case Decl::Function:
871 // These are disallowed in C++11 and permitted in C++1y. Allow them
872 // everywhere as an extension.
873 if (!Cxx1yLoc.isValid())
874 Cxx1yLoc = DS->getLocStart();
875 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000876
877 default:
878 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882 }
883
884 return true;
885}
886
887/// Check that the given field is initialized within a constexpr constructor.
888///
889/// \param Dcl The constexpr constructor being checked.
890/// \param Field The field being checked. This may be a member of an anonymous
891/// struct or union nested within the class being checked.
892/// \param Inits All declarations, including anonymous struct/union members and
893/// indirect members, for which any initialization was provided.
894/// \param Diagnosed Set to true if an error is produced.
895static void CheckConstexprCtorInitializer(Sema &SemaRef,
896 const FunctionDecl *Dcl,
897 FieldDecl *Field,
898 llvm::SmallSet<Decl*, 16> &Inits,
899 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000900 if (Field->isUnnamedBitfield())
901 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000902
903 if (Field->isAnonymousStructOrUnion() &&
904 Field->getType()->getAsCXXRecordDecl()->isEmpty())
905 return;
906
Richard Smith9f569cc2011-10-01 02:31:28 +0000907 if (!Inits.count(Field)) {
908 if (!Diagnosed) {
909 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
910 Diagnosed = true;
911 }
912 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
913 } else if (Field->isAnonymousStructOrUnion()) {
914 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
915 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
916 I != E; ++I)
917 // If an anonymous union contains an anonymous struct of which any member
918 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000919 if (!RD->isUnion() || Inits.count(*I))
920 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000921 }
922}
923
Richard Smitha10b9782013-04-22 15:31:51 +0000924/// Check the provided statement is allowed in a constexpr function
925/// definition.
926static bool
927CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
928 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
929 SourceLocation &Cxx1yLoc) {
930 // - its function-body shall be [...] a compound-statement that contains only
931 switch (S->getStmtClass()) {
932 case Stmt::NullStmtClass:
933 // - null statements,
934 return true;
935
936 case Stmt::DeclStmtClass:
937 // - static_assert-declarations
938 // - using-declarations,
939 // - using-directives,
940 // - typedef declarations and alias-declarations that do not define
941 // classes or enumerations,
942 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
943 return false;
944 return true;
945
946 case Stmt::ReturnStmtClass:
947 // - and exactly one return statement;
948 if (isa<CXXConstructorDecl>(Dcl)) {
949 // C++1y allows return statements in constexpr constructors.
950 if (!Cxx1yLoc.isValid())
951 Cxx1yLoc = S->getLocStart();
952 return true;
953 }
954
955 ReturnStmts.push_back(S->getLocStart());
956 return true;
957
958 case Stmt::CompoundStmtClass: {
959 // C++1y allows compound-statements.
960 if (!Cxx1yLoc.isValid())
961 Cxx1yLoc = S->getLocStart();
962
963 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
964 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
965 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
966 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
967 Cxx1yLoc))
968 return false;
969 }
970 return true;
971 }
972
973 case Stmt::AttributedStmtClass:
974 if (!Cxx1yLoc.isValid())
975 Cxx1yLoc = S->getLocStart();
976 return true;
977
978 case Stmt::IfStmtClass: {
979 // C++1y allows if-statements.
980 if (!Cxx1yLoc.isValid())
981 Cxx1yLoc = S->getLocStart();
982
983 IfStmt *If = cast<IfStmt>(S);
984 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
985 Cxx1yLoc))
986 return false;
987 if (If->getElse() &&
988 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
989 Cxx1yLoc))
990 return false;
991 return true;
992 }
993
994 case Stmt::WhileStmtClass:
995 case Stmt::DoStmtClass:
996 case Stmt::ForStmtClass:
997 case Stmt::CXXForRangeStmtClass:
998 case Stmt::ContinueStmtClass:
999 // C++1y allows all of these. We don't allow them as extensions in C++11,
1000 // because they don't make sense without variable mutation.
1001 if (!SemaRef.getLangOpts().CPlusPlus1y)
1002 break;
1003 if (!Cxx1yLoc.isValid())
1004 Cxx1yLoc = S->getLocStart();
1005 for (Stmt::child_range Children = S->children(); Children; ++Children)
1006 if (*Children &&
1007 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1008 Cxx1yLoc))
1009 return false;
1010 return true;
1011
1012 case Stmt::SwitchStmtClass:
1013 case Stmt::CaseStmtClass:
1014 case Stmt::DefaultStmtClass:
1015 case Stmt::BreakStmtClass:
1016 // C++1y allows switch-statements, and since they don't need variable
1017 // mutation, we can reasonably allow them in C++11 as an extension.
1018 if (!Cxx1yLoc.isValid())
1019 Cxx1yLoc = S->getLocStart();
1020 for (Stmt::child_range Children = S->children(); Children; ++Children)
1021 if (*Children &&
1022 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1023 Cxx1yLoc))
1024 return false;
1025 return true;
1026
1027 default:
1028 if (!isa<Expr>(S))
1029 break;
1030
1031 // C++1y allows expression-statements.
1032 if (!Cxx1yLoc.isValid())
1033 Cxx1yLoc = S->getLocStart();
1034 return true;
1035 }
1036
1037 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1038 << isa<CXXConstructorDecl>(Dcl);
1039 return false;
1040}
1041
Richard Smith9f569cc2011-10-01 02:31:28 +00001042/// Check the body for the given constexpr function declaration only contains
1043/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1044///
1045/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001046bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001047 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001048 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001049 // The definition of a constexpr function shall satisfy the following
1050 // constraints: [...]
1051 // - its function-body shall be = delete, = default, or a
1052 // compound-statement
1053 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001054 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001055 // In the definition of a constexpr constructor, [...]
1056 // - its function-body shall not be a function-try-block;
1057 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1058 << isa<CXXConstructorDecl>(Dcl);
1059 return false;
1060 }
1061
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001062 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001063
1064 // - its function-body shall be [...] a compound-statement that contains only
1065 // [... list of cases ...]
1066 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1067 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001068 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1069 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001070 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1071 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001072 }
1073
Richard Smitha10b9782013-04-22 15:31:51 +00001074 if (Cxx1yLoc.isValid())
1075 Diag(Cxx1yLoc,
1076 getLangOpts().CPlusPlus1y
1077 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1078 : diag::ext_constexpr_body_invalid_stmt)
1079 << isa<CXXConstructorDecl>(Dcl);
1080
Richard Smith9f569cc2011-10-01 02:31:28 +00001081 if (const CXXConstructorDecl *Constructor
1082 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1083 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001084 // DR1359:
1085 // - every non-variant non-static data member and base class sub-object
1086 // shall be initialized;
1087 // - if the class is a non-empty union, or for each non-empty anonymous
1088 // union member of a non-union class, exactly one non-static data member
1089 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001090 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001091 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001092 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1093 return false;
1094 }
Richard Smith6e433752011-10-10 16:38:04 +00001095 } else if (!Constructor->isDependentContext() &&
1096 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001097 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1098
1099 // Skip detailed checking if we have enough initializers, and we would
1100 // allow at most one initializer per member.
1101 bool AnyAnonStructUnionMembers = false;
1102 unsigned Fields = 0;
1103 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1104 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001105 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001106 AnyAnonStructUnionMembers = true;
1107 break;
1108 }
1109 }
1110 if (AnyAnonStructUnionMembers ||
1111 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1112 // Check initialization of non-static data members. Base classes are
1113 // always initialized so do not need to be checked. Dependent bases
1114 // might not have initializers in the member initializer list.
1115 llvm::SmallSet<Decl*, 16> Inits;
1116 for (CXXConstructorDecl::init_const_iterator
1117 I = Constructor->init_begin(), E = Constructor->init_end();
1118 I != E; ++I) {
1119 if (FieldDecl *FD = (*I)->getMember())
1120 Inits.insert(FD);
1121 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1122 Inits.insert(ID->chain_begin(), ID->chain_end());
1123 }
1124
1125 bool Diagnosed = false;
1126 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1127 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001128 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001129 if (Diagnosed)
1130 return false;
1131 }
1132 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001133 } else {
1134 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001135 // C++1y doesn't require constexpr functions to contain a 'return'
1136 // statement. We still do, unless the return type is void, because
1137 // otherwise if there's no return statement, the function cannot
1138 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001139 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001140 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001141 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1142 : diag::err_constexpr_body_no_return);
1143 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001144 }
1145 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001146 Diag(ReturnStmts.back(),
1147 getLangOpts().CPlusPlus1y
1148 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1149 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001150 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1151 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001152 }
1153 }
1154
Richard Smith5ba73e12012-02-04 00:33:54 +00001155 // C++11 [dcl.constexpr]p5:
1156 // if no function argument values exist such that the function invocation
1157 // substitution would produce a constant expression, the program is
1158 // ill-formed; no diagnostic required.
1159 // C++11 [dcl.constexpr]p3:
1160 // - every constructor call and implicit conversion used in initializing the
1161 // return value shall be one of those allowed in a constant expression.
1162 // C++11 [dcl.constexpr]p4:
1163 // - every constructor involved in initializing non-static data members and
1164 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001165 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001166 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001167 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001168 << isa<CXXConstructorDecl>(Dcl);
1169 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1170 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001171 // Don't return false here: we allow this for compatibility in
1172 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001173 }
1174
Richard Smith9f569cc2011-10-01 02:31:28 +00001175 return true;
1176}
1177
Douglas Gregorb48fe382008-10-31 09:07:45 +00001178/// isCurrentClassName - Determine whether the identifier II is the
1179/// name of the class type currently being defined. In the case of
1180/// nested classes, this will only return true if II is the name of
1181/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001182bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1183 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001184 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001185
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001186 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001187 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001188 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001189 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1190 } else
1191 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1192
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001193 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001194 return &II == CurDecl->getIdentifier();
1195 else
1196 return false;
1197}
1198
Douglas Gregor229d47a2012-11-10 07:24:09 +00001199/// \brief Determine whether the given class is a base class of the given
1200/// class, including looking at dependent bases.
1201static bool findCircularInheritance(const CXXRecordDecl *Class,
1202 const CXXRecordDecl *Current) {
1203 SmallVector<const CXXRecordDecl*, 8> Queue;
1204
1205 Class = Class->getCanonicalDecl();
1206 while (true) {
1207 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1208 E = Current->bases_end();
1209 I != E; ++I) {
1210 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1211 if (!Base)
1212 continue;
1213
1214 Base = Base->getDefinition();
1215 if (!Base)
1216 continue;
1217
1218 if (Base->getCanonicalDecl() == Class)
1219 return true;
1220
1221 Queue.push_back(Base);
1222 }
1223
1224 if (Queue.empty())
1225 return false;
1226
1227 Current = Queue.back();
1228 Queue.pop_back();
1229 }
1230
1231 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001232}
1233
Mike Stump1eb44332009-09-09 15:08:12 +00001234/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001235///
1236/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1237/// and returns NULL otherwise.
1238CXXBaseSpecifier *
1239Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1240 SourceRange SpecifierRange,
1241 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001242 TypeSourceInfo *TInfo,
1243 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001244 QualType BaseType = TInfo->getType();
1245
Douglas Gregor2943aed2009-03-03 04:44:36 +00001246 // C++ [class.union]p1:
1247 // A union shall not have base classes.
1248 if (Class->isUnion()) {
1249 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1250 << SpecifierRange;
1251 return 0;
1252 }
1253
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001254 if (EllipsisLoc.isValid() &&
1255 !TInfo->getType()->containsUnexpandedParameterPack()) {
1256 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1257 << TInfo->getTypeLoc().getSourceRange();
1258 EllipsisLoc = SourceLocation();
1259 }
Douglas Gregord777e282012-11-10 01:18:17 +00001260
1261 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1262
1263 if (BaseType->isDependentType()) {
1264 // Make sure that we don't have circular inheritance among our dependent
1265 // bases. For non-dependent bases, the check for completeness below handles
1266 // this.
1267 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1268 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1269 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001270 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001271 Diag(BaseLoc, diag::err_circular_inheritance)
1272 << BaseType << Context.getTypeDeclType(Class);
1273
1274 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1275 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1276 << BaseType;
1277
1278 return 0;
1279 }
1280 }
1281
Mike Stump1eb44332009-09-09 15:08:12 +00001282 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001283 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001284 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001285 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001286
1287 // Base specifiers must be record types.
1288 if (!BaseType->isRecordType()) {
1289 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1290 return 0;
1291 }
1292
1293 // C++ [class.union]p1:
1294 // A union shall not be used as a base class.
1295 if (BaseType->isUnionType()) {
1296 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1297 return 0;
1298 }
1299
1300 // C++ [class.derived]p2:
1301 // The class-name in a base-specifier shall not be an incompletely
1302 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001303 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001304 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001305 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001306 return 0;
John McCall572fc622010-08-17 07:23:57 +00001307 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001308
Eli Friedman1d954f62009-08-15 21:55:26 +00001309 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001310 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001312 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001313 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001314 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1315 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001316
Anders Carlsson1d209272011-03-25 14:55:14 +00001317 // C++ [class]p3:
1318 // If a class is marked final and it appears as a base-type-specifier in
1319 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001320 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001321 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1322 << CXXBaseDecl->getDeclName();
1323 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1324 << CXXBaseDecl->getDeclName();
1325 return 0;
1326 }
1327
John McCall572fc622010-08-17 07:23:57 +00001328 if (BaseDecl->isInvalidDecl())
1329 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001330
1331 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001332 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001333 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001334 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001335}
1336
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001337/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1338/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001339/// example:
1340/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001341/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001342BaseResult
John McCalld226f652010-08-21 09:40:31 +00001343Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001344 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001345 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001346 ParsedType basetype, SourceLocation BaseLoc,
1347 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001348 if (!classdecl)
1349 return true;
1350
Douglas Gregor40808ce2009-03-09 23:48:35 +00001351 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001352 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001353 if (!Class)
1354 return true;
1355
Richard Smith05321402013-02-19 23:47:15 +00001356 // We do not support any C++11 attributes on base-specifiers yet.
1357 // Diagnose any attributes we see.
1358 if (!Attributes.empty()) {
1359 for (AttributeList *Attr = Attributes.getList(); Attr;
1360 Attr = Attr->getNext()) {
1361 if (Attr->isInvalid() ||
1362 Attr->getKind() == AttributeList::IgnoredAttribute)
1363 continue;
1364 Diag(Attr->getLoc(),
1365 Attr->getKind() == AttributeList::UnknownAttribute
1366 ? diag::warn_unknown_attribute_ignored
1367 : diag::err_base_specifier_attribute)
1368 << Attr->getName();
1369 }
1370 }
1371
Nick Lewycky56062202010-07-26 16:56:01 +00001372 TypeSourceInfo *TInfo = 0;
1373 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001374
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001375 if (EllipsisLoc.isInvalid() &&
1376 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001377 UPPC_BaseType))
1378 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001379
Douglas Gregor2943aed2009-03-03 04:44:36 +00001380 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001381 Virtual, Access, TInfo,
1382 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001383 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001384 else
1385 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Douglas Gregor2943aed2009-03-03 04:44:36 +00001387 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001388}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001389
Douglas Gregor2943aed2009-03-03 04:44:36 +00001390/// \brief Performs the actual work of attaching the given base class
1391/// specifiers to a C++ class.
1392bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1393 unsigned NumBases) {
1394 if (NumBases == 0)
1395 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001396
1397 // Used to keep track of which base types we have already seen, so
1398 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001399 // that the key is always the unqualified canonical type of the base
1400 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001401 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1402
1403 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001404 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001405 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001406 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001407 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001408 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001409 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001410
1411 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1412 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001413 // C++ [class.mi]p3:
1414 // A class shall not be specified as a direct base class of a
1415 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001416 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001417 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001418 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001419 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001420
1421 // Delete the duplicate base class specifier; we're going to
1422 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001423 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001424
1425 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001426 } else {
1427 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001428 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001429 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001430 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1431 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1432 if (Class->isInterface() &&
1433 (!RD->isInterface() ||
1434 KnownBase->getAccessSpecifier() != AS_public)) {
1435 // The Microsoft extension __interface does not permit bases that
1436 // are not themselves public interfaces.
1437 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1438 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1439 << RD->getSourceRange();
1440 Invalid = true;
1441 }
1442 if (RD->hasAttr<WeakAttr>())
1443 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1444 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001445 }
1446 }
1447
1448 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001449 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001450
1451 // Delete the remaining (good) base class specifiers, since their
1452 // data has been copied into the CXXRecordDecl.
1453 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001454 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001455
1456 return Invalid;
1457}
1458
1459/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1460/// class, after checking whether there are any duplicate base
1461/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001462void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001463 unsigned NumBases) {
1464 if (!ClassDecl || !Bases || !NumBases)
1465 return;
1466
1467 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001468 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001469 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001470}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001471
Douglas Gregora8f32e02009-10-06 17:59:45 +00001472/// \brief Determine whether the type \p Derived is a C++ class that is
1473/// derived from the type \p Base.
1474bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001475 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001476 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001477
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001478 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001479 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001480 return false;
1481
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001482 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001483 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001484 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001485
1486 // If either the base or the derived type is invalid, don't try to
1487 // check whether one is derived from the other.
1488 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1489 return false;
1490
John McCall86ff3082010-02-04 22:26:26 +00001491 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1492 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001493}
1494
1495/// \brief Determine whether the type \p Derived is a C++ class that is
1496/// derived from the type \p Base.
1497bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001498 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001499 return false;
1500
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001501 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001502 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001503 return false;
1504
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001505 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001506 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001507 return false;
1508
Douglas Gregora8f32e02009-10-06 17:59:45 +00001509 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1510}
1511
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001512void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001513 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001514 assert(BasePathArray.empty() && "Base path array must be empty!");
1515 assert(Paths.isRecordingPaths() && "Must record paths!");
1516
1517 const CXXBasePath &Path = Paths.front();
1518
1519 // We first go backward and check if we have a virtual base.
1520 // FIXME: It would be better if CXXBasePath had the base specifier for
1521 // the nearest virtual base.
1522 unsigned Start = 0;
1523 for (unsigned I = Path.size(); I != 0; --I) {
1524 if (Path[I - 1].Base->isVirtual()) {
1525 Start = I - 1;
1526 break;
1527 }
1528 }
1529
1530 // Now add all bases.
1531 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001532 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001533}
1534
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001535/// \brief Determine whether the given base path includes a virtual
1536/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001537bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1538 for (CXXCastPath::const_iterator B = BasePath.begin(),
1539 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001540 B != BEnd; ++B)
1541 if ((*B)->isVirtual())
1542 return true;
1543
1544 return false;
1545}
1546
Douglas Gregora8f32e02009-10-06 17:59:45 +00001547/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1548/// conversion (where Derived and Base are class types) is
1549/// well-formed, meaning that the conversion is unambiguous (and
1550/// that all of the base classes are accessible). Returns true
1551/// and emits a diagnostic if the code is ill-formed, returns false
1552/// otherwise. Loc is the location where this routine should point to
1553/// if there is an error, and Range is the source range to highlight
1554/// if there is an error.
1555bool
1556Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001557 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001558 unsigned AmbigiousBaseConvID,
1559 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001560 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001561 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001562 // First, determine whether the path from Derived to Base is
1563 // ambiguous. This is slightly more expensive than checking whether
1564 // the Derived to Base conversion exists, because here we need to
1565 // explore multiple paths to determine if there is an ambiguity.
1566 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1567 /*DetectVirtual=*/false);
1568 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1569 assert(DerivationOkay &&
1570 "Can only be used with a derived-to-base conversion");
1571 (void)DerivationOkay;
1572
1573 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001574 if (InaccessibleBaseID) {
1575 // Check that the base class can be accessed.
1576 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1577 InaccessibleBaseID)) {
1578 case AR_inaccessible:
1579 return true;
1580 case AR_accessible:
1581 case AR_dependent:
1582 case AR_delayed:
1583 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001584 }
John McCall6b2accb2010-02-10 09:31:12 +00001585 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001586
1587 // Build a base path if necessary.
1588 if (BasePath)
1589 BuildBasePathArray(Paths, *BasePath);
1590 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001591 }
1592
1593 // We know that the derived-to-base conversion is ambiguous, and
1594 // we're going to produce a diagnostic. Perform the derived-to-base
1595 // search just one more time to compute all of the possible paths so
1596 // that we can print them out. This is more expensive than any of
1597 // the previous derived-to-base checks we've done, but at this point
1598 // performance isn't as much of an issue.
1599 Paths.clear();
1600 Paths.setRecordingPaths(true);
1601 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1602 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1603 (void)StillOkay;
1604
1605 // Build up a textual representation of the ambiguous paths, e.g.,
1606 // D -> B -> A, that will be used to illustrate the ambiguous
1607 // conversions in the diagnostic. We only print one of the paths
1608 // to each base class subobject.
1609 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1610
1611 Diag(Loc, AmbigiousBaseConvID)
1612 << Derived << Base << PathDisplayStr << Range << Name;
1613 return true;
1614}
1615
1616bool
1617Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001618 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001619 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001620 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001621 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001622 IgnoreAccess ? 0
1623 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001624 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001625 Loc, Range, DeclarationName(),
1626 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001627}
1628
1629
1630/// @brief Builds a string representing ambiguous paths from a
1631/// specific derived class to different subobjects of the same base
1632/// class.
1633///
1634/// This function builds a string that can be used in error messages
1635/// to show the different paths that one can take through the
1636/// inheritance hierarchy to go from the derived class to different
1637/// subobjects of a base class. The result looks something like this:
1638/// @code
1639/// struct D -> struct B -> struct A
1640/// struct D -> struct C -> struct A
1641/// @endcode
1642std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1643 std::string PathDisplayStr;
1644 std::set<unsigned> DisplayedPaths;
1645 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1646 Path != Paths.end(); ++Path) {
1647 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1648 // We haven't displayed a path to this particular base
1649 // class subobject yet.
1650 PathDisplayStr += "\n ";
1651 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1652 for (CXXBasePath::const_iterator Element = Path->begin();
1653 Element != Path->end(); ++Element)
1654 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1655 }
1656 }
1657
1658 return PathDisplayStr;
1659}
1660
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001661//===----------------------------------------------------------------------===//
1662// C++ class member Handling
1663//===----------------------------------------------------------------------===//
1664
Abramo Bagnara6206d532010-06-05 05:09:32 +00001665/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001666bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1667 SourceLocation ASLoc,
1668 SourceLocation ColonLoc,
1669 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001670 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001671 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001672 ASLoc, ColonLoc);
1673 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001674 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001675}
1676
Richard Smitha4b39652012-08-06 03:25:17 +00001677/// CheckOverrideControl - Check C++11 override control semantics.
1678void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001679 if (D->isInvalidDecl())
1680 return;
1681
Chris Lattner5f9e2722011-07-23 10:55:15 +00001682 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001683
Richard Smitha4b39652012-08-06 03:25:17 +00001684 // Do we know which functions this declaration might be overriding?
1685 bool OverridesAreKnown = !MD ||
1686 (!MD->getParent()->hasAnyDependentBases() &&
1687 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001688
Richard Smitha4b39652012-08-06 03:25:17 +00001689 if (!MD || !MD->isVirtual()) {
1690 if (OverridesAreKnown) {
1691 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1692 Diag(OA->getLocation(),
1693 diag::override_keyword_only_allowed_on_virtual_member_functions)
1694 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1695 D->dropAttr<OverrideAttr>();
1696 }
1697 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1698 Diag(FA->getLocation(),
1699 diag::override_keyword_only_allowed_on_virtual_member_functions)
1700 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1701 D->dropAttr<FinalAttr>();
1702 }
1703 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001704 return;
1705 }
Richard Smitha4b39652012-08-06 03:25:17 +00001706
1707 if (!OverridesAreKnown)
1708 return;
1709
1710 // C++11 [class.virtual]p5:
1711 // If a virtual function is marked with the virt-specifier override and
1712 // does not override a member function of a base class, the program is
1713 // ill-formed.
1714 bool HasOverriddenMethods =
1715 MD->begin_overridden_methods() != MD->end_overridden_methods();
1716 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1717 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1718 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001719}
1720
Richard Smitha4b39652012-08-06 03:25:17 +00001721/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001722/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001723/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001724bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1725 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001726 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001727 return false;
1728
1729 Diag(New->getLocation(), diag::err_final_function_overridden)
1730 << New->getDeclName();
1731 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1732 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001733}
1734
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001735static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001736 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1737 // FIXME: Destruction of ObjC lifetime types has side-effects.
1738 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1739 return !RD->isCompleteDefinition() ||
1740 !RD->hasTrivialDefaultConstructor() ||
1741 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001742 return false;
1743}
1744
John McCall76da55d2013-04-16 07:28:30 +00001745static AttributeList *getMSPropertyAttr(AttributeList *list) {
1746 for (AttributeList* it = list; it != 0; it = it->getNext())
1747 if (it->isDeclspecPropertyAttribute())
1748 return it;
1749 return 0;
1750}
1751
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001752/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1753/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001754/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001755/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1756/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001757NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001758Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001759 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001760 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001761 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001762 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001763 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1764 DeclarationName Name = NameInfo.getName();
1765 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001766
1767 // For anonymous bitfields, the location should point to the type.
1768 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001769 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001770
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001771 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001772
John McCall4bde1e12010-06-04 08:34:12 +00001773 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001774 assert(!DS.isFriendSpecified());
1775
Richard Smith1ab0d902011-06-25 02:28:38 +00001776 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001777
John McCalle402e722012-09-25 07:32:39 +00001778 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1779 // The Microsoft extension __interface only permits public member functions
1780 // and prohibits constructors, destructors, operators, non-public member
1781 // functions, static methods and data members.
1782 unsigned InvalidDecl;
1783 bool ShowDeclName = true;
1784 if (!isFunc)
1785 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1786 else if (AS != AS_public)
1787 InvalidDecl = 2;
1788 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1789 InvalidDecl = 3;
1790 else switch (Name.getNameKind()) {
1791 case DeclarationName::CXXConstructorName:
1792 InvalidDecl = 4;
1793 ShowDeclName = false;
1794 break;
1795
1796 case DeclarationName::CXXDestructorName:
1797 InvalidDecl = 5;
1798 ShowDeclName = false;
1799 break;
1800
1801 case DeclarationName::CXXOperatorName:
1802 case DeclarationName::CXXConversionFunctionName:
1803 InvalidDecl = 6;
1804 break;
1805
1806 default:
1807 InvalidDecl = 0;
1808 break;
1809 }
1810
1811 if (InvalidDecl) {
1812 if (ShowDeclName)
1813 Diag(Loc, diag::err_invalid_member_in_interface)
1814 << (InvalidDecl-1) << Name;
1815 else
1816 Diag(Loc, diag::err_invalid_member_in_interface)
1817 << (InvalidDecl-1) << "";
1818 return 0;
1819 }
1820 }
1821
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001822 // C++ 9.2p6: A member shall not be declared to have automatic storage
1823 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001824 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1825 // data members and cannot be applied to names declared const or static,
1826 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001827 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001828 case DeclSpec::SCS_unspecified:
1829 case DeclSpec::SCS_typedef:
1830 case DeclSpec::SCS_static:
1831 break;
1832 case DeclSpec::SCS_mutable:
1833 if (isFunc) {
1834 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Richard Smithec642442013-04-12 22:46:28 +00001836 // FIXME: It would be nicer if the keyword was ignored only for this
1837 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001838 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001839 }
1840 break;
1841 default:
1842 Diag(DS.getStorageClassSpecLoc(),
1843 diag::err_storageclass_invalid_for_member);
1844 D.getMutableDeclSpec().ClearStorageClassSpecs();
1845 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001846 }
1847
Sebastian Redl669d5d72008-11-14 23:42:31 +00001848 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1849 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001850 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001851
David Blaikie1d87fba2013-01-30 01:22:18 +00001852 if (DS.isConstexprSpecified() && isInstField) {
1853 SemaDiagnosticBuilder B =
1854 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1855 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1856 if (InitStyle == ICIS_NoInit) {
1857 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1858 D.getMutableDeclSpec().ClearConstexprSpec();
1859 const char *PrevSpec;
1860 unsigned DiagID;
1861 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1862 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001863 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001864 assert(!Failed && "Making a constexpr member const shouldn't fail");
1865 } else {
1866 B << 1;
1867 const char *PrevSpec;
1868 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001869 if (D.getMutableDeclSpec().SetStorageClassSpec(
1870 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001871 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001872 "This is the only DeclSpec that should fail to be applied");
1873 B << 1;
1874 } else {
1875 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1876 isInstField = false;
1877 }
1878 }
1879 }
1880
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001881 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001882 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001883 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001884
1885 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001886 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001887 Diag(Loc, diag::err_bad_variable_name)
1888 << Name;
1889 return 0;
1890 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001891
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001892 IdentifierInfo *II = Name.getAsIdentifierInfo();
1893
Douglas Gregorf2503652011-09-21 14:40:46 +00001894 // Member field could not be with "template" keyword.
1895 // So TemplateParameterLists should be empty in this case.
1896 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001897 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001898 if (TemplateParams->size()) {
1899 // There is no such thing as a member field template.
1900 Diag(D.getIdentifierLoc(), diag::err_template_member)
1901 << II
1902 << SourceRange(TemplateParams->getTemplateLoc(),
1903 TemplateParams->getRAngleLoc());
1904 } else {
1905 // There is an extraneous 'template<>' for this member.
1906 Diag(TemplateParams->getTemplateLoc(),
1907 diag::err_template_member_noparams)
1908 << II
1909 << SourceRange(TemplateParams->getTemplateLoc(),
1910 TemplateParams->getRAngleLoc());
1911 }
1912 return 0;
1913 }
1914
Douglas Gregor922fff22010-10-13 22:19:53 +00001915 if (SS.isSet() && !SS.isInvalid()) {
1916 // The user provided a superfluous scope specifier inside a class
1917 // definition:
1918 //
1919 // class X {
1920 // int X::member;
1921 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001922 if (DeclContext *DC = computeDeclContext(SS, false))
1923 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001924 else
1925 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1926 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001927
Douglas Gregor922fff22010-10-13 22:19:53 +00001928 SS.clear();
1929 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001930
John McCall76da55d2013-04-16 07:28:30 +00001931 AttributeList *MSPropertyAttr =
1932 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1933 if (MSPropertyAttr) {
1934 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1935 BitWidth, InitStyle, AS, MSPropertyAttr);
1936 isInstField = false;
1937 } else {
1938 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1939 BitWidth, InitStyle, AS);
1940 }
Chris Lattner6f8ce142009-03-05 23:03:49 +00001941 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001942 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001943 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001944
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001945 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001946 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001947 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001948 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001949
1950 // Non-instance-fields can't have a bitfield.
1951 if (BitWidth) {
1952 if (Member->isInvalidDecl()) {
1953 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001954 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001955 // C++ 9.6p3: A bit-field shall not be a static member.
1956 // "static member 'A' cannot be a bit-field"
1957 Diag(Loc, diag::err_static_not_bitfield)
1958 << Name << BitWidth->getSourceRange();
1959 } else if (isa<TypedefDecl>(Member)) {
1960 // "typedef member 'x' cannot be a bit-field"
1961 Diag(Loc, diag::err_typedef_not_bitfield)
1962 << Name << BitWidth->getSourceRange();
1963 } else {
1964 // A function typedef ("typedef int f(); f a;").
1965 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1966 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001967 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001968 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001969 }
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Chris Lattner8b963ef2009-03-05 23:01:03 +00001971 BitWidth = 0;
1972 Member->setInvalidDecl();
1973 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001974
1975 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Douglas Gregor37b372b2009-08-20 22:52:58 +00001977 // If we have declared a member function template, set the access of the
1978 // templated declaration as well.
1979 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1980 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001981 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001982
Richard Smitha4b39652012-08-06 03:25:17 +00001983 if (VS.isOverrideSpecified())
1984 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1985 if (VS.isFinalSpecified())
1986 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001987
Douglas Gregorf5251602011-03-08 17:10:18 +00001988 if (VS.getLastLocation().isValid()) {
1989 // Update the end location of a method that has a virt-specifiers.
1990 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1991 MD->setRangeEnd(VS.getLastLocation());
1992 }
Richard Smitha4b39652012-08-06 03:25:17 +00001993
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001994 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001995
Douglas Gregor10bd3682008-11-17 22:58:34 +00001996 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001997
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001998 if (isInstField) {
1999 FieldDecl *FD = cast<FieldDecl>(Member);
2000 FieldCollector->Add(FD);
2001
2002 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2003 FD->getLocation())
2004 != DiagnosticsEngine::Ignored) {
2005 // Remember all explicit private FieldDecls that have a name, no side
2006 // effects and are not part of a dependent type declaration.
2007 if (!FD->isImplicit() && FD->getDeclName() &&
2008 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002009 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002010 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002011 !InitializationHasSideEffects(*FD))
2012 UnusedPrivateFields.insert(FD);
2013 }
2014 }
2015
John McCalld226f652010-08-21 09:40:31 +00002016 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002017}
2018
Hans Wennborg471f9852012-09-18 15:58:06 +00002019namespace {
2020 class UninitializedFieldVisitor
2021 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2022 Sema &S;
2023 ValueDecl *VD;
2024 public:
2025 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2026 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002027 S(S) {
2028 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2029 this->VD = IFD->getAnonField();
2030 else
2031 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002032 }
2033
2034 void HandleExpr(Expr *E) {
2035 if (!E) return;
2036
2037 // Expressions like x(x) sometimes lack the surrounding expressions
2038 // but need to be checked anyways.
2039 HandleValue(E);
2040 Visit(E);
2041 }
2042
2043 void HandleValue(Expr *E) {
2044 E = E->IgnoreParens();
2045
2046 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2047 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002048 return;
2049
2050 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2051 // or union.
2052 MemberExpr *FieldME = ME;
2053
Hans Wennborg471f9852012-09-18 15:58:06 +00002054 Expr *Base = E;
2055 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002056 ME = cast<MemberExpr>(Base);
2057
2058 if (isa<VarDecl>(ME->getMemberDecl()))
2059 return;
2060
2061 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2062 if (!FD->isAnonymousStructOrUnion())
2063 FieldME = ME;
2064
Hans Wennborg471f9852012-09-18 15:58:06 +00002065 Base = ME->getBase();
2066 }
2067
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002068 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002069 unsigned diag = VD->getType()->isReferenceType()
2070 ? diag::warn_reference_field_is_uninit
2071 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002072 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002073 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002074 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002075 }
2076
2077 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2078 HandleValue(CO->getTrueExpr());
2079 HandleValue(CO->getFalseExpr());
2080 return;
2081 }
2082
2083 if (BinaryConditionalOperator *BCO =
2084 dyn_cast<BinaryConditionalOperator>(E)) {
2085 HandleValue(BCO->getCommon());
2086 HandleValue(BCO->getFalseExpr());
2087 return;
2088 }
2089
2090 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2091 switch (BO->getOpcode()) {
2092 default:
2093 return;
2094 case(BO_PtrMemD):
2095 case(BO_PtrMemI):
2096 HandleValue(BO->getLHS());
2097 return;
2098 case(BO_Comma):
2099 HandleValue(BO->getRHS());
2100 return;
2101 }
2102 }
2103 }
2104
2105 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2106 if (E->getCastKind() == CK_LValueToRValue)
2107 HandleValue(E->getSubExpr());
2108
2109 Inherited::VisitImplicitCastExpr(E);
2110 }
2111
2112 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2113 Expr *Callee = E->getCallee();
2114 if (isa<MemberExpr>(Callee))
2115 HandleValue(Callee);
2116
2117 Inherited::VisitCXXMemberCallExpr(E);
2118 }
2119 };
2120 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2121 ValueDecl *VD) {
2122 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2123 }
2124} // namespace
2125
Richard Smith7a614d82011-06-11 17:19:42 +00002126/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002127/// in-class initializer for a non-static C++ class member, and after
2128/// instantiating an in-class initializer in a class template. Such actions
2129/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002130void
Richard Smithca523302012-06-10 03:12:00 +00002131Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002132 Expr *InitExpr) {
2133 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002134 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2135 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002136
2137 if (!InitExpr) {
2138 FD->setInvalidDecl();
2139 FD->removeInClassInitializer();
2140 return;
2141 }
2142
Peter Collingbournefef21892011-10-23 18:59:44 +00002143 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2144 FD->setInvalidDecl();
2145 FD->removeInClassInitializer();
2146 return;
2147 }
2148
Hans Wennborg471f9852012-09-18 15:58:06 +00002149 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2150 != DiagnosticsEngine::Ignored) {
2151 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2152 }
2153
Richard Smith7a614d82011-06-11 17:19:42 +00002154 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002155 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00002156 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002157 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00002158 << /*at end of ctor*/1 << InitExpr->getSourceRange();
2159 }
Sebastian Redl33deb352012-02-22 10:50:08 +00002160 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002161 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002162 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002163 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002164 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2165 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002166 if (Init.isInvalid()) {
2167 FD->setInvalidDecl();
2168 return;
2169 }
Richard Smith7a614d82011-06-11 17:19:42 +00002170 }
2171
Richard Smith41956372013-01-14 22:39:08 +00002172 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002173 // The initialization of each base and member constitutes a
2174 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002175 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002176 if (Init.isInvalid()) {
2177 FD->setInvalidDecl();
2178 return;
2179 }
2180
2181 InitExpr = Init.release();
2182
2183 FD->setInClassInitializer(InitExpr);
2184}
2185
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002186/// \brief Find the direct and/or virtual base specifiers that
2187/// correspond to the given base type, for use in base initialization
2188/// within a constructor.
2189static bool FindBaseInitializer(Sema &SemaRef,
2190 CXXRecordDecl *ClassDecl,
2191 QualType BaseType,
2192 const CXXBaseSpecifier *&DirectBaseSpec,
2193 const CXXBaseSpecifier *&VirtualBaseSpec) {
2194 // First, check for a direct base class.
2195 DirectBaseSpec = 0;
2196 for (CXXRecordDecl::base_class_const_iterator Base
2197 = ClassDecl->bases_begin();
2198 Base != ClassDecl->bases_end(); ++Base) {
2199 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2200 // We found a direct base of this type. That's what we're
2201 // initializing.
2202 DirectBaseSpec = &*Base;
2203 break;
2204 }
2205 }
2206
2207 // Check for a virtual base class.
2208 // FIXME: We might be able to short-circuit this if we know in advance that
2209 // there are no virtual bases.
2210 VirtualBaseSpec = 0;
2211 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2212 // We haven't found a base yet; search the class hierarchy for a
2213 // virtual base class.
2214 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2215 /*DetectVirtual=*/false);
2216 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2217 BaseType, Paths)) {
2218 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2219 Path != Paths.end(); ++Path) {
2220 if (Path->back().Base->isVirtual()) {
2221 VirtualBaseSpec = Path->back().Base;
2222 break;
2223 }
2224 }
2225 }
2226 }
2227
2228 return DirectBaseSpec || VirtualBaseSpec;
2229}
2230
Sebastian Redl6df65482011-09-24 17:48:25 +00002231/// \brief Handle a C++ member initializer using braced-init-list syntax.
2232MemInitResult
2233Sema::ActOnMemInitializer(Decl *ConstructorD,
2234 Scope *S,
2235 CXXScopeSpec &SS,
2236 IdentifierInfo *MemberOrBase,
2237 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002238 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002239 SourceLocation IdLoc,
2240 Expr *InitList,
2241 SourceLocation EllipsisLoc) {
2242 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002243 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002244 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002245}
2246
2247/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002248MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002249Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002250 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002251 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002252 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002253 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002254 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002255 SourceLocation IdLoc,
2256 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002257 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002258 SourceLocation RParenLoc,
2259 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002260 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002261 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002262 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002263 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002264}
2265
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002266namespace {
2267
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002268// Callback to only accept typo corrections that can be a valid C++ member
2269// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002270class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2271 public:
2272 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2273 : ClassDecl(ClassDecl) {}
2274
2275 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2276 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2277 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2278 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2279 else
2280 return isa<TypeDecl>(ND);
2281 }
2282 return false;
2283 }
2284
2285 private:
2286 CXXRecordDecl *ClassDecl;
2287};
2288
2289}
2290
Sebastian Redl6df65482011-09-24 17:48:25 +00002291/// \brief Handle a C++ member initializer.
2292MemInitResult
2293Sema::BuildMemInitializer(Decl *ConstructorD,
2294 Scope *S,
2295 CXXScopeSpec &SS,
2296 IdentifierInfo *MemberOrBase,
2297 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002298 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002299 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002300 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002301 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002302 if (!ConstructorD)
2303 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002305 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002306
2307 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002308 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002309 if (!Constructor) {
2310 // The user wrote a constructor initializer on a function that is
2311 // not a C++ constructor. Ignore the error for now, because we may
2312 // have more member initializers coming; we'll diagnose it just
2313 // once in ActOnMemInitializers.
2314 return true;
2315 }
2316
2317 CXXRecordDecl *ClassDecl = Constructor->getParent();
2318
2319 // C++ [class.base.init]p2:
2320 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002321 // constructor's class and, if not found in that scope, are looked
2322 // up in the scope containing the constructor's definition.
2323 // [Note: if the constructor's class contains a member with the
2324 // same name as a direct or virtual base class of the class, a
2325 // mem-initializer-id naming the member or base class and composed
2326 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002327 // mem-initializer-id for the hidden base class may be specified
2328 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002329 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002330 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002331 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002332 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002333 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002334 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002335 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2336 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002337 if (EllipsisLoc.isValid())
2338 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002339 << MemberOrBase
2340 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002341
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002342 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002343 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002344 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002345 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002346 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002347 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002348 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002349
2350 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002351 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002352 } else if (DS.getTypeSpecType() == TST_decltype) {
2353 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002354 } else {
2355 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2356 LookupParsedName(R, S, &SS);
2357
2358 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2359 if (!TyD) {
2360 if (R.isAmbiguous()) return true;
2361
John McCallfd225442010-04-09 19:01:14 +00002362 // We don't want access-control diagnostics here.
2363 R.suppressDiagnostics();
2364
Douglas Gregor7a886e12010-01-19 06:46:48 +00002365 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2366 bool NotUnknownSpecialization = false;
2367 DeclContext *DC = computeDeclContext(SS, false);
2368 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2369 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2370
2371 if (!NotUnknownSpecialization) {
2372 // When the scope specifier can refer to a member of an unknown
2373 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002374 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2375 SS.getWithLocInContext(Context),
2376 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002377 if (BaseType.isNull())
2378 return true;
2379
Douglas Gregor7a886e12010-01-19 06:46:48 +00002380 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002381 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002382 }
2383 }
2384
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002385 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002386 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002387 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002388 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002389 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002390 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002391 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2392 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002393 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002394 // We have found a non-static data member with a similar
2395 // name to what was typed; complain and initialize that
2396 // member.
2397 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2398 << MemberOrBase << true << CorrectedQuotedStr
2399 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2400 Diag(Member->getLocation(), diag::note_previous_decl)
2401 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002402
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002403 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002404 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002405 const CXXBaseSpecifier *DirectBaseSpec;
2406 const CXXBaseSpecifier *VirtualBaseSpec;
2407 if (FindBaseInitializer(*this, ClassDecl,
2408 Context.getTypeDeclType(Type),
2409 DirectBaseSpec, VirtualBaseSpec)) {
2410 // We have found a direct or virtual base class with a
2411 // similar name to what was typed; complain and initialize
2412 // that base class.
2413 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002414 << MemberOrBase << false << CorrectedQuotedStr
2415 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002416
2417 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2418 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002419 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002420 diag::note_base_class_specified_here)
2421 << BaseSpec->getType()
2422 << BaseSpec->getSourceRange();
2423
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002424 TyD = Type;
2425 }
2426 }
2427 }
2428
Douglas Gregor7a886e12010-01-19 06:46:48 +00002429 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002430 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002431 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002432 return true;
2433 }
John McCall2b194412009-12-21 10:41:20 +00002434 }
2435
Douglas Gregor7a886e12010-01-19 06:46:48 +00002436 if (BaseType.isNull()) {
2437 BaseType = Context.getTypeDeclType(TyD);
2438 if (SS.isSet()) {
2439 NestedNameSpecifier *Qualifier =
2440 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002441
Douglas Gregor7a886e12010-01-19 06:46:48 +00002442 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002443 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002444 }
John McCall2b194412009-12-21 10:41:20 +00002445 }
2446 }
Mike Stump1eb44332009-09-09 15:08:12 +00002447
John McCalla93c9342009-12-07 02:54:59 +00002448 if (!TInfo)
2449 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002450
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002451 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002452}
2453
Chandler Carruth81c64772011-09-03 01:14:15 +00002454/// Checks a member initializer expression for cases where reference (or
2455/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002456static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2457 Expr *Init,
2458 SourceLocation IdLoc) {
2459 QualType MemberTy = Member->getType();
2460
2461 // We only handle pointers and references currently.
2462 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2463 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2464 return;
2465
2466 const bool IsPointer = MemberTy->isPointerType();
2467 if (IsPointer) {
2468 if (const UnaryOperator *Op
2469 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2470 // The only case we're worried about with pointers requires taking the
2471 // address.
2472 if (Op->getOpcode() != UO_AddrOf)
2473 return;
2474
2475 Init = Op->getSubExpr();
2476 } else {
2477 // We only handle address-of expression initializers for pointers.
2478 return;
2479 }
2480 }
2481
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002482 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2483 // Taking the address of a temporary will be diagnosed as a hard error.
2484 if (IsPointer)
2485 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002486
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002487 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2488 << Member << Init->getSourceRange();
2489 } else if (const DeclRefExpr *DRE
2490 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2491 // We only warn when referring to a non-reference parameter declaration.
2492 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2493 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002494 return;
2495
2496 S.Diag(Init->getExprLoc(),
2497 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2498 : diag::warn_bind_ref_member_to_parameter)
2499 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002500 } else {
2501 // Other initializers are fine.
2502 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002503 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002504
2505 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2506 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002507}
2508
John McCallf312b1e2010-08-26 23:41:50 +00002509MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002510Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002511 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002512 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2513 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2514 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002515 "Member must be a FieldDecl or IndirectFieldDecl");
2516
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002517 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002518 return true;
2519
Douglas Gregor464b2f02010-11-05 22:21:31 +00002520 if (Member->isInvalidDecl())
2521 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002522
John McCallb4190042009-11-04 23:02:40 +00002523 // Diagnose value-uses of fields to initialize themselves, e.g.
2524 // foo(foo)
2525 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002526 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002527 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002528 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002529 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002530 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002531 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002532 } else {
2533 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002534 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002535 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002536
Richard Trieude5e75c2012-06-14 23:11:34 +00002537 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2538 != DiagnosticsEngine::Ignored)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002539 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieude5e75c2012-06-14 23:11:34 +00002540 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002541 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002542 // initializing the i'th field, throw a warning if any of the >= i'th
2543 // fields are used, as they are not yet initialized.
2544 // Right now we are only handling the case where the i'th field uses
2545 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002546 // Also need to take into account that some fields may be initialized by
2547 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002548 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002549
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002550 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002551
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002552 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002553 // Can't check initialization for a member of dependent type or when
2554 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002555 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002556 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002557 bool InitList = false;
2558 if (isa<InitListExpr>(Init)) {
2559 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002560 Args = Init;
Sebastian Redl772291a2012-02-19 16:31:05 +00002561
2562 if (isStdInitializerList(Member->getType(), 0)) {
2563 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2564 << /*at end of ctor*/1 << InitRange;
2565 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002566 }
2567
Chandler Carruth894aed92010-12-06 09:23:57 +00002568 // Initialize the member.
2569 InitializedEntity MemberEntity =
2570 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2571 : InitializedEntity::InitializeMember(IndirectMember, 0);
2572 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002573 InitList ? InitializationKind::CreateDirectList(IdLoc)
2574 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2575 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002576
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002577 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2578 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002579 if (MemberInit.isInvalid())
2580 return true;
2581
Richard Smith41956372013-01-14 22:39:08 +00002582 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002583 // The initialization of each base and member constitutes a
2584 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002585 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002586 if (MemberInit.isInvalid())
2587 return true;
2588
Richard Smithc83c2302012-12-19 01:39:02 +00002589 Init = MemberInit.get();
2590 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002591 }
2592
Chandler Carruth894aed92010-12-06 09:23:57 +00002593 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002594 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2595 InitRange.getBegin(), Init,
2596 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002597 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002598 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2599 InitRange.getBegin(), Init,
2600 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002601 }
Eli Friedman59c04372009-07-29 19:44:27 +00002602}
2603
John McCallf312b1e2010-08-26 23:41:50 +00002604MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002605Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002606 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002607 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002608 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002609 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002610 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002611 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002612
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002613 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002614 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002615 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2616 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002617 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002618 }
2619
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002620 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002621 // Initialize the object.
2622 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2623 QualType(ClassDecl->getTypeForDecl(), 0));
2624 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002625 InitList ? InitializationKind::CreateDirectList(NameLoc)
2626 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2627 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002628 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002629 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002630 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002631 if (DelegationInit.isInvalid())
2632 return true;
2633
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002634 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2635 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002636
Richard Smith41956372013-01-14 22:39:08 +00002637 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002638 // The initialization of each base and member constitutes a
2639 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002640 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2641 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002642 if (DelegationInit.isInvalid())
2643 return true;
2644
Eli Friedmand21016f2012-05-19 23:35:23 +00002645 // If we are in a dependent context, template instantiation will
2646 // perform this type-checking again. Just save the arguments that we
2647 // received in a ParenListExpr.
2648 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2649 // of the information that we have about the base
2650 // initializer. However, deconstructing the ASTs is a dicey process,
2651 // and this approach is far more likely to get the corner cases right.
2652 if (CurContext->isDependentContext())
2653 DelegationInit = Owned(Init);
2654
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002655 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002656 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002657 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002658}
2659
2660MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002661Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002662 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002663 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002664 SourceLocation BaseLoc
2665 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002666
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002667 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2668 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2669 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2670
2671 // C++ [class.base.init]p2:
2672 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002673 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002674 // of that class, the mem-initializer is ill-formed. A
2675 // mem-initializer-list can initialize a base class using any
2676 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002677 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002678
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002679 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002680 if (EllipsisLoc.isValid()) {
2681 // This is a pack expansion.
2682 if (!BaseType->containsUnexpandedParameterPack()) {
2683 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002684 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002685
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002686 EllipsisLoc = SourceLocation();
2687 }
2688 } else {
2689 // Check for any unexpanded parameter packs.
2690 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2691 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002692
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002693 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002694 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002695 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002696
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002697 // Check for direct and virtual base classes.
2698 const CXXBaseSpecifier *DirectBaseSpec = 0;
2699 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2700 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002701 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2702 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002703 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002704
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002705 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2706 VirtualBaseSpec);
2707
2708 // C++ [base.class.init]p2:
2709 // Unless the mem-initializer-id names a nonstatic data member of the
2710 // constructor's class or a direct or virtual base of that class, the
2711 // mem-initializer is ill-formed.
2712 if (!DirectBaseSpec && !VirtualBaseSpec) {
2713 // If the class has any dependent bases, then it's possible that
2714 // one of those types will resolve to the same type as
2715 // BaseType. Therefore, just treat this as a dependent base
2716 // class initialization. FIXME: Should we try to check the
2717 // initialization anyway? It seems odd.
2718 if (ClassDecl->hasAnyDependentBases())
2719 Dependent = true;
2720 else
2721 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2722 << BaseType << Context.getTypeDeclType(ClassDecl)
2723 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2724 }
2725 }
2726
2727 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002728 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Sebastian Redl6df65482011-09-24 17:48:25 +00002730 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2731 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002732 InitRange.getBegin(), Init,
2733 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002734 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002735
2736 // C++ [base.class.init]p2:
2737 // If a mem-initializer-id is ambiguous because it designates both
2738 // a direct non-virtual base class and an inherited virtual base
2739 // class, the mem-initializer is ill-formed.
2740 if (DirectBaseSpec && VirtualBaseSpec)
2741 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002742 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002743
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002744 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002745 if (!BaseSpec)
2746 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2747
2748 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002749 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002750 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002751 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002752 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002753 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002754 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002755
2756 InitializedEntity BaseEntity =
2757 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2758 InitializationKind Kind =
2759 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2760 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2761 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002762 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2763 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002764 if (BaseInit.isInvalid())
2765 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002766
Richard Smith41956372013-01-14 22:39:08 +00002767 // C++11 [class.base.init]p7:
2768 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002769 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002770 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002771 if (BaseInit.isInvalid())
2772 return true;
2773
2774 // If we are in a dependent context, template instantiation will
2775 // perform this type-checking again. Just save the arguments that we
2776 // received in a ParenListExpr.
2777 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2778 // of the information that we have about the base
2779 // initializer. However, deconstructing the ASTs is a dicey process,
2780 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002781 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002782 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002783
Sean Huntcbb67482011-01-08 20:30:50 +00002784 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002785 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002786 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002787 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002788 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002789}
2790
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002791// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002792static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2793 if (T.isNull()) T = E->getType();
2794 QualType TargetType = SemaRef.BuildReferenceType(
2795 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002796 SourceLocation ExprLoc = E->getLocStart();
2797 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2798 TargetType, ExprLoc);
2799
2800 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2801 SourceRange(ExprLoc, ExprLoc),
2802 E->getSourceRange()).take();
2803}
2804
Anders Carlssone5ef7402010-04-23 03:10:23 +00002805/// ImplicitInitializerKind - How an implicit base or member initializer should
2806/// initialize its base or member.
2807enum ImplicitInitializerKind {
2808 IIK_Default,
2809 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002810 IIK_Move,
2811 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002812};
2813
Anders Carlssondefefd22010-04-23 02:00:02 +00002814static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002815BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002816 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002817 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002818 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002819 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002820 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002821 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2822 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002823
John McCall60d7b3a2010-08-24 06:29:42 +00002824 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002825
2826 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002827 case IIK_Inherit: {
2828 const CXXRecordDecl *Inherited =
2829 Constructor->getInheritedConstructor()->getParent();
2830 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2831 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2832 // C++11 [class.inhctor]p8:
2833 // Each expression in the expression-list is of the form
2834 // static_cast<T&&>(p), where p is the name of the corresponding
2835 // constructor parameter and T is the declared type of p.
2836 SmallVector<Expr*, 16> Args;
2837 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2838 ParmVarDecl *PD = Constructor->getParamDecl(I);
2839 ExprResult ArgExpr =
2840 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2841 VK_LValue, SourceLocation());
2842 if (ArgExpr.isInvalid())
2843 return true;
2844 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2845 }
2846
2847 InitializationKind InitKind = InitializationKind::CreateDirect(
2848 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002849 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002850 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2851 break;
2852 }
2853 }
2854 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002855 case IIK_Default: {
2856 InitializationKind InitKind
2857 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002858 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2859 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002860 break;
2861 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002862
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002863 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002864 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002865 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002866 ParmVarDecl *Param = Constructor->getParamDecl(0);
2867 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002868
Anders Carlssone5ef7402010-04-23 03:10:23 +00002869 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002870 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002871 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002872 Constructor->getLocation(), ParamType,
2873 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002874
Eli Friedman5f2987c2012-02-02 03:46:19 +00002875 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2876
Anders Carlssonc7957502010-04-24 22:02:54 +00002877 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002878 QualType ArgTy =
2879 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2880 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002881
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002882 if (Moving) {
2883 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2884 }
2885
John McCallf871d0c2010-08-07 06:22:56 +00002886 CXXCastPath BasePath;
2887 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002888 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2889 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002890 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002891 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002892
Anders Carlssone5ef7402010-04-23 03:10:23 +00002893 InitializationKind InitKind
2894 = InitializationKind::CreateDirect(Constructor->getLocation(),
2895 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002896 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2897 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002898 break;
2899 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002900 }
John McCall9ae2f072010-08-23 23:25:46 +00002901
Douglas Gregor53c374f2010-12-07 00:41:46 +00002902 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002903 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002904 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002905
Anders Carlssondefefd22010-04-23 02:00:02 +00002906 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002907 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002908 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2909 SourceLocation()),
2910 BaseSpec->isVirtual(),
2911 SourceLocation(),
2912 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002913 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002914 SourceLocation());
2915
Anders Carlssondefefd22010-04-23 02:00:02 +00002916 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002917}
2918
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002919static bool RefersToRValueRef(Expr *MemRef) {
2920 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2921 return Referenced->getType()->isRValueReferenceType();
2922}
2923
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002924static bool
2925BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002926 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002927 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002928 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002929 if (Field->isInvalidDecl())
2930 return true;
2931
Chandler Carruthf186b542010-06-29 23:50:44 +00002932 SourceLocation Loc = Constructor->getLocation();
2933
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002934 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2935 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002936 ParmVarDecl *Param = Constructor->getParamDecl(0);
2937 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002938
2939 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002940 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2941 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002942
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002943 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002944 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002945 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002946 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002947
Eli Friedman5f2987c2012-02-02 03:46:19 +00002948 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2949
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002950 if (Moving) {
2951 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2952 }
2953
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002954 // Build a reference to this field within the parameter.
2955 CXXScopeSpec SS;
2956 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2957 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002958 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2959 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002960 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002961 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002962 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002963 ParamType, Loc,
2964 /*IsArrow=*/false,
2965 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002966 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002967 /*FirstQualifierInScope=*/0,
2968 MemberLookup,
2969 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002970 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002971 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002972
2973 // C++11 [class.copy]p15:
2974 // - if a member m has rvalue reference type T&&, it is direct-initialized
2975 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002976 if (RefersToRValueRef(CtorArg.get())) {
2977 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002978 }
2979
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002980 // When the field we are copying is an array, create index variables for
2981 // each dimension of the array. We use these index variables to subscript
2982 // the source array, and other clients (e.g., CodeGen) will perform the
2983 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002984 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002985 QualType BaseType = Field->getType();
2986 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002987 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002988 while (const ConstantArrayType *Array
2989 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002990 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002991 // Create the iteration variable for this array index.
2992 IdentifierInfo *IterationVarName = 0;
2993 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002994 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002995 llvm::raw_svector_ostream OS(Str);
2996 OS << "__i" << IndexVariables.size();
2997 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2998 }
2999 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003000 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003001 IterationVarName, SizeType,
3002 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003003 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003004 IndexVariables.push_back(IterationVar);
3005
3006 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003007 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003008 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003009 assert(!IterationVarRef.isInvalid() &&
3010 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003011 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3012 assert(!IterationVarRef.isInvalid() &&
3013 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003014
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003015 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003016 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003017 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003018 Loc);
3019 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003020 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003021
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003022 BaseType = Array->getElementType();
3023 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003024
3025 // The array subscript expression is an lvalue, which is wrong for moving.
3026 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003027 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003028
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003029 // Construct the entity that we will be initializing. For an array, this
3030 // will be first element in the array, which may require several levels
3031 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003032 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003033 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003034 if (Indirect)
3035 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3036 else
3037 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003038 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3039 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3040 0,
3041 Entities.back()));
3042
3043 // Direct-initialize to use the copy constructor.
3044 InitializationKind InitKind =
3045 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3046
Sebastian Redl74e611a2011-09-04 18:14:28 +00003047 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003048 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003049
John McCall60d7b3a2010-08-24 06:29:42 +00003050 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003051 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003052 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003053 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003054 if (MemberInit.isInvalid())
3055 return true;
3056
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003057 if (Indirect) {
3058 assert(IndexVariables.size() == 0 &&
3059 "Indirect field improperly initialized");
3060 CXXMemberInit
3061 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3062 Loc, Loc,
3063 MemberInit.takeAs<Expr>(),
3064 Loc);
3065 } else
3066 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3067 Loc, MemberInit.takeAs<Expr>(),
3068 Loc,
3069 IndexVariables.data(),
3070 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003071 return false;
3072 }
3073
Richard Smith07b0fdc2013-03-18 21:12:30 +00003074 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3075 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003076
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003077 QualType FieldBaseElementType =
3078 SemaRef.Context.getBaseElementType(Field->getType());
3079
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003080 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003081 InitializedEntity InitEntity
3082 = Indirect? InitializedEntity::InitializeMember(Indirect)
3083 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003084 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003085 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003086
3087 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3088 ExprResult MemberInit =
3089 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003090
Douglas Gregor53c374f2010-12-07 00:41:46 +00003091 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003092 if (MemberInit.isInvalid())
3093 return true;
3094
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003095 if (Indirect)
3096 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3097 Indirect, Loc,
3098 Loc,
3099 MemberInit.get(),
3100 Loc);
3101 else
3102 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3103 Field, Loc, Loc,
3104 MemberInit.get(),
3105 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003106 return false;
3107 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003108
Sean Hunt1f2f3842011-05-17 00:19:05 +00003109 if (!Field->getParent()->isUnion()) {
3110 if (FieldBaseElementType->isReferenceType()) {
3111 SemaRef.Diag(Constructor->getLocation(),
3112 diag::err_uninitialized_member_in_ctor)
3113 << (int)Constructor->isImplicit()
3114 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3115 << 0 << Field->getDeclName();
3116 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3117 return true;
3118 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003119
Sean Hunt1f2f3842011-05-17 00:19:05 +00003120 if (FieldBaseElementType.isConstQualified()) {
3121 SemaRef.Diag(Constructor->getLocation(),
3122 diag::err_uninitialized_member_in_ctor)
3123 << (int)Constructor->isImplicit()
3124 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3125 << 1 << Field->getDeclName();
3126 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3127 return true;
3128 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003129 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003130
David Blaikie4e4d0842012-03-11 07:00:24 +00003131 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003132 FieldBaseElementType->isObjCRetainableType() &&
3133 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3134 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003135 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003136 // Default-initialize Objective-C pointers to NULL.
3137 CXXMemberInit
3138 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3139 Loc, Loc,
3140 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3141 Loc);
3142 return false;
3143 }
3144
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003145 // Nothing to initialize.
3146 CXXMemberInit = 0;
3147 return false;
3148}
John McCallf1860e52010-05-20 23:23:51 +00003149
3150namespace {
3151struct BaseAndFieldInfo {
3152 Sema &S;
3153 CXXConstructorDecl *Ctor;
3154 bool AnyErrorsInInits;
3155 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003156 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003157 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003158
3159 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3160 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003161 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3162 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003163 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003164 else if (Generated && Ctor->isMoveConstructor())
3165 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003166 else if (Ctor->getInheritedConstructor())
3167 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003168 else
3169 IIK = IIK_Default;
3170 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003171
3172 bool isImplicitCopyOrMove() const {
3173 switch (IIK) {
3174 case IIK_Copy:
3175 case IIK_Move:
3176 return true;
3177
3178 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003179 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003180 return false;
3181 }
David Blaikie30263482012-01-20 21:50:17 +00003182
3183 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003184 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003185
3186 bool addFieldInitializer(CXXCtorInitializer *Init) {
3187 AllToInit.push_back(Init);
3188
3189 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003190 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003191 S.UnusedPrivateFields.remove(Init->getAnyMember());
3192
3193 return false;
3194 }
John McCallf1860e52010-05-20 23:23:51 +00003195};
3196}
3197
Richard Smitha4950662011-09-19 13:34:43 +00003198/// \brief Determine whether the given indirect field declaration is somewhere
3199/// within an anonymous union.
3200static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3201 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3202 CEnd = F->chain_end();
3203 C != CEnd; ++C)
3204 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3205 if (Record->isUnion())
3206 return true;
3207
3208 return false;
3209}
3210
Douglas Gregorddb21472011-11-02 23:04:16 +00003211/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3212/// array type.
3213static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3214 if (T->isIncompleteArrayType())
3215 return true;
3216
3217 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3218 if (!ArrayT->getSize())
3219 return true;
3220
3221 T = ArrayT->getElementType();
3222 }
3223
3224 return false;
3225}
3226
Richard Smith7a614d82011-06-11 17:19:42 +00003227static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003228 FieldDecl *Field,
3229 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003230
Chandler Carruthe861c602010-06-30 02:59:29 +00003231 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003232 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3233 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003234
Richard Smith0b8220a2012-08-07 21:30:42 +00003235 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003236 // has a brace-or-equal-initializer, the entity is initialized as specified
3237 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003238 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003239 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3240 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003241 CXXCtorInitializer *Init;
3242 if (Indirect)
3243 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3244 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003245 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003246 SourceLocation());
3247 else
3248 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3249 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003250 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003251 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003252 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003253 }
3254
Richard Smithc115f632011-09-18 11:14:50 +00003255 // Don't build an implicit initializer for union members if none was
3256 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003257 if (Field->getParent()->isUnion() ||
3258 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003259 return false;
3260
Douglas Gregorddb21472011-11-02 23:04:16 +00003261 // Don't initialize incomplete or zero-length arrays.
3262 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3263 return false;
3264
John McCallf1860e52010-05-20 23:23:51 +00003265 // Don't try to build an implicit initializer if there were semantic
3266 // errors in any of the initializers (and therefore we might be
3267 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003268 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003269 return false;
3270
Sean Huntcbb67482011-01-08 20:30:50 +00003271 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003272 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3273 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003274 return true;
John McCallf1860e52010-05-20 23:23:51 +00003275
Richard Smith0b8220a2012-08-07 21:30:42 +00003276 if (!Init)
3277 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003278
Richard Smith0b8220a2012-08-07 21:30:42 +00003279 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003280}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003281
3282bool
3283Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3284 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003285 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003286 Constructor->setNumCtorInitializers(1);
3287 CXXCtorInitializer **initializer =
3288 new (Context) CXXCtorInitializer*[1];
3289 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3290 Constructor->setCtorInitializers(initializer);
3291
Sean Huntb76af9c2011-05-03 23:05:34 +00003292 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003293 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003294 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3295 }
3296
Sean Huntc1598702011-05-05 00:05:47 +00003297 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003298
Sean Hunt059ce0d2011-05-01 07:04:31 +00003299 return false;
3300}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003301
David Blaikie93c86172013-01-17 05:26:25 +00003302bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3303 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003304 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003305 // Just store the initializers as written, they will be checked during
3306 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003307 if (!Initializers.empty()) {
3308 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003309 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003310 new (Context) CXXCtorInitializer*[Initializers.size()];
3311 memcpy(baseOrMemberInitializers, Initializers.data(),
3312 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003313 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003314 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003315
3316 // Let template instantiation know whether we had errors.
3317 if (AnyErrors)
3318 Constructor->setInvalidDecl();
3319
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003320 return false;
3321 }
3322
John McCallf1860e52010-05-20 23:23:51 +00003323 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003324
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003325 // We need to build the initializer AST according to order of construction
3326 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003327 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003328 if (!ClassDecl)
3329 return true;
3330
Eli Friedman80c30da2009-11-09 19:20:36 +00003331 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003332
David Blaikie93c86172013-01-17 05:26:25 +00003333 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003334 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003335
3336 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003337 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003338 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003339 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003340 }
3341
Anders Carlsson711f34a2010-04-21 19:52:01 +00003342 // Keep track of the direct virtual bases.
3343 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3344 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3345 E = ClassDecl->bases_end(); I != E; ++I) {
3346 if (I->isVirtual())
3347 DirectVBases.insert(I);
3348 }
3349
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003350 // Push virtual bases before others.
3351 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3352 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3353
Sean Huntcbb67482011-01-08 20:30:50 +00003354 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003355 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3356 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003357 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003358 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003359 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003360 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003361 VBase, IsInheritedVirtualBase,
3362 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003363 HadError = true;
3364 continue;
3365 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003366
John McCallf1860e52010-05-20 23:23:51 +00003367 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003368 }
3369 }
Mike Stump1eb44332009-09-09 15:08:12 +00003370
John McCallf1860e52010-05-20 23:23:51 +00003371 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003372 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3373 E = ClassDecl->bases_end(); Base != E; ++Base) {
3374 // Virtuals are in the virtual base list and already constructed.
3375 if (Base->isVirtual())
3376 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003377
Sean Huntcbb67482011-01-08 20:30:50 +00003378 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003379 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3380 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003381 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003382 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003383 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003384 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003385 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003386 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003387 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003388 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003389
John McCallf1860e52010-05-20 23:23:51 +00003390 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003391 }
3392 }
Mike Stump1eb44332009-09-09 15:08:12 +00003393
John McCallf1860e52010-05-20 23:23:51 +00003394 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003395 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3396 MemEnd = ClassDecl->decls_end();
3397 Mem != MemEnd; ++Mem) {
3398 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003399 // C++ [class.bit]p2:
3400 // A declaration for a bit-field that omits the identifier declares an
3401 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3402 // initialized.
3403 if (F->isUnnamedBitfield())
3404 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003405
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003406 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003407 // handle anonymous struct/union fields based on their individual
3408 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003409 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003410 continue;
3411
3412 if (CollectFieldInitializer(*this, Info, F))
3413 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003414 continue;
3415 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003416
3417 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003418 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003419 continue;
3420
3421 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3422 if (F->getType()->isIncompleteArrayType()) {
3423 assert(ClassDecl->hasFlexibleArrayMember() &&
3424 "Incomplete array type is not valid");
3425 continue;
3426 }
3427
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003428 // Initialize each field of an anonymous struct individually.
3429 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3430 HadError = true;
3431
3432 continue;
3433 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003434 }
Mike Stump1eb44332009-09-09 15:08:12 +00003435
David Blaikie93c86172013-01-17 05:26:25 +00003436 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003437 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003438 Constructor->setNumCtorInitializers(NumInitializers);
3439 CXXCtorInitializer **baseOrMemberInitializers =
3440 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003441 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003442 NumInitializers * sizeof(CXXCtorInitializer*));
3443 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003444
John McCallef027fe2010-03-16 21:39:52 +00003445 // Constructors implicitly reference the base and member
3446 // destructors.
3447 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3448 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003449 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003450
3451 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003452}
3453
David Blaikieee000bb2013-01-17 08:49:22 +00003454static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003455 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003456 const RecordDecl *RD = RT->getDecl();
3457 if (RD->isAnonymousStructOrUnion()) {
3458 for (RecordDecl::field_iterator Field = RD->field_begin(),
3459 E = RD->field_end(); Field != E; ++Field)
3460 PopulateKeysForFields(*Field, IdealInits);
3461 return;
3462 }
Eli Friedman6347f422009-07-21 19:28:10 +00003463 }
David Blaikieee000bb2013-01-17 08:49:22 +00003464 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003465}
3466
Anders Carlssonea356fb2010-04-02 05:42:15 +00003467static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003468 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003469}
3470
Anders Carlssonea356fb2010-04-02 05:42:15 +00003471static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003472 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003473 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003474 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003475
David Blaikieee000bb2013-01-17 08:49:22 +00003476 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003477}
3478
David Blaikie93c86172013-01-17 05:26:25 +00003479static void DiagnoseBaseOrMemInitializerOrder(
3480 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3481 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003482 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003483 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003484
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003485 // Don't check initializers order unless the warning is enabled at the
3486 // location of at least one initializer.
3487 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003488 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003489 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003490 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3491 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003492 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003493 ShouldCheckOrder = true;
3494 break;
3495 }
3496 }
3497 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003498 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003499
John McCalld6ca8da2010-04-10 07:37:23 +00003500 // Build the list of bases and members in the order that they'll
3501 // actually be initialized. The explicit initializers should be in
3502 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003503 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003504
Anders Carlsson071d6102010-04-02 03:38:04 +00003505 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3506
John McCalld6ca8da2010-04-10 07:37:23 +00003507 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003508 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003509 ClassDecl->vbases_begin(),
3510 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003511 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003512
John McCalld6ca8da2010-04-10 07:37:23 +00003513 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003514 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003515 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003516 if (Base->isVirtual())
3517 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003518 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003519 }
Mike Stump1eb44332009-09-09 15:08:12 +00003520
John McCalld6ca8da2010-04-10 07:37:23 +00003521 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003522 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003523 E = ClassDecl->field_end(); Field != E; ++Field) {
3524 if (Field->isUnnamedBitfield())
3525 continue;
3526
David Blaikieee000bb2013-01-17 08:49:22 +00003527 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003528 }
3529
John McCalld6ca8da2010-04-10 07:37:23 +00003530 unsigned NumIdealInits = IdealInitKeys.size();
3531 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003532
Sean Huntcbb67482011-01-08 20:30:50 +00003533 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003534 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003535 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003536 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003537
3538 // Scan forward to try to find this initializer in the idealized
3539 // initializers list.
3540 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3541 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003542 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003543
3544 // If we didn't find this initializer, it must be because we
3545 // scanned past it on a previous iteration. That can only
3546 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003547 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003548 Sema::SemaDiagnosticBuilder D =
3549 SemaRef.Diag(PrevInit->getSourceLocation(),
3550 diag::warn_initializer_out_of_order);
3551
Francois Pichet00eb3f92010-12-04 09:14:42 +00003552 if (PrevInit->isAnyMemberInitializer())
3553 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003554 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003555 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003556
Francois Pichet00eb3f92010-12-04 09:14:42 +00003557 if (Init->isAnyMemberInitializer())
3558 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003559 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003560 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003561
3562 // Move back to the initializer's location in the ideal list.
3563 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3564 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003565 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003566
3567 assert(IdealIndex != NumIdealInits &&
3568 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003569 }
John McCalld6ca8da2010-04-10 07:37:23 +00003570
3571 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003572 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003573}
3574
John McCall3c3ccdb2010-04-10 09:28:51 +00003575namespace {
3576bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003577 CXXCtorInitializer *Init,
3578 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003579 if (!PrevInit) {
3580 PrevInit = Init;
3581 return false;
3582 }
3583
Douglas Gregordc392c12013-03-25 23:28:23 +00003584 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003585 S.Diag(Init->getSourceLocation(),
3586 diag::err_multiple_mem_initialization)
3587 << Field->getDeclName()
3588 << Init->getSourceRange();
3589 else {
John McCallf4c73712011-01-19 06:33:43 +00003590 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003591 assert(BaseClass && "neither field nor base");
3592 S.Diag(Init->getSourceLocation(),
3593 diag::err_multiple_base_initialization)
3594 << QualType(BaseClass, 0)
3595 << Init->getSourceRange();
3596 }
3597 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3598 << 0 << PrevInit->getSourceRange();
3599
3600 return true;
3601}
3602
Sean Huntcbb67482011-01-08 20:30:50 +00003603typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003604typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3605
3606bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003607 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003608 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003609 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003610 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003611 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003612
3613 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003614 if (Parent->isUnion()) {
3615 UnionEntry &En = Unions[Parent];
3616 if (En.first && En.first != Child) {
3617 S.Diag(Init->getSourceLocation(),
3618 diag::err_multiple_mem_union_initialization)
3619 << Field->getDeclName()
3620 << Init->getSourceRange();
3621 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3622 << 0 << En.second->getSourceRange();
3623 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003624 }
3625 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003626 En.first = Child;
3627 En.second = Init;
3628 }
David Blaikie6fe29652011-11-17 06:01:57 +00003629 if (!Parent->isAnonymousStructOrUnion())
3630 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003631 }
3632
3633 Child = Parent;
3634 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003635 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003636
3637 return false;
3638}
3639}
3640
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003641/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003642void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003643 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003644 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003645 bool AnyErrors) {
3646 if (!ConstructorDecl)
3647 return;
3648
3649 AdjustDeclIfTemplate(ConstructorDecl);
3650
3651 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003652 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003653
3654 if (!Constructor) {
3655 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3656 return;
3657 }
3658
John McCall3c3ccdb2010-04-10 09:28:51 +00003659 // Mapping for the duplicate initializers check.
3660 // For member initializers, this is keyed with a FieldDecl*.
3661 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003662 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003663
3664 // Mapping for the inconsistent anonymous-union initializers check.
3665 RedundantUnionMap MemberUnions;
3666
Anders Carlssonea356fb2010-04-02 05:42:15 +00003667 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003668 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003669 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003670
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003671 // Set the source order index.
3672 Init->setSourceOrder(i);
3673
Francois Pichet00eb3f92010-12-04 09:14:42 +00003674 if (Init->isAnyMemberInitializer()) {
3675 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003676 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3677 CheckRedundantUnionInit(*this, Init, MemberUnions))
3678 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003679 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003680 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3681 if (CheckRedundantInit(*this, Init, Members[Key]))
3682 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003683 } else {
3684 assert(Init->isDelegatingInitializer());
3685 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003686 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003687 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003688 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003689 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003690 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003691 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003692 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003693 // Return immediately as the initializer is set.
3694 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003695 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003696 }
3697
Anders Carlssonea356fb2010-04-02 05:42:15 +00003698 if (HadError)
3699 return;
3700
David Blaikie93c86172013-01-17 05:26:25 +00003701 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003702
David Blaikie93c86172013-01-17 05:26:25 +00003703 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003704}
3705
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003706void
John McCallef027fe2010-03-16 21:39:52 +00003707Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3708 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003709 // Ignore dependent contexts. Also ignore unions, since their members never
3710 // have destructors implicitly called.
3711 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003712 return;
John McCall58e6f342010-03-16 05:22:47 +00003713
3714 // FIXME: all the access-control diagnostics are positioned on the
3715 // field/base declaration. That's probably good; that said, the
3716 // user might reasonably want to know why the destructor is being
3717 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003718
Anders Carlsson9f853df2009-11-17 04:44:12 +00003719 // Non-static data members.
3720 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3721 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003722 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003723 if (Field->isInvalidDecl())
3724 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003725
3726 // Don't destroy incomplete or zero-length arrays.
3727 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3728 continue;
3729
Anders Carlsson9f853df2009-11-17 04:44:12 +00003730 QualType FieldType = Context.getBaseElementType(Field->getType());
3731
3732 const RecordType* RT = FieldType->getAs<RecordType>();
3733 if (!RT)
3734 continue;
3735
3736 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003737 if (FieldClassDecl->isInvalidDecl())
3738 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003739 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003740 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003741 // The destructor for an implicit anonymous union member is never invoked.
3742 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3743 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003744
Douglas Gregordb89f282010-07-01 22:47:18 +00003745 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003746 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003747 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003748 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003749 << Field->getDeclName()
3750 << FieldType);
3751
Eli Friedman5f2987c2012-02-02 03:46:19 +00003752 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003753 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003754 }
3755
John McCall58e6f342010-03-16 05:22:47 +00003756 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3757
Anders Carlsson9f853df2009-11-17 04:44:12 +00003758 // Bases.
3759 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3760 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003761 // Bases are always records in a well-formed non-dependent class.
3762 const RecordType *RT = Base->getType()->getAs<RecordType>();
3763
3764 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003765 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003766 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003767
John McCall58e6f342010-03-16 05:22:47 +00003768 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003769 // If our base class is invalid, we probably can't get its dtor anyway.
3770 if (BaseClassDecl->isInvalidDecl())
3771 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003772 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003773 continue;
John McCall58e6f342010-03-16 05:22:47 +00003774
Douglas Gregordb89f282010-07-01 22:47:18 +00003775 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003776 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003777
3778 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003779 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003780 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003781 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003782 << Base->getSourceRange(),
3783 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003784
Eli Friedman5f2987c2012-02-02 03:46:19 +00003785 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003786 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003787 }
3788
3789 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003790 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3791 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003792
3793 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003794 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003795
3796 // Ignore direct virtual bases.
3797 if (DirectVirtualBases.count(RT))
3798 continue;
3799
John McCall58e6f342010-03-16 05:22:47 +00003800 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003801 // If our base class is invalid, we probably can't get its dtor anyway.
3802 if (BaseClassDecl->isInvalidDecl())
3803 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003804 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003805 continue;
John McCall58e6f342010-03-16 05:22:47 +00003806
Douglas Gregordb89f282010-07-01 22:47:18 +00003807 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003808 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003809 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003810 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003811 << VBase->getType(),
3812 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003813
Eli Friedman5f2987c2012-02-02 03:46:19 +00003814 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003815 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003816 }
3817}
3818
John McCalld226f652010-08-21 09:40:31 +00003819void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003820 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003821 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Mike Stump1eb44332009-09-09 15:08:12 +00003823 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003824 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003825 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003826}
3827
Mike Stump1eb44332009-09-09 15:08:12 +00003828bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003829 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003830 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3831 unsigned DiagID;
3832 AbstractDiagSelID SelID;
3833
3834 public:
3835 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3836 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3837
3838 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003839 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003840 if (SelID == -1)
3841 S.Diag(Loc, DiagID) << T;
3842 else
3843 S.Diag(Loc, DiagID) << SelID << T;
3844 }
3845 } Diagnoser(DiagID, SelID);
3846
3847 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003848}
3849
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003850bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003851 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003852 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003853 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003854
Anders Carlsson11f21a02009-03-23 19:10:31 +00003855 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003856 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003857
Ted Kremenek6217b802009-07-29 21:53:49 +00003858 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003859 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003860 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003861 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003862
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003863 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003864 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003865 }
Mike Stump1eb44332009-09-09 15:08:12 +00003866
Ted Kremenek6217b802009-07-29 21:53:49 +00003867 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003868 if (!RT)
3869 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003870
John McCall86ff3082010-02-04 22:26:26 +00003871 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003872
John McCall94c3b562010-08-18 09:41:07 +00003873 // We can't answer whether something is abstract until it has a
3874 // definition. If it's currently being defined, we'll walk back
3875 // over all the declarations when we have a full definition.
3876 const CXXRecordDecl *Def = RD->getDefinition();
3877 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003878 return false;
3879
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003880 if (!RD->isAbstract())
3881 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003882
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003883 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003884 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003885
John McCall94c3b562010-08-18 09:41:07 +00003886 return true;
3887}
3888
3889void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3890 // Check if we've already emitted the list of pure virtual functions
3891 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003892 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003893 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003894
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003895 CXXFinalOverriderMap FinalOverriders;
3896 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003897
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003898 // Keep a set of seen pure methods so we won't diagnose the same method
3899 // more than once.
3900 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3901
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003902 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3903 MEnd = FinalOverriders.end();
3904 M != MEnd;
3905 ++M) {
3906 for (OverridingMethods::iterator SO = M->second.begin(),
3907 SOEnd = M->second.end();
3908 SO != SOEnd; ++SO) {
3909 // C++ [class.abstract]p4:
3910 // A class is abstract if it contains or inherits at least one
3911 // pure virtual function for which the final overrider is pure
3912 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003913
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003914 //
3915 if (SO->second.size() != 1)
3916 continue;
3917
3918 if (!SO->second.front().Method->isPure())
3919 continue;
3920
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003921 if (!SeenPureMethods.insert(SO->second.front().Method))
3922 continue;
3923
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003924 Diag(SO->second.front().Method->getLocation(),
3925 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003926 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003927 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003928 }
3929
3930 if (!PureVirtualClassDiagSet)
3931 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3932 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003933}
3934
Anders Carlsson8211eff2009-03-24 01:19:16 +00003935namespace {
John McCall94c3b562010-08-18 09:41:07 +00003936struct AbstractUsageInfo {
3937 Sema &S;
3938 CXXRecordDecl *Record;
3939 CanQualType AbstractType;
3940 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003941
John McCall94c3b562010-08-18 09:41:07 +00003942 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3943 : S(S), Record(Record),
3944 AbstractType(S.Context.getCanonicalType(
3945 S.Context.getTypeDeclType(Record))),
3946 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003947
John McCall94c3b562010-08-18 09:41:07 +00003948 void DiagnoseAbstractType() {
3949 if (Invalid) return;
3950 S.DiagnoseAbstractType(Record);
3951 Invalid = true;
3952 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003953
John McCall94c3b562010-08-18 09:41:07 +00003954 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3955};
3956
3957struct CheckAbstractUsage {
3958 AbstractUsageInfo &Info;
3959 const NamedDecl *Ctx;
3960
3961 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3962 : Info(Info), Ctx(Ctx) {}
3963
3964 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3965 switch (TL.getTypeLocClass()) {
3966#define ABSTRACT_TYPELOC(CLASS, PARENT)
3967#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003968 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003969#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003970 }
John McCall94c3b562010-08-18 09:41:07 +00003971 }
Mike Stump1eb44332009-09-09 15:08:12 +00003972
John McCall94c3b562010-08-18 09:41:07 +00003973 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3974 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3975 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003976 if (!TL.getArg(I))
3977 continue;
3978
John McCall94c3b562010-08-18 09:41:07 +00003979 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3980 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003981 }
John McCall94c3b562010-08-18 09:41:07 +00003982 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003983
John McCall94c3b562010-08-18 09:41:07 +00003984 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3985 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3986 }
Mike Stump1eb44332009-09-09 15:08:12 +00003987
John McCall94c3b562010-08-18 09:41:07 +00003988 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3989 // Visit the type parameters from a permissive context.
3990 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3991 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3992 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3993 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3994 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3995 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003996 }
John McCall94c3b562010-08-18 09:41:07 +00003997 }
Mike Stump1eb44332009-09-09 15:08:12 +00003998
John McCall94c3b562010-08-18 09:41:07 +00003999 // Visit pointee types from a permissive context.
4000#define CheckPolymorphic(Type) \
4001 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4002 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4003 }
4004 CheckPolymorphic(PointerTypeLoc)
4005 CheckPolymorphic(ReferenceTypeLoc)
4006 CheckPolymorphic(MemberPointerTypeLoc)
4007 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004008 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004009
John McCall94c3b562010-08-18 09:41:07 +00004010 /// Handle all the types we haven't given a more specific
4011 /// implementation for above.
4012 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4013 // Every other kind of type that we haven't called out already
4014 // that has an inner type is either (1) sugar or (2) contains that
4015 // inner type in some way as a subobject.
4016 if (TypeLoc Next = TL.getNextTypeLoc())
4017 return Visit(Next, Sel);
4018
4019 // If there's no inner type and we're in a permissive context,
4020 // don't diagnose.
4021 if (Sel == Sema::AbstractNone) return;
4022
4023 // Check whether the type matches the abstract type.
4024 QualType T = TL.getType();
4025 if (T->isArrayType()) {
4026 Sel = Sema::AbstractArrayType;
4027 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004028 }
John McCall94c3b562010-08-18 09:41:07 +00004029 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4030 if (CT != Info.AbstractType) return;
4031
4032 // It matched; do some magic.
4033 if (Sel == Sema::AbstractArrayType) {
4034 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4035 << T << TL.getSourceRange();
4036 } else {
4037 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4038 << Sel << T << TL.getSourceRange();
4039 }
4040 Info.DiagnoseAbstractType();
4041 }
4042};
4043
4044void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4045 Sema::AbstractDiagSelID Sel) {
4046 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4047}
4048
4049}
4050
4051/// Check for invalid uses of an abstract type in a method declaration.
4052static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4053 CXXMethodDecl *MD) {
4054 // No need to do the check on definitions, which require that
4055 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004056 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004057 return;
4058
4059 // For safety's sake, just ignore it if we don't have type source
4060 // information. This should never happen for non-implicit methods,
4061 // but...
4062 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4063 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4064}
4065
4066/// Check for invalid uses of an abstract type within a class definition.
4067static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4068 CXXRecordDecl *RD) {
4069 for (CXXRecordDecl::decl_iterator
4070 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4071 Decl *D = *I;
4072 if (D->isImplicit()) continue;
4073
4074 // Methods and method templates.
4075 if (isa<CXXMethodDecl>(D)) {
4076 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4077 } else if (isa<FunctionTemplateDecl>(D)) {
4078 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4079 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4080
4081 // Fields and static variables.
4082 } else if (isa<FieldDecl>(D)) {
4083 FieldDecl *FD = cast<FieldDecl>(D);
4084 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4085 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4086 } else if (isa<VarDecl>(D)) {
4087 VarDecl *VD = cast<VarDecl>(D);
4088 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4089 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4090
4091 // Nested classes and class templates.
4092 } else if (isa<CXXRecordDecl>(D)) {
4093 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4094 } else if (isa<ClassTemplateDecl>(D)) {
4095 CheckAbstractClassUsage(Info,
4096 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4097 }
4098 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004099}
4100
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004101/// \brief Perform semantic checks on a class definition that has been
4102/// completing, introducing implicitly-declared members, checking for
4103/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004104void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004105 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004106 return;
4107
John McCall94c3b562010-08-18 09:41:07 +00004108 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4109 AbstractUsageInfo Info(*this, Record);
4110 CheckAbstractClassUsage(Info, Record);
4111 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004112
4113 // If this is not an aggregate type and has no user-declared constructor,
4114 // complain about any non-static data members of reference or const scalar
4115 // type, since they will never get initializers.
4116 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004117 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4118 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004119 bool Complained = false;
4120 for (RecordDecl::field_iterator F = Record->field_begin(),
4121 FEnd = Record->field_end();
4122 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004123 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004124 continue;
4125
Douglas Gregor325e5932010-04-15 00:00:53 +00004126 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004127 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004128 if (!Complained) {
4129 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4130 << Record->getTagKind() << Record;
4131 Complained = true;
4132 }
4133
4134 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4135 << F->getType()->isReferenceType()
4136 << F->getDeclName();
4137 }
4138 }
4139 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004140
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004141 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004142 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004143
4144 if (Record->getIdentifier()) {
4145 // C++ [class.mem]p13:
4146 // If T is the name of a class, then each of the following shall have a
4147 // name different from T:
4148 // - every member of every anonymous union that is a member of class T.
4149 //
4150 // C++ [class.mem]p14:
4151 // In addition, if class T has a user-declared constructor (12.1), every
4152 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004153 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4154 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4155 ++I) {
4156 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004157 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4158 isa<IndirectFieldDecl>(D)) {
4159 Diag(D->getLocation(), diag::err_member_name_of_class)
4160 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004161 break;
4162 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004163 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004164 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004165
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004166 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004167 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004168 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004169 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004170 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4171 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4172 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004173
David Blaikieb6b5b972012-09-21 03:21:07 +00004174 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4175 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4176 DiagnoseAbstractType(Record);
4177 }
4178
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004179 if (!Record->isDependentType()) {
4180 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4181 MEnd = Record->method_end();
4182 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004183 // See if a method overloads virtual methods in a base
4184 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004185 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004186 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004187
4188 // Check whether the explicitly-defaulted special members are valid.
4189 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4190 CheckExplicitlyDefaultedSpecialMember(*M);
4191
4192 // For an explicitly defaulted or deleted special member, we defer
4193 // determining triviality until the class is complete. That time is now!
4194 if (!M->isImplicit() && !M->isUserProvided()) {
4195 CXXSpecialMember CSM = getSpecialMember(*M);
4196 if (CSM != CXXInvalid) {
4197 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4198
4199 // Inform the class that we've finished declaring this member.
4200 Record->finishedDefaultedOrDeletedMember(*M);
4201 }
4202 }
4203 }
4204 }
4205
4206 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4207 // function that is not a constructor declares that member function to be
4208 // const. [...] The class of which that function is a member shall be
4209 // a literal type.
4210 //
4211 // If the class has virtual bases, any constexpr members will already have
4212 // been diagnosed by the checks performed on the member declaration, so
4213 // suppress this (less useful) diagnostic.
4214 //
4215 // We delay this until we know whether an explicitly-defaulted (or deleted)
4216 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004217 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004218 !Record->isLiteral() && !Record->getNumVBases()) {
4219 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4220 MEnd = Record->method_end();
4221 M != MEnd; ++M) {
4222 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4223 switch (Record->getTemplateSpecializationKind()) {
4224 case TSK_ImplicitInstantiation:
4225 case TSK_ExplicitInstantiationDeclaration:
4226 case TSK_ExplicitInstantiationDefinition:
4227 // If a template instantiates to a non-literal type, but its members
4228 // instantiate to constexpr functions, the template is technically
4229 // ill-formed, but we allow it for sanity.
4230 continue;
4231
4232 case TSK_Undeclared:
4233 case TSK_ExplicitSpecialization:
4234 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4235 diag::err_constexpr_method_non_literal);
4236 break;
4237 }
4238
4239 // Only produce one error per class.
4240 break;
4241 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004242 }
4243 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004244
Richard Smith07b0fdc2013-03-18 21:12:30 +00004245 // Declare inheriting constructors. We do this eagerly here because:
4246 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004247 // constructors from different classes.
4248 // - The lazy declaration of the other implicit constructors is so as to not
4249 // waste space and performance on classes that are not meant to be
4250 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004251 // have inheriting constructors.
4252 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004253}
4254
Richard Smith7756afa2012-06-10 05:43:50 +00004255/// Is the special member function which would be selected to perform the
4256/// specified operation on the specified class type a constexpr constructor?
4257static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4258 Sema::CXXSpecialMember CSM,
4259 bool ConstArg) {
4260 Sema::SpecialMemberOverloadResult *SMOR =
4261 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4262 false, false, false, false);
4263 if (!SMOR || !SMOR->getMethod())
4264 // A constructor we wouldn't select can't be "involved in initializing"
4265 // anything.
4266 return true;
4267 return SMOR->getMethod()->isConstexpr();
4268}
4269
4270/// Determine whether the specified special member function would be constexpr
4271/// if it were implicitly defined.
4272static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4273 Sema::CXXSpecialMember CSM,
4274 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004275 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004276 return false;
4277
4278 // C++11 [dcl.constexpr]p4:
4279 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004280 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004281 switch (CSM) {
4282 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004283 // Since default constructor lookup is essentially trivial (and cannot
4284 // involve, for instance, template instantiation), we compute whether a
4285 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4286 //
4287 // This is important for performance; we need to know whether the default
4288 // constructor is constexpr to determine whether the type is a literal type.
4289 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4290
Richard Smith7756afa2012-06-10 05:43:50 +00004291 case Sema::CXXCopyConstructor:
4292 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004293 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004294 break;
4295
4296 case Sema::CXXCopyAssignment:
4297 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004298 if (!S.getLangOpts().CPlusPlus1y)
4299 return false;
4300 // In C++1y, we need to perform overload resolution.
4301 Ctor = false;
4302 break;
4303
Richard Smith7756afa2012-06-10 05:43:50 +00004304 case Sema::CXXDestructor:
4305 case Sema::CXXInvalid:
4306 return false;
4307 }
4308
4309 // -- if the class is a non-empty union, or for each non-empty anonymous
4310 // union member of a non-union class, exactly one non-static data member
4311 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004312 //
4313 // If we squint, this is guaranteed, since exactly one non-static data member
4314 // will be initialized (if the constructor isn't deleted), we just don't know
4315 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004316 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004317 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004318
4319 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004320 if (Ctor && ClassDecl->getNumVBases())
4321 return false;
4322
4323 // C++1y [class.copy]p26:
4324 // -- [the class] is a literal type, and
4325 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004326 return false;
4327
4328 // -- every constructor involved in initializing [...] base class
4329 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004330 // -- the assignment operator selected to copy/move each direct base
4331 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004332 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4333 BEnd = ClassDecl->bases_end();
4334 B != BEnd; ++B) {
4335 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4336 if (!BaseType) continue;
4337
4338 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4339 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4340 return false;
4341 }
4342
4343 // -- every constructor involved in initializing non-static data members
4344 // [...] shall be a constexpr constructor;
4345 // -- every non-static data member and base class sub-object shall be
4346 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004347 // -- for each non-stastic data member of X that is of class type (or array
4348 // thereof), the assignment operator selected to copy/move that member is
4349 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004350 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4351 FEnd = ClassDecl->field_end();
4352 F != FEnd; ++F) {
4353 if (F->isInvalidDecl())
4354 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004355 if (const RecordType *RecordTy =
4356 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004357 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4358 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4359 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004360 }
4361 }
4362
4363 // All OK, it's constexpr!
4364 return true;
4365}
4366
Richard Smithb9d0b762012-07-27 04:22:15 +00004367static Sema::ImplicitExceptionSpecification
4368computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4369 switch (S.getSpecialMember(MD)) {
4370 case Sema::CXXDefaultConstructor:
4371 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4372 case Sema::CXXCopyConstructor:
4373 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4374 case Sema::CXXCopyAssignment:
4375 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4376 case Sema::CXXMoveConstructor:
4377 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4378 case Sema::CXXMoveAssignment:
4379 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4380 case Sema::CXXDestructor:
4381 return S.ComputeDefaultedDtorExceptionSpec(MD);
4382 case Sema::CXXInvalid:
4383 break;
4384 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004385 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4386 "only special members have implicit exception specs");
4387 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004388}
4389
Richard Smithdd25e802012-07-30 23:48:14 +00004390static void
4391updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4392 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4393 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4394 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004395 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4396 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004397}
4398
Richard Smithb9d0b762012-07-27 04:22:15 +00004399void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4400 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4401 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4402 return;
4403
Richard Smithdd25e802012-07-30 23:48:14 +00004404 // Evaluate the exception specification.
4405 ImplicitExceptionSpecification ExceptSpec =
4406 computeImplicitExceptionSpec(*this, Loc, MD);
4407
4408 // Update the type of the special member to use it.
4409 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4410
4411 // A user-provided destructor can be defined outside the class. When that
4412 // happens, be sure to update the exception specification on both
4413 // declarations.
4414 const FunctionProtoType *CanonicalFPT =
4415 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4416 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4417 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4418 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004419}
4420
Richard Smith3003e1d2012-05-15 04:39:51 +00004421void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4422 CXXRecordDecl *RD = MD->getParent();
4423 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004424
Richard Smith3003e1d2012-05-15 04:39:51 +00004425 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4426 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004427
4428 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004429 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004430 bool First = MD == MD->getCanonicalDecl();
4431
4432 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004433
4434 // C++11 [dcl.fct.def.default]p1:
4435 // A function that is explicitly defaulted shall
4436 // -- be a special member function (checked elsewhere),
4437 // -- have the same type (except for ref-qualifiers, and except that a
4438 // copy operation can take a non-const reference) as an implicit
4439 // declaration, and
4440 // -- not have default arguments.
4441 unsigned ExpectedParams = 1;
4442 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4443 ExpectedParams = 0;
4444 if (MD->getNumParams() != ExpectedParams) {
4445 // This also checks for default arguments: a copy or move constructor with a
4446 // default argument is classified as a default constructor, and assignment
4447 // operations and destructors can't have default arguments.
4448 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4449 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004450 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004451 } else if (MD->isVariadic()) {
4452 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4453 << CSM << MD->getSourceRange();
4454 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004455 }
4456
Richard Smith3003e1d2012-05-15 04:39:51 +00004457 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004458
Richard Smith7756afa2012-06-10 05:43:50 +00004459 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004460 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004461 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004462 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004463 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004464
Richard Smith3003e1d2012-05-15 04:39:51 +00004465 QualType ReturnType = Context.VoidTy;
4466 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4467 // Check for return type matching.
4468 ReturnType = Type->getResultType();
4469 QualType ExpectedReturnType =
4470 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4471 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4472 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4473 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4474 HadError = true;
4475 }
4476
4477 // A defaulted special member cannot have cv-qualifiers.
4478 if (Type->getTypeQuals()) {
4479 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004480 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004481 HadError = true;
4482 }
4483 }
4484
4485 // Check for parameter type matching.
4486 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004487 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004488 if (ExpectedParams && ArgType->isReferenceType()) {
4489 // Argument must be reference to possibly-const T.
4490 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004491 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004492
4493 if (ReferentType.isVolatileQualified()) {
4494 Diag(MD->getLocation(),
4495 diag::err_defaulted_special_member_volatile_param) << CSM;
4496 HadError = true;
4497 }
4498
Richard Smith7756afa2012-06-10 05:43:50 +00004499 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004500 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4501 Diag(MD->getLocation(),
4502 diag::err_defaulted_special_member_copy_const_param)
4503 << (CSM == CXXCopyAssignment);
4504 // FIXME: Explain why this special member can't be const.
4505 } else {
4506 Diag(MD->getLocation(),
4507 diag::err_defaulted_special_member_move_const_param)
4508 << (CSM == CXXMoveAssignment);
4509 }
4510 HadError = true;
4511 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004512 } else if (ExpectedParams) {
4513 // A copy assignment operator can take its argument by value, but a
4514 // defaulted one cannot.
4515 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004516 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004517 HadError = true;
4518 }
Sean Huntbe631222011-05-17 20:44:43 +00004519
Richard Smith61802452011-12-22 02:22:31 +00004520 // C++11 [dcl.fct.def.default]p2:
4521 // An explicitly-defaulted function may be declared constexpr only if it
4522 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004523 // Do not apply this rule to members of class templates, since core issue 1358
4524 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004525 // functions which cannot be constexpr (for non-constructors in C++11 and for
4526 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004527 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4528 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004529 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4530 : isa<CXXConstructorDecl>(MD)) &&
4531 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004532 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4533 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004534 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004535 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004536 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004537
Richard Smith61802452011-12-22 02:22:31 +00004538 // and may have an explicit exception-specification only if it is compatible
4539 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004540 if (Type->hasExceptionSpec()) {
4541 // Delay the check if this is the first declaration of the special member,
4542 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004543 if (First) {
4544 // If the exception specification needs to be instantiated, do so now,
4545 // before we clobber it with an EST_Unevaluated specification below.
4546 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4547 InstantiateExceptionSpec(MD->getLocStart(), MD);
4548 Type = MD->getType()->getAs<FunctionProtoType>();
4549 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004550 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004551 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004552 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4553 }
Richard Smith61802452011-12-22 02:22:31 +00004554
4555 // If a function is explicitly defaulted on its first declaration,
4556 if (First) {
4557 // -- it is implicitly considered to be constexpr if the implicit
4558 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004559 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004560
Richard Smith3003e1d2012-05-15 04:39:51 +00004561 // -- it is implicitly considered to have the same exception-specification
4562 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004563 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4564 EPI.ExceptionSpecType = EST_Unevaluated;
4565 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004566 MD->setType(Context.getFunctionType(ReturnType,
4567 ArrayRef<QualType>(&ArgType,
4568 ExpectedParams),
4569 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004570 }
4571
Richard Smith3003e1d2012-05-15 04:39:51 +00004572 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004573 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004574 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004575 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004576 // C++11 [dcl.fct.def.default]p4:
4577 // [For a] user-provided explicitly-defaulted function [...] if such a
4578 // function is implicitly defined as deleted, the program is ill-formed.
4579 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4580 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004581 }
4582 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004583
Richard Smith3003e1d2012-05-15 04:39:51 +00004584 if (HadError)
4585 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004586}
4587
Richard Smith1d28caf2012-12-11 01:14:52 +00004588/// Check whether the exception specification provided for an
4589/// explicitly-defaulted special member matches the exception specification
4590/// that would have been generated for an implicit special member, per
4591/// C++11 [dcl.fct.def.default]p2.
4592void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4593 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4594 // Compute the implicit exception specification.
4595 FunctionProtoType::ExtProtoInfo EPI;
4596 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4597 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004598 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004599
4600 // Ensure that it matches.
4601 CheckEquivalentExceptionSpec(
4602 PDiag(diag::err_incorrect_defaulted_exception_spec)
4603 << getSpecialMember(MD), PDiag(),
4604 ImplicitType, SourceLocation(),
4605 SpecifiedType, MD->getLocation());
4606}
4607
4608void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4609 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4610 I != N; ++I)
4611 CheckExplicitlyDefaultedMemberExceptionSpec(
4612 DelayedDefaultedMemberExceptionSpecs[I].first,
4613 DelayedDefaultedMemberExceptionSpecs[I].second);
4614
4615 DelayedDefaultedMemberExceptionSpecs.clear();
4616}
4617
Richard Smith7d5088a2012-02-18 02:02:13 +00004618namespace {
4619struct SpecialMemberDeletionInfo {
4620 Sema &S;
4621 CXXMethodDecl *MD;
4622 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004623 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004624
4625 // Properties of the special member, computed for convenience.
4626 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4627 SourceLocation Loc;
4628
4629 bool AllFieldsAreConst;
4630
4631 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004632 Sema::CXXSpecialMember CSM, bool Diagnose)
4633 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004634 IsConstructor(false), IsAssignment(false), IsMove(false),
4635 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4636 AllFieldsAreConst(true) {
4637 switch (CSM) {
4638 case Sema::CXXDefaultConstructor:
4639 case Sema::CXXCopyConstructor:
4640 IsConstructor = true;
4641 break;
4642 case Sema::CXXMoveConstructor:
4643 IsConstructor = true;
4644 IsMove = true;
4645 break;
4646 case Sema::CXXCopyAssignment:
4647 IsAssignment = true;
4648 break;
4649 case Sema::CXXMoveAssignment:
4650 IsAssignment = true;
4651 IsMove = true;
4652 break;
4653 case Sema::CXXDestructor:
4654 break;
4655 case Sema::CXXInvalid:
4656 llvm_unreachable("invalid special member kind");
4657 }
4658
4659 if (MD->getNumParams()) {
4660 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4661 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4662 }
4663 }
4664
4665 bool inUnion() const { return MD->getParent()->isUnion(); }
4666
4667 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004668 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4669 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004670 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004671 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4672 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4673 Quals = 0;
4674 return S.LookupSpecialMember(Class, CSM,
4675 ConstArg || (Quals & Qualifiers::Const),
4676 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004677 MD->getRefQualifier() == RQ_RValue,
4678 TQ & Qualifiers::Const,
4679 TQ & Qualifiers::Volatile);
4680 }
4681
Richard Smith6c4c36c2012-03-30 20:53:28 +00004682 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004683
Richard Smith6c4c36c2012-03-30 20:53:28 +00004684 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004685 bool shouldDeleteForField(FieldDecl *FD);
4686 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004687
Richard Smith517bb842012-07-18 03:51:16 +00004688 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4689 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004690 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4691 Sema::SpecialMemberOverloadResult *SMOR,
4692 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004693
4694 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004695};
4696}
4697
John McCall12d8d802012-04-09 20:53:23 +00004698/// Is the given special member inaccessible when used on the given
4699/// sub-object.
4700bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4701 CXXMethodDecl *target) {
4702 /// If we're operating on a base class, the object type is the
4703 /// type of this special member.
4704 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004705 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004706 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4707 objectTy = S.Context.getTypeDeclType(MD->getParent());
4708 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4709
4710 // If we're operating on a field, the object type is the type of the field.
4711 } else {
4712 objectTy = S.Context.getTypeDeclType(target->getParent());
4713 }
4714
4715 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4716}
4717
Richard Smith6c4c36c2012-03-30 20:53:28 +00004718/// Check whether we should delete a special member due to the implicit
4719/// definition containing a call to a special member of a subobject.
4720bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4721 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4722 bool IsDtorCallInCtor) {
4723 CXXMethodDecl *Decl = SMOR->getMethod();
4724 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4725
4726 int DiagKind = -1;
4727
4728 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4729 DiagKind = !Decl ? 0 : 1;
4730 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4731 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004732 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004733 DiagKind = 3;
4734 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4735 !Decl->isTrivial()) {
4736 // A member of a union must have a trivial corresponding special member.
4737 // As a weird special case, a destructor call from a union's constructor
4738 // must be accessible and non-deleted, but need not be trivial. Such a
4739 // destructor is never actually called, but is semantically checked as
4740 // if it were.
4741 DiagKind = 4;
4742 }
4743
4744 if (DiagKind == -1)
4745 return false;
4746
4747 if (Diagnose) {
4748 if (Field) {
4749 S.Diag(Field->getLocation(),
4750 diag::note_deleted_special_member_class_subobject)
4751 << CSM << MD->getParent() << /*IsField*/true
4752 << Field << DiagKind << IsDtorCallInCtor;
4753 } else {
4754 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4755 S.Diag(Base->getLocStart(),
4756 diag::note_deleted_special_member_class_subobject)
4757 << CSM << MD->getParent() << /*IsField*/false
4758 << Base->getType() << DiagKind << IsDtorCallInCtor;
4759 }
4760
4761 if (DiagKind == 1)
4762 S.NoteDeletedFunction(Decl);
4763 // FIXME: Explain inaccessibility if DiagKind == 3.
4764 }
4765
4766 return true;
4767}
4768
Richard Smith9a561d52012-02-26 09:11:52 +00004769/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004770/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004771bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004772 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004773 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004774
4775 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004776 // -- any direct or virtual base class, or non-static data member with no
4777 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004778 // either M has no default constructor or overload resolution as applied
4779 // to M's default constructor results in an ambiguity or in a function
4780 // that is deleted or inaccessible
4781 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4782 // -- a direct or virtual base class B that cannot be copied/moved because
4783 // overload resolution, as applied to B's corresponding special member,
4784 // results in an ambiguity or a function that is deleted or inaccessible
4785 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004786 // C++11 [class.dtor]p5:
4787 // -- any direct or virtual base class [...] has a type with a destructor
4788 // that is deleted or inaccessible
4789 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004790 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004791 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004792 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004793
Richard Smith6c4c36c2012-03-30 20:53:28 +00004794 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4795 // -- any direct or virtual base class or non-static data member has a
4796 // type with a destructor that is deleted or inaccessible
4797 if (IsConstructor) {
4798 Sema::SpecialMemberOverloadResult *SMOR =
4799 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4800 false, false, false, false, false);
4801 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4802 return true;
4803 }
4804
Richard Smith9a561d52012-02-26 09:11:52 +00004805 return false;
4806}
4807
4808/// Check whether we should delete a special member function due to the class
4809/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004810bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004811 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004812 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004813}
4814
4815/// Check whether we should delete a special member function due to the class
4816/// having a particular non-static data member.
4817bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4818 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4819 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4820
4821 if (CSM == Sema::CXXDefaultConstructor) {
4822 // For a default constructor, all references must be initialized in-class
4823 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004824 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4825 if (Diagnose)
4826 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4827 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004828 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004829 }
Richard Smith79363f52012-02-27 06:07:25 +00004830 // C++11 [class.ctor]p5: any non-variant non-static data member of
4831 // const-qualified type (or array thereof) with no
4832 // brace-or-equal-initializer does not have a user-provided default
4833 // constructor.
4834 if (!inUnion() && FieldType.isConstQualified() &&
4835 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004836 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4837 if (Diagnose)
4838 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004839 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004840 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004841 }
4842
4843 if (inUnion() && !FieldType.isConstQualified())
4844 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004845 } else if (CSM == Sema::CXXCopyConstructor) {
4846 // For a copy constructor, data members must not be of rvalue reference
4847 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004848 if (FieldType->isRValueReferenceType()) {
4849 if (Diagnose)
4850 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4851 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004852 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004853 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004854 } else if (IsAssignment) {
4855 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004856 if (FieldType->isReferenceType()) {
4857 if (Diagnose)
4858 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4859 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004860 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004861 }
4862 if (!FieldRecord && FieldType.isConstQualified()) {
4863 // C++11 [class.copy]p23:
4864 // -- a non-static data member of const non-class type (or array thereof)
4865 if (Diagnose)
4866 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004867 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004868 return true;
4869 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004870 }
4871
4872 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004873 // Some additional restrictions exist on the variant members.
4874 if (!inUnion() && FieldRecord->isUnion() &&
4875 FieldRecord->isAnonymousStructOrUnion()) {
4876 bool AllVariantFieldsAreConst = true;
4877
Richard Smithdf8dc862012-03-29 19:00:10 +00004878 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004879 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4880 UE = FieldRecord->field_end();
4881 UI != UE; ++UI) {
4882 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004883
4884 if (!UnionFieldType.isConstQualified())
4885 AllVariantFieldsAreConst = false;
4886
Richard Smith9a561d52012-02-26 09:11:52 +00004887 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4888 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004889 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4890 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004891 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004892 }
4893
4894 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004895 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004896 FieldRecord->field_begin() != FieldRecord->field_end()) {
4897 if (Diagnose)
4898 S.Diag(FieldRecord->getLocation(),
4899 diag::note_deleted_default_ctor_all_const)
4900 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004901 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004902 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004903
Richard Smithdf8dc862012-03-29 19:00:10 +00004904 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004905 // This is technically non-conformant, but sanity demands it.
4906 return false;
4907 }
4908
Richard Smith517bb842012-07-18 03:51:16 +00004909 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4910 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004911 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004912 }
4913
4914 return false;
4915}
4916
4917/// C++11 [class.ctor] p5:
4918/// A defaulted default constructor for a class X is defined as deleted if
4919/// X is a union and all of its variant members are of const-qualified type.
4920bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004921 // This is a silly definition, because it gives an empty union a deleted
4922 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004923 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4924 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4925 if (Diagnose)
4926 S.Diag(MD->getParent()->getLocation(),
4927 diag::note_deleted_default_ctor_all_const)
4928 << MD->getParent() << /*not anonymous union*/0;
4929 return true;
4930 }
4931 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004932}
4933
4934/// Determine whether a defaulted special member function should be defined as
4935/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4936/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004937bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4938 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004939 if (MD->isInvalidDecl())
4940 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004941 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004942 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004943 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004944 return false;
4945
Richard Smith7d5088a2012-02-18 02:02:13 +00004946 // C++11 [expr.lambda.prim]p19:
4947 // The closure type associated with a lambda-expression has a
4948 // deleted (8.4.3) default constructor and a deleted copy
4949 // assignment operator.
4950 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004951 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4952 if (Diagnose)
4953 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004954 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004955 }
4956
Richard Smith5bdaac52012-04-02 20:59:25 +00004957 // For an anonymous struct or union, the copy and assignment special members
4958 // will never be used, so skip the check. For an anonymous union declared at
4959 // namespace scope, the constructor and destructor are used.
4960 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4961 RD->isAnonymousStructOrUnion())
4962 return false;
4963
Richard Smith6c4c36c2012-03-30 20:53:28 +00004964 // C++11 [class.copy]p7, p18:
4965 // If the class definition declares a move constructor or move assignment
4966 // operator, an implicitly declared copy constructor or copy assignment
4967 // operator is defined as deleted.
4968 if (MD->isImplicit() &&
4969 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4970 CXXMethodDecl *UserDeclaredMove = 0;
4971
4972 // In Microsoft mode, a user-declared move only causes the deletion of the
4973 // corresponding copy operation, not both copy operations.
4974 if (RD->hasUserDeclaredMoveConstructor() &&
4975 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4976 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004977
4978 // Find any user-declared move constructor.
4979 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4980 E = RD->ctor_end(); I != E; ++I) {
4981 if (I->isMoveConstructor()) {
4982 UserDeclaredMove = *I;
4983 break;
4984 }
4985 }
Richard Smith1c931be2012-04-02 18:40:40 +00004986 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004987 } else if (RD->hasUserDeclaredMoveAssignment() &&
4988 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4989 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004990
4991 // Find any user-declared move assignment operator.
4992 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4993 E = RD->method_end(); I != E; ++I) {
4994 if (I->isMoveAssignmentOperator()) {
4995 UserDeclaredMove = *I;
4996 break;
4997 }
4998 }
Richard Smith1c931be2012-04-02 18:40:40 +00004999 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005000 }
5001
5002 if (UserDeclaredMove) {
5003 Diag(UserDeclaredMove->getLocation(),
5004 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005005 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005006 << UserDeclaredMove->isMoveAssignmentOperator();
5007 return true;
5008 }
5009 }
Sean Hunte16da072011-10-10 06:18:57 +00005010
Richard Smith5bdaac52012-04-02 20:59:25 +00005011 // Do access control from the special member function
5012 ContextRAII MethodContext(*this, MD);
5013
Richard Smith9a561d52012-02-26 09:11:52 +00005014 // C++11 [class.dtor]p5:
5015 // -- for a virtual destructor, lookup of the non-array deallocation function
5016 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005017 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005018 FunctionDecl *OperatorDelete = 0;
5019 DeclarationName Name =
5020 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5021 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005022 OperatorDelete, false)) {
5023 if (Diagnose)
5024 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005025 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005026 }
Richard Smith9a561d52012-02-26 09:11:52 +00005027 }
5028
Richard Smith6c4c36c2012-03-30 20:53:28 +00005029 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005030
Sean Huntcdee3fe2011-05-11 22:34:38 +00005031 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005032 BE = RD->bases_end(); BI != BE; ++BI)
5033 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005034 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005035 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005036
5037 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005038 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00005039 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005040 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005041
5042 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005043 FE = RD->field_end(); FI != FE; ++FI)
5044 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005045 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005046 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005047
Richard Smith7d5088a2012-02-18 02:02:13 +00005048 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005049 return true;
5050
5051 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005052}
5053
Richard Smithac713512012-12-08 02:53:02 +00005054/// Perform lookup for a special member of the specified kind, and determine
5055/// whether it is trivial. If the triviality can be determined without the
5056/// lookup, skip it. This is intended for use when determining whether a
5057/// special member of a containing object is trivial, and thus does not ever
5058/// perform overload resolution for default constructors.
5059///
5060/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5061/// member that was most likely to be intended to be trivial, if any.
5062static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5063 Sema::CXXSpecialMember CSM, unsigned Quals,
5064 CXXMethodDecl **Selected) {
5065 if (Selected)
5066 *Selected = 0;
5067
5068 switch (CSM) {
5069 case Sema::CXXInvalid:
5070 llvm_unreachable("not a special member");
5071
5072 case Sema::CXXDefaultConstructor:
5073 // C++11 [class.ctor]p5:
5074 // A default constructor is trivial if:
5075 // - all the [direct subobjects] have trivial default constructors
5076 //
5077 // Note, no overload resolution is performed in this case.
5078 if (RD->hasTrivialDefaultConstructor())
5079 return true;
5080
5081 if (Selected) {
5082 // If there's a default constructor which could have been trivial, dig it
5083 // out. Otherwise, if there's any user-provided default constructor, point
5084 // to that as an example of why there's not a trivial one.
5085 CXXConstructorDecl *DefCtor = 0;
5086 if (RD->needsImplicitDefaultConstructor())
5087 S.DeclareImplicitDefaultConstructor(RD);
5088 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5089 CE = RD->ctor_end(); CI != CE; ++CI) {
5090 if (!CI->isDefaultConstructor())
5091 continue;
5092 DefCtor = *CI;
5093 if (!DefCtor->isUserProvided())
5094 break;
5095 }
5096
5097 *Selected = DefCtor;
5098 }
5099
5100 return false;
5101
5102 case Sema::CXXDestructor:
5103 // C++11 [class.dtor]p5:
5104 // A destructor is trivial if:
5105 // - all the direct [subobjects] have trivial destructors
5106 if (RD->hasTrivialDestructor())
5107 return true;
5108
5109 if (Selected) {
5110 if (RD->needsImplicitDestructor())
5111 S.DeclareImplicitDestructor(RD);
5112 *Selected = RD->getDestructor();
5113 }
5114
5115 return false;
5116
5117 case Sema::CXXCopyConstructor:
5118 // C++11 [class.copy]p12:
5119 // A copy constructor is trivial if:
5120 // - the constructor selected to copy each direct [subobject] is trivial
5121 if (RD->hasTrivialCopyConstructor()) {
5122 if (Quals == Qualifiers::Const)
5123 // We must either select the trivial copy constructor or reach an
5124 // ambiguity; no need to actually perform overload resolution.
5125 return true;
5126 } else if (!Selected) {
5127 return false;
5128 }
5129 // In C++98, we are not supposed to perform overload resolution here, but we
5130 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5131 // cases like B as having a non-trivial copy constructor:
5132 // struct A { template<typename T> A(T&); };
5133 // struct B { mutable A a; };
5134 goto NeedOverloadResolution;
5135
5136 case Sema::CXXCopyAssignment:
5137 // C++11 [class.copy]p25:
5138 // A copy assignment operator is trivial if:
5139 // - the assignment operator selected to copy each direct [subobject] is
5140 // trivial
5141 if (RD->hasTrivialCopyAssignment()) {
5142 if (Quals == Qualifiers::Const)
5143 return true;
5144 } else if (!Selected) {
5145 return false;
5146 }
5147 // In C++98, we are not supposed to perform overload resolution here, but we
5148 // treat that as a language defect.
5149 goto NeedOverloadResolution;
5150
5151 case Sema::CXXMoveConstructor:
5152 case Sema::CXXMoveAssignment:
5153 NeedOverloadResolution:
5154 Sema::SpecialMemberOverloadResult *SMOR =
5155 S.LookupSpecialMember(RD, CSM,
5156 Quals & Qualifiers::Const,
5157 Quals & Qualifiers::Volatile,
5158 /*RValueThis*/false, /*ConstThis*/false,
5159 /*VolatileThis*/false);
5160
5161 // The standard doesn't describe how to behave if the lookup is ambiguous.
5162 // We treat it as not making the member non-trivial, just like the standard
5163 // mandates for the default constructor. This should rarely matter, because
5164 // the member will also be deleted.
5165 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5166 return true;
5167
5168 if (!SMOR->getMethod()) {
5169 assert(SMOR->getKind() ==
5170 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5171 return false;
5172 }
5173
5174 // We deliberately don't check if we found a deleted special member. We're
5175 // not supposed to!
5176 if (Selected)
5177 *Selected = SMOR->getMethod();
5178 return SMOR->getMethod()->isTrivial();
5179 }
5180
5181 llvm_unreachable("unknown special method kind");
5182}
5183
Benjamin Kramera574c892013-02-15 12:30:38 +00005184static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005185 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5186 CI != CE; ++CI)
5187 if (!CI->isImplicit())
5188 return *CI;
5189
5190 // Look for constructor templates.
5191 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5192 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5193 if (CXXConstructorDecl *CD =
5194 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5195 return CD;
5196 }
5197
5198 return 0;
5199}
5200
5201/// The kind of subobject we are checking for triviality. The values of this
5202/// enumeration are used in diagnostics.
5203enum TrivialSubobjectKind {
5204 /// The subobject is a base class.
5205 TSK_BaseClass,
5206 /// The subobject is a non-static data member.
5207 TSK_Field,
5208 /// The object is actually the complete object.
5209 TSK_CompleteObject
5210};
5211
5212/// Check whether the special member selected for a given type would be trivial.
5213static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5214 QualType SubType,
5215 Sema::CXXSpecialMember CSM,
5216 TrivialSubobjectKind Kind,
5217 bool Diagnose) {
5218 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5219 if (!SubRD)
5220 return true;
5221
5222 CXXMethodDecl *Selected;
5223 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5224 Diagnose ? &Selected : 0))
5225 return true;
5226
5227 if (Diagnose) {
5228 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5229 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5230 << Kind << SubType.getUnqualifiedType();
5231 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5232 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5233 } else if (!Selected)
5234 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5235 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5236 else if (Selected->isUserProvided()) {
5237 if (Kind == TSK_CompleteObject)
5238 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5239 << Kind << SubType.getUnqualifiedType() << CSM;
5240 else {
5241 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5242 << Kind << SubType.getUnqualifiedType() << CSM;
5243 S.Diag(Selected->getLocation(), diag::note_declared_at);
5244 }
5245 } else {
5246 if (Kind != TSK_CompleteObject)
5247 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5248 << Kind << SubType.getUnqualifiedType() << CSM;
5249
5250 // Explain why the defaulted or deleted special member isn't trivial.
5251 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5252 }
5253 }
5254
5255 return false;
5256}
5257
5258/// Check whether the members of a class type allow a special member to be
5259/// trivial.
5260static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5261 Sema::CXXSpecialMember CSM,
5262 bool ConstArg, bool Diagnose) {
5263 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5264 FE = RD->field_end(); FI != FE; ++FI) {
5265 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5266 continue;
5267
5268 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5269
5270 // Pretend anonymous struct or union members are members of this class.
5271 if (FI->isAnonymousStructOrUnion()) {
5272 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5273 CSM, ConstArg, Diagnose))
5274 return false;
5275 continue;
5276 }
5277
5278 // C++11 [class.ctor]p5:
5279 // A default constructor is trivial if [...]
5280 // -- no non-static data member of its class has a
5281 // brace-or-equal-initializer
5282 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5283 if (Diagnose)
5284 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5285 return false;
5286 }
5287
5288 // Objective C ARC 4.3.5:
5289 // [...] nontrivally ownership-qualified types are [...] not trivially
5290 // default constructible, copy constructible, move constructible, copy
5291 // assignable, move assignable, or destructible [...]
5292 if (S.getLangOpts().ObjCAutoRefCount &&
5293 FieldType.hasNonTrivialObjCLifetime()) {
5294 if (Diagnose)
5295 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5296 << RD << FieldType.getObjCLifetime();
5297 return false;
5298 }
5299
5300 if (ConstArg && !FI->isMutable())
5301 FieldType.addConst();
5302 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5303 TSK_Field, Diagnose))
5304 return false;
5305 }
5306
5307 return true;
5308}
5309
5310/// Diagnose why the specified class does not have a trivial special member of
5311/// the given kind.
5312void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5313 QualType Ty = Context.getRecordType(RD);
5314 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5315 Ty.addConst();
5316
5317 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5318 TSK_CompleteObject, /*Diagnose*/true);
5319}
5320
5321/// Determine whether a defaulted or deleted special member function is trivial,
5322/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5323/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5324bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5325 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005326 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5327
5328 CXXRecordDecl *RD = MD->getParent();
5329
5330 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005331
5332 // C++11 [class.copy]p12, p25:
5333 // A [special member] is trivial if its declared parameter type is the same
5334 // as if it had been implicitly declared [...]
5335 switch (CSM) {
5336 case CXXDefaultConstructor:
5337 case CXXDestructor:
5338 // Trivial default constructors and destructors cannot have parameters.
5339 break;
5340
5341 case CXXCopyConstructor:
5342 case CXXCopyAssignment: {
5343 // Trivial copy operations always have const, non-volatile parameter types.
5344 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005345 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005346 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5347 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5348 if (Diagnose)
5349 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5350 << Param0->getSourceRange() << Param0->getType()
5351 << Context.getLValueReferenceType(
5352 Context.getRecordType(RD).withConst());
5353 return false;
5354 }
5355 break;
5356 }
5357
5358 case CXXMoveConstructor:
5359 case CXXMoveAssignment: {
5360 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005361 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005362 const RValueReferenceType *RT =
5363 Param0->getType()->getAs<RValueReferenceType>();
5364 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5365 if (Diagnose)
5366 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5367 << Param0->getSourceRange() << Param0->getType()
5368 << Context.getRValueReferenceType(Context.getRecordType(RD));
5369 return false;
5370 }
5371 break;
5372 }
5373
5374 case CXXInvalid:
5375 llvm_unreachable("not a special member");
5376 }
5377
5378 // FIXME: We require that the parameter-declaration-clause is equivalent to
5379 // that of an implicit declaration, not just that the declared parameter type
5380 // matches, in order to prevent absuridities like a function simultaneously
5381 // being a trivial copy constructor and a non-trivial default constructor.
5382 // This issue has not yet been assigned a core issue number.
5383 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5384 if (Diagnose)
5385 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5386 diag::note_nontrivial_default_arg)
5387 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5388 return false;
5389 }
5390 if (MD->isVariadic()) {
5391 if (Diagnose)
5392 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5393 return false;
5394 }
5395
5396 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5397 // A copy/move [constructor or assignment operator] is trivial if
5398 // -- the [member] selected to copy/move each direct base class subobject
5399 // is trivial
5400 //
5401 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5402 // A [default constructor or destructor] is trivial if
5403 // -- all the direct base classes have trivial [default constructors or
5404 // destructors]
5405 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5406 BE = RD->bases_end(); BI != BE; ++BI)
5407 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5408 ConstArg ? BI->getType().withConst()
5409 : BI->getType(),
5410 CSM, TSK_BaseClass, Diagnose))
5411 return false;
5412
5413 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5414 // A copy/move [constructor or assignment operator] for a class X is
5415 // trivial if
5416 // -- for each non-static data member of X that is of class type (or array
5417 // thereof), the constructor selected to copy/move that member is
5418 // trivial
5419 //
5420 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5421 // A [default constructor or destructor] is trivial if
5422 // -- for all of the non-static data members of its class that are of class
5423 // type (or array thereof), each such class has a trivial [default
5424 // constructor or destructor]
5425 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5426 return false;
5427
5428 // C++11 [class.dtor]p5:
5429 // A destructor is trivial if [...]
5430 // -- the destructor is not virtual
5431 if (CSM == CXXDestructor && MD->isVirtual()) {
5432 if (Diagnose)
5433 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5434 return false;
5435 }
5436
5437 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5438 // A [special member] for class X is trivial if [...]
5439 // -- class X has no virtual functions and no virtual base classes
5440 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5441 if (!Diagnose)
5442 return false;
5443
5444 if (RD->getNumVBases()) {
5445 // Check for virtual bases. We already know that the corresponding
5446 // member in all bases is trivial, so vbases must all be direct.
5447 CXXBaseSpecifier &BS = *RD->vbases_begin();
5448 assert(BS.isVirtual());
5449 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5450 return false;
5451 }
5452
5453 // Must have a virtual method.
5454 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5455 ME = RD->method_end(); MI != ME; ++MI) {
5456 if (MI->isVirtual()) {
5457 SourceLocation MLoc = MI->getLocStart();
5458 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5459 return false;
5460 }
5461 }
5462
5463 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5464 }
5465
5466 // Looks like it's trivial!
5467 return true;
5468}
5469
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005470/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005471namespace {
5472 struct FindHiddenVirtualMethodData {
5473 Sema *S;
5474 CXXMethodDecl *Method;
5475 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005476 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005477 };
5478}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005479
David Blaikie5f750682012-10-19 00:53:08 +00005480/// \brief Check whether any most overriden method from MD in Methods
5481static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5482 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5483 if (MD->size_overridden_methods() == 0)
5484 return Methods.count(MD->getCanonicalDecl());
5485 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5486 E = MD->end_overridden_methods();
5487 I != E; ++I)
5488 if (CheckMostOverridenMethods(*I, Methods))
5489 return true;
5490 return false;
5491}
5492
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005493/// \brief Member lookup function that determines whether a given C++
5494/// method overloads virtual methods in a base class without overriding any,
5495/// to be used with CXXRecordDecl::lookupInBases().
5496static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5497 CXXBasePath &Path,
5498 void *UserData) {
5499 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5500
5501 FindHiddenVirtualMethodData &Data
5502 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5503
5504 DeclarationName Name = Data.Method->getDeclName();
5505 assert(Name.getNameKind() == DeclarationName::Identifier);
5506
5507 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005508 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005509 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005510 !Path.Decls.empty();
5511 Path.Decls = Path.Decls.slice(1)) {
5512 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005513 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005514 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005515 foundSameNameMethod = true;
5516 // Interested only in hidden virtual methods.
5517 if (!MD->isVirtual())
5518 continue;
5519 // If the method we are checking overrides a method from its base
5520 // don't warn about the other overloaded methods.
5521 if (!Data.S->IsOverload(Data.Method, MD, false))
5522 return true;
5523 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005524 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005525 overloadedMethods.push_back(MD);
5526 }
5527 }
5528
5529 if (foundSameNameMethod)
5530 Data.OverloadedMethods.append(overloadedMethods.begin(),
5531 overloadedMethods.end());
5532 return foundSameNameMethod;
5533}
5534
David Blaikie5f750682012-10-19 00:53:08 +00005535/// \brief Add the most overriden methods from MD to Methods
5536static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5537 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5538 if (MD->size_overridden_methods() == 0)
5539 Methods.insert(MD->getCanonicalDecl());
5540 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5541 E = MD->end_overridden_methods();
5542 I != E; ++I)
5543 AddMostOverridenMethods(*I, Methods);
5544}
5545
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005546/// \brief See if a method overloads virtual methods in a base class without
5547/// overriding any.
5548void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5549 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005550 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005551 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005552 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005553 return;
5554
5555 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5556 /*bool RecordPaths=*/false,
5557 /*bool DetectVirtual=*/false);
5558 FindHiddenVirtualMethodData Data;
5559 Data.Method = MD;
5560 Data.S = this;
5561
5562 // Keep the base methods that were overriden or introduced in the subclass
5563 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005564 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5565 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5566 NamedDecl *ND = *I;
5567 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005568 ND = shad->getTargetDecl();
5569 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5570 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005571 }
5572
5573 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5574 !Data.OverloadedMethods.empty()) {
5575 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5576 << MD << (Data.OverloadedMethods.size() > 1);
5577
5578 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5579 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005580 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005581 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005582 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5583 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005584 }
5585 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005586}
5587
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005588void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005589 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005590 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005591 SourceLocation RBrac,
5592 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005593 if (!TagDecl)
5594 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005595
Douglas Gregor42af25f2009-05-11 19:58:34 +00005596 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005597
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005598 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5599 if (l->getKind() != AttributeList::AT_Visibility)
5600 continue;
5601 l->setInvalid();
5602 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5603 l->getName();
5604 }
5605
David Blaikie77b6de02011-09-22 02:58:26 +00005606 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005607 // strict aliasing violation!
5608 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005609 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005610
Douglas Gregor23c94db2010-07-02 17:43:08 +00005611 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005612 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005613}
5614
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005615/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5616/// special functions, such as the default constructor, copy
5617/// constructor, or destructor, to the given C++ class (C++
5618/// [special]p1). This routine can only be executed just before the
5619/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005620void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005621 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005622 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005623
Richard Smithbc2a35d2012-12-08 08:32:28 +00005624 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005625 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005626
Richard Smithbc2a35d2012-12-08 08:32:28 +00005627 // If the properties or semantics of the copy constructor couldn't be
5628 // determined while the class was being declared, force a declaration
5629 // of it now.
5630 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5631 DeclareImplicitCopyConstructor(ClassDecl);
5632 }
5633
Richard Smith80ad52f2013-01-02 11:42:31 +00005634 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005635 ++ASTContext::NumImplicitMoveConstructors;
5636
Richard Smithbc2a35d2012-12-08 08:32:28 +00005637 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5638 DeclareImplicitMoveConstructor(ClassDecl);
5639 }
5640
Douglas Gregora376d102010-07-02 21:50:04 +00005641 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5642 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005643
5644 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005645 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005646 // it shows up in the right place in the vtable and that we diagnose
5647 // problems with the implicit exception specification.
5648 if (ClassDecl->isDynamicClass() ||
5649 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005650 DeclareImplicitCopyAssignment(ClassDecl);
5651 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005652
Richard Smith80ad52f2013-01-02 11:42:31 +00005653 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005654 ++ASTContext::NumImplicitMoveAssignmentOperators;
5655
5656 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005657 if (ClassDecl->isDynamicClass() ||
5658 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005659 DeclareImplicitMoveAssignment(ClassDecl);
5660 }
5661
Douglas Gregor4923aa22010-07-02 20:37:36 +00005662 if (!ClassDecl->hasUserDeclaredDestructor()) {
5663 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005664
5665 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005666 // have to declare the destructor immediately. This ensures that, e.g., it
5667 // shows up in the right place in the vtable and that we diagnose problems
5668 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005669 if (ClassDecl->isDynamicClass() ||
5670 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005671 DeclareImplicitDestructor(ClassDecl);
5672 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005673}
5674
Francois Pichet8387e2a2011-04-22 22:18:13 +00005675void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5676 if (!D)
5677 return;
5678
5679 int NumParamList = D->getNumTemplateParameterLists();
5680 for (int i = 0; i < NumParamList; i++) {
5681 TemplateParameterList* Params = D->getTemplateParameterList(i);
5682 for (TemplateParameterList::iterator Param = Params->begin(),
5683 ParamEnd = Params->end();
5684 Param != ParamEnd; ++Param) {
5685 NamedDecl *Named = cast<NamedDecl>(*Param);
5686 if (Named->getDeclName()) {
5687 S->AddDecl(Named);
5688 IdResolver.AddDecl(Named);
5689 }
5690 }
5691 }
5692}
5693
John McCalld226f652010-08-21 09:40:31 +00005694void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005695 if (!D)
5696 return;
5697
5698 TemplateParameterList *Params = 0;
5699 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5700 Params = Template->getTemplateParameters();
5701 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5702 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5703 Params = PartialSpec->getTemplateParameters();
5704 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005705 return;
5706
Douglas Gregor6569d682009-05-27 23:11:45 +00005707 for (TemplateParameterList::iterator Param = Params->begin(),
5708 ParamEnd = Params->end();
5709 Param != ParamEnd; ++Param) {
5710 NamedDecl *Named = cast<NamedDecl>(*Param);
5711 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005712 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005713 IdResolver.AddDecl(Named);
5714 }
5715 }
5716}
5717
John McCalld226f652010-08-21 09:40:31 +00005718void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005719 if (!RecordD) return;
5720 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005721 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005722 PushDeclContext(S, Record);
5723}
5724
John McCalld226f652010-08-21 09:40:31 +00005725void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005726 if (!RecordD) return;
5727 PopDeclContext();
5728}
5729
Douglas Gregor72b505b2008-12-16 21:30:33 +00005730/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5731/// parsing a top-level (non-nested) C++ class, and we are now
5732/// parsing those parts of the given Method declaration that could
5733/// not be parsed earlier (C++ [class.mem]p2), such as default
5734/// arguments. This action should enter the scope of the given
5735/// Method declaration as if we had just parsed the qualified method
5736/// name. However, it should not bring the parameters into scope;
5737/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005738void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005739}
5740
5741/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5742/// C++ method declaration. We're (re-)introducing the given
5743/// function parameter into scope for use in parsing later parts of
5744/// the method declaration. For example, we could see an
5745/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005746void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005747 if (!ParamD)
5748 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005749
John McCalld226f652010-08-21 09:40:31 +00005750 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005751
5752 // If this parameter has an unparsed default argument, clear it out
5753 // to make way for the parsed default argument.
5754 if (Param->hasUnparsedDefaultArg())
5755 Param->setDefaultArg(0);
5756
John McCalld226f652010-08-21 09:40:31 +00005757 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005758 if (Param->getDeclName())
5759 IdResolver.AddDecl(Param);
5760}
5761
5762/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5763/// processing the delayed method declaration for Method. The method
5764/// declaration is now considered finished. There may be a separate
5765/// ActOnStartOfFunctionDef action later (not necessarily
5766/// immediately!) for this method, if it was also defined inside the
5767/// class body.
John McCalld226f652010-08-21 09:40:31 +00005768void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005769 if (!MethodD)
5770 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005771
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005772 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005773
John McCalld226f652010-08-21 09:40:31 +00005774 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005775
5776 // Now that we have our default arguments, check the constructor
5777 // again. It could produce additional diagnostics or affect whether
5778 // the class has implicitly-declared destructors, among other
5779 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005780 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5781 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005782
5783 // Check the default arguments, which we may have added.
5784 if (!Method->isInvalidDecl())
5785 CheckCXXDefaultArguments(Method);
5786}
5787
Douglas Gregor42a552f2008-11-05 20:51:48 +00005788/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005789/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005790/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005791/// emit diagnostics and set the invalid bit to true. In any case, the type
5792/// will be updated to reflect a well-formed type for the constructor and
5793/// returned.
5794QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005795 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005796 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005797
5798 // C++ [class.ctor]p3:
5799 // A constructor shall not be virtual (10.3) or static (9.4). A
5800 // constructor can be invoked for a const, volatile or const
5801 // volatile object. A constructor shall not be declared const,
5802 // volatile, or const volatile (9.3.2).
5803 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005804 if (!D.isInvalidType())
5805 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5806 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5807 << SourceRange(D.getIdentifierLoc());
5808 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005809 }
John McCalld931b082010-08-26 03:08:43 +00005810 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005811 if (!D.isInvalidType())
5812 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5813 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5814 << SourceRange(D.getIdentifierLoc());
5815 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005816 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005817 }
Mike Stump1eb44332009-09-09 15:08:12 +00005818
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005819 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005820 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005821 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005822 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5823 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005824 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005825 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5826 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005827 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005828 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5829 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005830 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005831 }
Mike Stump1eb44332009-09-09 15:08:12 +00005832
Douglas Gregorc938c162011-01-26 05:01:58 +00005833 // C++0x [class.ctor]p4:
5834 // A constructor shall not be declared with a ref-qualifier.
5835 if (FTI.hasRefQualifier()) {
5836 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5837 << FTI.RefQualifierIsLValueRef
5838 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5839 D.setInvalidType();
5840 }
5841
Douglas Gregor42a552f2008-11-05 20:51:48 +00005842 // Rebuild the function type "R" without any type qualifiers (in
5843 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005844 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005845 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005846 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5847 return R;
5848
5849 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5850 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005851 EPI.RefQualifier = RQ_None;
5852
Richard Smith07b0fdc2013-03-18 21:12:30 +00005853 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005854}
5855
Douglas Gregor72b505b2008-12-16 21:30:33 +00005856/// CheckConstructor - Checks a fully-formed constructor for
5857/// well-formedness, issuing any diagnostics required. Returns true if
5858/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005859void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005860 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005861 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5862 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005863 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005864
5865 // C++ [class.copy]p3:
5866 // A declaration of a constructor for a class X is ill-formed if
5867 // its first parameter is of type (optionally cv-qualified) X and
5868 // either there are no other parameters or else all other
5869 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005870 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005871 ((Constructor->getNumParams() == 1) ||
5872 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005873 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5874 Constructor->getTemplateSpecializationKind()
5875 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005876 QualType ParamType = Constructor->getParamDecl(0)->getType();
5877 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5878 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005879 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005880 const char *ConstRef
5881 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5882 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005883 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005884 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005885
5886 // FIXME: Rather that making the constructor invalid, we should endeavor
5887 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005888 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005889 }
5890 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005891}
5892
John McCall15442822010-08-04 01:04:25 +00005893/// CheckDestructor - Checks a fully-formed destructor definition for
5894/// well-formedness, issuing any diagnostics required. Returns true
5895/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005896bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005897 CXXRecordDecl *RD = Destructor->getParent();
5898
Peter Collingbournef51cfb82013-05-20 14:12:25 +00005899 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005900 SourceLocation Loc;
5901
5902 if (!Destructor->isImplicit())
5903 Loc = Destructor->getLocation();
5904 else
5905 Loc = RD->getLocation();
5906
5907 // If we have a virtual destructor, look up the deallocation function
5908 FunctionDecl *OperatorDelete = 0;
5909 DeclarationName Name =
5910 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005911 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005912 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005913
Eli Friedman5f2987c2012-02-02 03:46:19 +00005914 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005915
5916 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005917 }
Anders Carlsson37909802009-11-30 21:24:50 +00005918
5919 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005920}
5921
Mike Stump1eb44332009-09-09 15:08:12 +00005922static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005923FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5924 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5925 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005926 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005927}
5928
Douglas Gregor42a552f2008-11-05 20:51:48 +00005929/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5930/// the well-formednes of the destructor declarator @p D with type @p
5931/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005932/// emit diagnostics and set the declarator to invalid. Even if this happens,
5933/// will be updated to reflect a well-formed type for the destructor and
5934/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005935QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005936 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005937 // C++ [class.dtor]p1:
5938 // [...] A typedef-name that names a class is a class-name
5939 // (7.1.3); however, a typedef-name that names a class shall not
5940 // be used as the identifier in the declarator for a destructor
5941 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005942 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005943 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005944 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005945 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005946 else if (const TemplateSpecializationType *TST =
5947 DeclaratorType->getAs<TemplateSpecializationType>())
5948 if (TST->isTypeAlias())
5949 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5950 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005951
5952 // C++ [class.dtor]p2:
5953 // A destructor is used to destroy objects of its class type. A
5954 // destructor takes no parameters, and no return type can be
5955 // specified for it (not even void). The address of a destructor
5956 // shall not be taken. A destructor shall not be static. A
5957 // destructor can be invoked for a const, volatile or const
5958 // volatile object. A destructor shall not be declared const,
5959 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005960 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005961 if (!D.isInvalidType())
5962 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5963 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005964 << SourceRange(D.getIdentifierLoc())
5965 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5966
John McCalld931b082010-08-26 03:08:43 +00005967 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005968 }
Chris Lattner65401802009-04-25 08:28:21 +00005969 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005970 // Destructors don't have return types, but the parser will
5971 // happily parse something like:
5972 //
5973 // class X {
5974 // float ~X();
5975 // };
5976 //
5977 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005978 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5979 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5980 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005981 }
Mike Stump1eb44332009-09-09 15:08:12 +00005982
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005983 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005984 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005985 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005986 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5987 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005988 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005989 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5990 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005991 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005992 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5993 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005994 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005995 }
5996
Douglas Gregorc938c162011-01-26 05:01:58 +00005997 // C++0x [class.dtor]p2:
5998 // A destructor shall not be declared with a ref-qualifier.
5999 if (FTI.hasRefQualifier()) {
6000 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6001 << FTI.RefQualifierIsLValueRef
6002 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6003 D.setInvalidType();
6004 }
6005
Douglas Gregor42a552f2008-11-05 20:51:48 +00006006 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006007 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006008 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6009
6010 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006011 FTI.freeArgs();
6012 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006013 }
6014
Mike Stump1eb44332009-09-09 15:08:12 +00006015 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006016 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006017 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006018 D.setInvalidType();
6019 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006020
6021 // Rebuild the function type "R" without any type qualifiers or
6022 // parameters (in case any of the errors above fired) and with
6023 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006024 // types.
John McCalle23cf432010-12-14 08:05:40 +00006025 if (!D.isInvalidType())
6026 return R;
6027
Douglas Gregord92ec472010-07-01 05:10:53 +00006028 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006029 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6030 EPI.Variadic = false;
6031 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006032 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006033 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006034}
6035
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006036/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6037/// well-formednes of the conversion function declarator @p D with
6038/// type @p R. If there are any errors in the declarator, this routine
6039/// will emit diagnostics and return true. Otherwise, it will return
6040/// false. Either way, the type @p R will be updated to reflect a
6041/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006042void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006043 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006044 // C++ [class.conv.fct]p1:
6045 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006046 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006047 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006048 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006049 if (!D.isInvalidType())
6050 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6051 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6052 << SourceRange(D.getIdentifierLoc());
6053 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006054 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006055 }
John McCalla3f81372010-04-13 00:04:31 +00006056
6057 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6058
Chris Lattner6e475012009-04-25 08:35:12 +00006059 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006060 // Conversion functions don't have return types, but the parser will
6061 // happily parse something like:
6062 //
6063 // class X {
6064 // float operator bool();
6065 // };
6066 //
6067 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006068 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6069 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6070 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006071 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006072 }
6073
John McCalla3f81372010-04-13 00:04:31 +00006074 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6075
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006076 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006077 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006078 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6079
6080 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006081 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006082 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006083 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006084 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006085 D.setInvalidType();
6086 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006087
John McCalla3f81372010-04-13 00:04:31 +00006088 // Diagnose "&operator bool()" and other such nonsense. This
6089 // is actually a gcc extension which we don't support.
6090 if (Proto->getResultType() != ConvType) {
6091 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6092 << Proto->getResultType();
6093 D.setInvalidType();
6094 ConvType = Proto->getResultType();
6095 }
6096
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006097 // C++ [class.conv.fct]p4:
6098 // The conversion-type-id shall not represent a function type nor
6099 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006100 if (ConvType->isArrayType()) {
6101 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6102 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006103 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006104 } else if (ConvType->isFunctionType()) {
6105 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6106 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006107 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006108 }
6109
6110 // Rebuild the function type "R" without any parameters (in case any
6111 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006112 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006113 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006114 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006115
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006116 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006117 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006118 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006119 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006120 diag::warn_cxx98_compat_explicit_conversion_functions :
6121 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006122 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006123}
6124
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006125/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6126/// the declaration of the given C++ conversion function. This routine
6127/// is responsible for recording the conversion function in the C++
6128/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006129Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006130 assert(Conversion && "Expected to receive a conversion function declaration");
6131
Douglas Gregor9d350972008-12-12 08:25:50 +00006132 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006133
6134 // Make sure we aren't redeclaring the conversion function.
6135 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006136
6137 // C++ [class.conv.fct]p1:
6138 // [...] A conversion function is never used to convert a
6139 // (possibly cv-qualified) object to the (possibly cv-qualified)
6140 // same object type (or a reference to it), to a (possibly
6141 // cv-qualified) base class of that type (or a reference to it),
6142 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006143 // FIXME: Suppress this warning if the conversion function ends up being a
6144 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006145 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006146 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006147 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006148 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006149 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6150 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006151 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006152 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006153 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6154 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006155 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006156 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006157 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006158 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006159 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006160 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006161 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006162 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006163 }
6164
Douglas Gregore80622f2010-09-29 04:25:11 +00006165 if (FunctionTemplateDecl *ConversionTemplate
6166 = Conversion->getDescribedFunctionTemplate())
6167 return ConversionTemplate;
6168
John McCalld226f652010-08-21 09:40:31 +00006169 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006170}
6171
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006172//===----------------------------------------------------------------------===//
6173// Namespace Handling
6174//===----------------------------------------------------------------------===//
6175
Richard Smithd1a55a62012-10-04 22:13:39 +00006176/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6177/// reopened.
6178static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6179 SourceLocation Loc,
6180 IdentifierInfo *II, bool *IsInline,
6181 NamespaceDecl *PrevNS) {
6182 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006183
Richard Smithc969e6a2012-10-05 01:46:25 +00006184 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6185 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6186 // inline namespaces, with the intention of bringing names into namespace std.
6187 //
6188 // We support this just well enough to get that case working; this is not
6189 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006190 if (*IsInline && II && II->getName().startswith("__atomic") &&
6191 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006192 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006193 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6194 NS = NS->getPreviousDecl())
6195 NS->setInline(*IsInline);
6196 // Patch up the lookup table for the containing namespace. This isn't really
6197 // correct, but it's good enough for this particular case.
6198 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6199 E = PrevNS->decls_end(); I != E; ++I)
6200 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6201 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6202 return;
6203 }
6204
6205 if (PrevNS->isInline())
6206 // The user probably just forgot the 'inline', so suggest that it
6207 // be added back.
6208 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6209 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6210 else
6211 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6212 << IsInline;
6213
6214 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6215 *IsInline = PrevNS->isInline();
6216}
John McCallea318642010-08-26 09:15:37 +00006217
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006218/// ActOnStartNamespaceDef - This is called at the start of a namespace
6219/// definition.
John McCalld226f652010-08-21 09:40:31 +00006220Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006221 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006222 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006223 SourceLocation IdentLoc,
6224 IdentifierInfo *II,
6225 SourceLocation LBrace,
6226 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006227 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6228 // For anonymous namespace, take the location of the left brace.
6229 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006230 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006231 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006232 bool IsStd = false;
6233 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006234 Scope *DeclRegionScope = NamespcScope->getParent();
6235
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006236 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006237 if (II) {
6238 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006239 // The identifier in an original-namespace-definition shall not
6240 // have been previously defined in the declarative region in
6241 // which the original-namespace-definition appears. The
6242 // identifier in an original-namespace-definition is the name of
6243 // the namespace. Subsequently in that declarative region, it is
6244 // treated as an original-namespace-name.
6245 //
6246 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006247 // look through using directives, just look for any ordinary names.
6248
6249 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006250 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6251 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006252 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006253 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6254 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6255 ++I) {
6256 if ((*I)->getIdentifierNamespace() & IDNS) {
6257 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006258 break;
6259 }
6260 }
6261
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006262 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6263
6264 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006265 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006266 if (IsInline != PrevNS->isInline())
6267 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6268 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006269 } else if (PrevDecl) {
6270 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006271 Diag(Loc, diag::err_redefinition_different_kind)
6272 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006273 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006274 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006275 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006276 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006277 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006278 // This is the first "real" definition of the namespace "std", so update
6279 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006280 PrevNS = getStdNamespace();
6281 IsStd = true;
6282 AddToKnown = !IsInline;
6283 } else {
6284 // We've seen this namespace for the first time.
6285 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006286 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006287 } else {
John McCall9aeed322009-10-01 00:25:31 +00006288 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006289
6290 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006291 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006292 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006293 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006294 } else {
6295 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006296 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006297 }
6298
Richard Smithd1a55a62012-10-04 22:13:39 +00006299 if (PrevNS && IsInline != PrevNS->isInline())
6300 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6301 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006302 }
6303
6304 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6305 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006306 if (IsInvalid)
6307 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006308
6309 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006310
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006311 // FIXME: Should we be merging attributes?
6312 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006313 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006314
6315 if (IsStd)
6316 StdNamespace = Namespc;
6317 if (AddToKnown)
6318 KnownNamespaces[Namespc] = false;
6319
6320 if (II) {
6321 PushOnScopeChains(Namespc, DeclRegionScope);
6322 } else {
6323 // Link the anonymous namespace into its parent.
6324 DeclContext *Parent = CurContext->getRedeclContext();
6325 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6326 TU->setAnonymousNamespace(Namespc);
6327 } else {
6328 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006329 }
John McCall9aeed322009-10-01 00:25:31 +00006330
Douglas Gregora4181472010-03-24 00:46:35 +00006331 CurContext->addDecl(Namespc);
6332
John McCall9aeed322009-10-01 00:25:31 +00006333 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6334 // behaves as if it were replaced by
6335 // namespace unique { /* empty body */ }
6336 // using namespace unique;
6337 // namespace unique { namespace-body }
6338 // where all occurrences of 'unique' in a translation unit are
6339 // replaced by the same identifier and this identifier differs
6340 // from all other identifiers in the entire program.
6341
6342 // We just create the namespace with an empty name and then add an
6343 // implicit using declaration, just like the standard suggests.
6344 //
6345 // CodeGen enforces the "universally unique" aspect by giving all
6346 // declarations semantically contained within an anonymous
6347 // namespace internal linkage.
6348
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006349 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006350 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006351 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006352 /* 'using' */ LBrace,
6353 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006354 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006355 /* identifier */ SourceLocation(),
6356 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006357 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006358 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006359 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006360 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006361 }
6362
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006363 ActOnDocumentableDecl(Namespc);
6364
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006365 // Although we could have an invalid decl (i.e. the namespace name is a
6366 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006367 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6368 // for the namespace has the declarations that showed up in that particular
6369 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006370 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006371 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006372}
6373
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006374/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6375/// is a namespace alias, returns the namespace it points to.
6376static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6377 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6378 return AD->getNamespace();
6379 return dyn_cast_or_null<NamespaceDecl>(D);
6380}
6381
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006382/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6383/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006384void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006385 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6386 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006387 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006388 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006389 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006390 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006391}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006392
John McCall384aff82010-08-25 07:42:41 +00006393CXXRecordDecl *Sema::getStdBadAlloc() const {
6394 return cast_or_null<CXXRecordDecl>(
6395 StdBadAlloc.get(Context.getExternalSource()));
6396}
6397
6398NamespaceDecl *Sema::getStdNamespace() const {
6399 return cast_or_null<NamespaceDecl>(
6400 StdNamespace.get(Context.getExternalSource()));
6401}
6402
Douglas Gregor66992202010-06-29 17:53:46 +00006403/// \brief Retrieve the special "std" namespace, which may require us to
6404/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006405NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006406 if (!StdNamespace) {
6407 // The "std" namespace has not yet been defined, so build one implicitly.
6408 StdNamespace = NamespaceDecl::Create(Context,
6409 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006410 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006411 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006412 &PP.getIdentifierTable().get("std"),
6413 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006414 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006415 }
6416
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006417 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006418}
6419
Sebastian Redl395e04d2012-01-17 22:49:33 +00006420bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006421 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006422 "Looking for std::initializer_list outside of C++.");
6423
6424 // We're looking for implicit instantiations of
6425 // template <typename E> class std::initializer_list.
6426
6427 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6428 return false;
6429
Sebastian Redl84760e32012-01-17 22:49:58 +00006430 ClassTemplateDecl *Template = 0;
6431 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006432
Sebastian Redl84760e32012-01-17 22:49:58 +00006433 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006434
Sebastian Redl84760e32012-01-17 22:49:58 +00006435 ClassTemplateSpecializationDecl *Specialization =
6436 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6437 if (!Specialization)
6438 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006439
Sebastian Redl84760e32012-01-17 22:49:58 +00006440 Template = Specialization->getSpecializedTemplate();
6441 Arguments = Specialization->getTemplateArgs().data();
6442 } else if (const TemplateSpecializationType *TST =
6443 Ty->getAs<TemplateSpecializationType>()) {
6444 Template = dyn_cast_or_null<ClassTemplateDecl>(
6445 TST->getTemplateName().getAsTemplateDecl());
6446 Arguments = TST->getArgs();
6447 }
6448 if (!Template)
6449 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006450
6451 if (!StdInitializerList) {
6452 // Haven't recognized std::initializer_list yet, maybe this is it.
6453 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6454 if (TemplateClass->getIdentifier() !=
6455 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006456 !getStdNamespace()->InEnclosingNamespaceSetOf(
6457 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006458 return false;
6459 // This is a template called std::initializer_list, but is it the right
6460 // template?
6461 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006462 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006463 return false;
6464 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6465 return false;
6466
6467 // It's the right template.
6468 StdInitializerList = Template;
6469 }
6470
6471 if (Template != StdInitializerList)
6472 return false;
6473
6474 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006475 if (Element)
6476 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006477 return true;
6478}
6479
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006480static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6481 NamespaceDecl *Std = S.getStdNamespace();
6482 if (!Std) {
6483 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6484 return 0;
6485 }
6486
6487 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6488 Loc, Sema::LookupOrdinaryName);
6489 if (!S.LookupQualifiedName(Result, Std)) {
6490 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6491 return 0;
6492 }
6493 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6494 if (!Template) {
6495 Result.suppressDiagnostics();
6496 // We found something weird. Complain about the first thing we found.
6497 NamedDecl *Found = *Result.begin();
6498 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6499 return 0;
6500 }
6501
6502 // We found some template called std::initializer_list. Now verify that it's
6503 // correct.
6504 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006505 if (Params->getMinRequiredArguments() != 1 ||
6506 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006507 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6508 return 0;
6509 }
6510
6511 return Template;
6512}
6513
6514QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6515 if (!StdInitializerList) {
6516 StdInitializerList = LookupStdInitializerList(*this, Loc);
6517 if (!StdInitializerList)
6518 return QualType();
6519 }
6520
6521 TemplateArgumentListInfo Args(Loc, Loc);
6522 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6523 Context.getTrivialTypeSourceInfo(Element,
6524 Loc)));
6525 return Context.getCanonicalType(
6526 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6527}
6528
Sebastian Redl98d36062012-01-17 22:50:14 +00006529bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6530 // C++ [dcl.init.list]p2:
6531 // A constructor is an initializer-list constructor if its first parameter
6532 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6533 // std::initializer_list<E> for some type E, and either there are no other
6534 // parameters or else all other parameters have default arguments.
6535 if (Ctor->getNumParams() < 1 ||
6536 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6537 return false;
6538
6539 QualType ArgType = Ctor->getParamDecl(0)->getType();
6540 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6541 ArgType = RT->getPointeeType().getUnqualifiedType();
6542
6543 return isStdInitializerList(ArgType, 0);
6544}
6545
Douglas Gregor9172aa62011-03-26 22:25:30 +00006546/// \brief Determine whether a using statement is in a context where it will be
6547/// apply in all contexts.
6548static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6549 switch (CurContext->getDeclKind()) {
6550 case Decl::TranslationUnit:
6551 return true;
6552 case Decl::LinkageSpec:
6553 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6554 default:
6555 return false;
6556 }
6557}
6558
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006559namespace {
6560
6561// Callback to only accept typo corrections that are namespaces.
6562class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6563 public:
6564 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6565 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6566 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6567 }
6568 return false;
6569 }
6570};
6571
6572}
6573
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006574static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6575 CXXScopeSpec &SS,
6576 SourceLocation IdentLoc,
6577 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006578 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006579 R.clear();
6580 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006581 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006582 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006583 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6584 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006585 if (DeclContext *DC = S.computeDeclContext(SS, false))
6586 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6587 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006588 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6589 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006590 else
6591 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6592 << Ident << CorrectedQuotedStr
6593 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006594
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006595 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6596 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006597
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006598 R.addDecl(Corrected.getCorrectionDecl());
6599 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006600 }
6601 return false;
6602}
6603
John McCalld226f652010-08-21 09:40:31 +00006604Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006605 SourceLocation UsingLoc,
6606 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006607 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006608 SourceLocation IdentLoc,
6609 IdentifierInfo *NamespcName,
6610 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006611 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6612 assert(NamespcName && "Invalid NamespcName.");
6613 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006614
6615 // This can only happen along a recovery path.
6616 while (S->getFlags() & Scope::TemplateParamScope)
6617 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006618 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006619
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006620 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006621 NestedNameSpecifier *Qualifier = 0;
6622 if (SS.isSet())
6623 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6624
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006625 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006626 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6627 LookupParsedName(R, S, &SS);
6628 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006629 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006630
Douglas Gregor66992202010-06-29 17:53:46 +00006631 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006632 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006633 // Allow "using namespace std;" or "using namespace ::std;" even if
6634 // "std" hasn't been defined yet, for GCC compatibility.
6635 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6636 NamespcName->isStr("std")) {
6637 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006638 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006639 R.resolveKind();
6640 }
6641 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006642 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006643 }
6644
John McCallf36e02d2009-10-09 21:13:30 +00006645 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006646 NamedDecl *Named = R.getFoundDecl();
6647 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6648 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006649 // C++ [namespace.udir]p1:
6650 // A using-directive specifies that the names in the nominated
6651 // namespace can be used in the scope in which the
6652 // using-directive appears after the using-directive. During
6653 // unqualified name lookup (3.4.1), the names appear as if they
6654 // were declared in the nearest enclosing namespace which
6655 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006656 // namespace. [Note: in this context, "contains" means "contains
6657 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006658
6659 // Find enclosing context containing both using-directive and
6660 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006661 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006662 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6663 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6664 CommonAncestor = CommonAncestor->getParent();
6665
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006666 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006667 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006668 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006669
Douglas Gregor9172aa62011-03-26 22:25:30 +00006670 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006671 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006672 Diag(IdentLoc, diag::warn_using_directive_in_header);
6673 }
6674
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006675 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006676 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006677 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006678 }
6679
Richard Smith6b3d3e52013-02-20 19:22:51 +00006680 if (UDir)
6681 ProcessDeclAttributeList(S, UDir, AttrList);
6682
John McCalld226f652010-08-21 09:40:31 +00006683 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006684}
6685
6686void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006687 // If the scope has an associated entity and the using directive is at
6688 // namespace or translation unit scope, add the UsingDirectiveDecl into
6689 // its lookup structure so qualified name lookup can find it.
6690 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6691 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006692 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006693 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006694 // Otherwise, it is at block sope. The using-directives will affect lookup
6695 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006696 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006697}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006698
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006699
John McCalld226f652010-08-21 09:40:31 +00006700Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006701 AccessSpecifier AS,
6702 bool HasUsingKeyword,
6703 SourceLocation UsingLoc,
6704 CXXScopeSpec &SS,
6705 UnqualifiedId &Name,
6706 AttributeList *AttrList,
6707 bool IsTypeName,
6708 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006709 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006710
Douglas Gregor12c118a2009-11-04 16:30:06 +00006711 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006712 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006713 case UnqualifiedId::IK_Identifier:
6714 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006715 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006716 case UnqualifiedId::IK_ConversionFunctionId:
6717 break;
6718
6719 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006720 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006721 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006722 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006723 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006724 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006725 diag::err_using_decl_constructor)
6726 << SS.getRange();
6727
Richard Smith80ad52f2013-01-02 11:42:31 +00006728 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006729
John McCalld226f652010-08-21 09:40:31 +00006730 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006731
6732 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006733 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006734 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006735 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006736
6737 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006738 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006739 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006740 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006741 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006742
6743 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6744 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006745 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006746 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006747
Richard Smith07b0fdc2013-03-18 21:12:30 +00006748 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006749 // TODO: store that the declaration was written without 'using' and
6750 // talk about access decls instead of using decls in the
6751 // diagnostics.
6752 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006753 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006754
6755 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006756 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006757 }
6758
Douglas Gregor56c04582010-12-16 00:46:58 +00006759 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6760 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6761 return 0;
6762
John McCall9488ea12009-11-17 05:59:44 +00006763 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006764 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006765 /* IsInstantiation */ false,
6766 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006767 if (UD)
6768 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006769
John McCalld226f652010-08-21 09:40:31 +00006770 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006771}
6772
Douglas Gregor09acc982010-07-07 23:08:52 +00006773/// \brief Determine whether a using declaration considers the given
6774/// declarations as "equivalent", e.g., if they are redeclarations of
6775/// the same entity or are both typedefs of the same type.
6776static bool
6777IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6778 bool &SuppressRedeclaration) {
6779 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6780 SuppressRedeclaration = false;
6781 return true;
6782 }
6783
Richard Smith162e1c12011-04-15 14:24:37 +00006784 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6785 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006786 SuppressRedeclaration = true;
6787 return Context.hasSameType(TD1->getUnderlyingType(),
6788 TD2->getUnderlyingType());
6789 }
6790
6791 return false;
6792}
6793
6794
John McCall9f54ad42009-12-10 09:41:52 +00006795/// Determines whether to create a using shadow decl for a particular
6796/// decl, given the set of decls existing prior to this using lookup.
6797bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6798 const LookupResult &Previous) {
6799 // Diagnose finding a decl which is not from a base class of the
6800 // current class. We do this now because there are cases where this
6801 // function will silently decide not to build a shadow decl, which
6802 // will pre-empt further diagnostics.
6803 //
6804 // We don't need to do this in C++0x because we do the check once on
6805 // the qualifier.
6806 //
6807 // FIXME: diagnose the following if we care enough:
6808 // struct A { int foo; };
6809 // struct B : A { using A::foo; };
6810 // template <class T> struct C : A {};
6811 // template <class T> struct D : C<T> { using B::foo; } // <---
6812 // This is invalid (during instantiation) in C++03 because B::foo
6813 // resolves to the using decl in B, which is not a base class of D<T>.
6814 // We can't diagnose it immediately because C<T> is an unknown
6815 // specialization. The UsingShadowDecl in D<T> then points directly
6816 // to A::foo, which will look well-formed when we instantiate.
6817 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006818 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006819 DeclContext *OrigDC = Orig->getDeclContext();
6820
6821 // Handle enums and anonymous structs.
6822 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6823 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6824 while (OrigRec->isAnonymousStructOrUnion())
6825 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6826
6827 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6828 if (OrigDC == CurContext) {
6829 Diag(Using->getLocation(),
6830 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006831 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006832 Diag(Orig->getLocation(), diag::note_using_decl_target);
6833 return true;
6834 }
6835
Douglas Gregordc355712011-02-25 00:36:19 +00006836 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006837 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006838 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006839 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006840 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006841 Diag(Orig->getLocation(), diag::note_using_decl_target);
6842 return true;
6843 }
6844 }
6845
6846 if (Previous.empty()) return false;
6847
6848 NamedDecl *Target = Orig;
6849 if (isa<UsingShadowDecl>(Target))
6850 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6851
John McCalld7533ec2009-12-11 02:33:26 +00006852 // If the target happens to be one of the previous declarations, we
6853 // don't have a conflict.
6854 //
6855 // FIXME: but we might be increasing its access, in which case we
6856 // should redeclare it.
6857 NamedDecl *NonTag = 0, *Tag = 0;
6858 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6859 I != E; ++I) {
6860 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006861 bool Result;
6862 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6863 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006864
6865 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6866 }
6867
John McCall9f54ad42009-12-10 09:41:52 +00006868 if (Target->isFunctionOrFunctionTemplate()) {
6869 FunctionDecl *FD;
6870 if (isa<FunctionTemplateDecl>(Target))
6871 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6872 else
6873 FD = cast<FunctionDecl>(Target);
6874
6875 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006876 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006877 case Ovl_Overload:
6878 return false;
6879
6880 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006881 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006882 break;
6883
6884 // We found a decl with the exact signature.
6885 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006886 // If we're in a record, we want to hide the target, so we
6887 // return true (without a diagnostic) to tell the caller not to
6888 // build a shadow decl.
6889 if (CurContext->isRecord())
6890 return true;
6891
6892 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006893 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006894 break;
6895 }
6896
6897 Diag(Target->getLocation(), diag::note_using_decl_target);
6898 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6899 return true;
6900 }
6901
6902 // Target is not a function.
6903
John McCall9f54ad42009-12-10 09:41:52 +00006904 if (isa<TagDecl>(Target)) {
6905 // No conflict between a tag and a non-tag.
6906 if (!Tag) return false;
6907
John McCall41ce66f2009-12-10 19:51:03 +00006908 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006909 Diag(Target->getLocation(), diag::note_using_decl_target);
6910 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6911 return true;
6912 }
6913
6914 // No conflict between a tag and a non-tag.
6915 if (!NonTag) return false;
6916
John McCall41ce66f2009-12-10 19:51:03 +00006917 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006918 Diag(Target->getLocation(), diag::note_using_decl_target);
6919 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6920 return true;
6921}
6922
John McCall9488ea12009-11-17 05:59:44 +00006923/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006924UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006925 UsingDecl *UD,
6926 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006927
6928 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006929 NamedDecl *Target = Orig;
6930 if (isa<UsingShadowDecl>(Target)) {
6931 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6932 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006933 }
6934
6935 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006936 = UsingShadowDecl::Create(Context, CurContext,
6937 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006938 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006939
6940 Shadow->setAccess(UD->getAccess());
6941 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6942 Shadow->setInvalidDecl();
6943
John McCall9488ea12009-11-17 05:59:44 +00006944 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006945 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006946 else
John McCall604e7f12009-12-08 07:46:18 +00006947 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006948
John McCall604e7f12009-12-08 07:46:18 +00006949
John McCall9f54ad42009-12-10 09:41:52 +00006950 return Shadow;
6951}
John McCall604e7f12009-12-08 07:46:18 +00006952
John McCall9f54ad42009-12-10 09:41:52 +00006953/// Hides a using shadow declaration. This is required by the current
6954/// using-decl implementation when a resolvable using declaration in a
6955/// class is followed by a declaration which would hide or override
6956/// one or more of the using decl's targets; for example:
6957///
6958/// struct Base { void foo(int); };
6959/// struct Derived : Base {
6960/// using Base::foo;
6961/// void foo(int);
6962/// };
6963///
6964/// The governing language is C++03 [namespace.udecl]p12:
6965///
6966/// When a using-declaration brings names from a base class into a
6967/// derived class scope, member functions in the derived class
6968/// override and/or hide member functions with the same name and
6969/// parameter types in a base class (rather than conflicting).
6970///
6971/// There are two ways to implement this:
6972/// (1) optimistically create shadow decls when they're not hidden
6973/// by existing declarations, or
6974/// (2) don't create any shadow decls (or at least don't make them
6975/// visible) until we've fully parsed/instantiated the class.
6976/// The problem with (1) is that we might have to retroactively remove
6977/// a shadow decl, which requires several O(n) operations because the
6978/// decl structures are (very reasonably) not designed for removal.
6979/// (2) avoids this but is very fiddly and phase-dependent.
6980void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006981 if (Shadow->getDeclName().getNameKind() ==
6982 DeclarationName::CXXConversionFunctionName)
6983 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6984
John McCall9f54ad42009-12-10 09:41:52 +00006985 // Remove it from the DeclContext...
6986 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006987
John McCall9f54ad42009-12-10 09:41:52 +00006988 // ...and the scope, if applicable...
6989 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006990 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006991 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006992 }
6993
John McCall9f54ad42009-12-10 09:41:52 +00006994 // ...and the using decl.
6995 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6996
6997 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006998 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006999}
7000
John McCall7ba107a2009-11-18 02:36:19 +00007001/// Builds a using declaration.
7002///
7003/// \param IsInstantiation - Whether this call arises from an
7004/// instantiation of an unresolved using declaration. We treat
7005/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007006NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7007 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007008 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007009 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007010 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007011 bool IsInstantiation,
7012 bool IsTypeName,
7013 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007014 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007015 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007016 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007017
Anders Carlsson550b14b2009-08-28 05:49:21 +00007018 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007019
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007020 if (SS.isEmpty()) {
7021 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007022 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007023 }
Mike Stump1eb44332009-09-09 15:08:12 +00007024
John McCall9f54ad42009-12-10 09:41:52 +00007025 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007026 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007027 ForRedeclaration);
7028 Previous.setHideTags(false);
7029 if (S) {
7030 LookupName(Previous, S);
7031
7032 // It is really dumb that we have to do this.
7033 LookupResult::Filter F = Previous.makeFilter();
7034 while (F.hasNext()) {
7035 NamedDecl *D = F.next();
7036 if (!isDeclInScope(D, CurContext, S))
7037 F.erase();
7038 }
7039 F.done();
7040 } else {
7041 assert(IsInstantiation && "no scope in non-instantiation");
7042 assert(CurContext->isRecord() && "scope not record in instantiation");
7043 LookupQualifiedName(Previous, CurContext);
7044 }
7045
John McCall9f54ad42009-12-10 09:41:52 +00007046 // Check for invalid redeclarations.
7047 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7048 return 0;
7049
7050 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007051 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7052 return 0;
7053
John McCallaf8e6ed2009-11-12 03:15:40 +00007054 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007055 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007056 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007057 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00007058 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00007059 // FIXME: not all declaration name kinds are legal here
7060 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7061 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007062 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007063 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007064 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007065 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7066 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007067 }
John McCalled976492009-12-04 22:46:56 +00007068 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007069 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7070 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007071 }
John McCalled976492009-12-04 22:46:56 +00007072 D->setAccess(AS);
7073 CurContext->addDecl(D);
7074
7075 if (!LookupContext) return D;
7076 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007077
John McCall77bb1aa2010-05-01 00:40:08 +00007078 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007079 UD->setInvalidDecl();
7080 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007081 }
7082
Richard Smithc5a89a12012-04-02 01:30:27 +00007083 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007084 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007085 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007086 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007087 return UD;
7088 }
7089
7090 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007091
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007092 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007093
John McCall604e7f12009-12-08 07:46:18 +00007094 // Unlike most lookups, we don't always want to hide tag
7095 // declarations: tag names are visible through the using declaration
7096 // even if hidden by ordinary names, *except* in a dependent context
7097 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007098 if (!IsInstantiation)
7099 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007100
John McCallb9abd8722012-04-07 03:04:20 +00007101 // For the purposes of this lookup, we have a base object type
7102 // equal to that of the current context.
7103 if (CurContext->isRecord()) {
7104 R.setBaseObjectType(
7105 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7106 }
7107
John McCalla24dc2e2009-11-17 02:14:36 +00007108 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007109
John McCallf36e02d2009-10-09 21:13:30 +00007110 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00007111 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007112 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007113 UD->setInvalidDecl();
7114 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007115 }
7116
John McCalled976492009-12-04 22:46:56 +00007117 if (R.isAmbiguous()) {
7118 UD->setInvalidDecl();
7119 return UD;
7120 }
Mike Stump1eb44332009-09-09 15:08:12 +00007121
John McCall7ba107a2009-11-18 02:36:19 +00007122 if (IsTypeName) {
7123 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007124 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007125 Diag(IdentLoc, diag::err_using_typename_non_type);
7126 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7127 Diag((*I)->getUnderlyingDecl()->getLocation(),
7128 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007129 UD->setInvalidDecl();
7130 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007131 }
7132 } else {
7133 // If we asked for a non-typename and we got a type, error out,
7134 // but only if this is an instantiation of an unresolved using
7135 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007136 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007137 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7138 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007139 UD->setInvalidDecl();
7140 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007141 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007142 }
7143
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007144 // C++0x N2914 [namespace.udecl]p6:
7145 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007146 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007147 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7148 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007149 UD->setInvalidDecl();
7150 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007151 }
Mike Stump1eb44332009-09-09 15:08:12 +00007152
John McCall9f54ad42009-12-10 09:41:52 +00007153 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7154 if (!CheckUsingShadowDecl(UD, *I, Previous))
7155 BuildUsingShadowDecl(S, UD, *I);
7156 }
John McCall9488ea12009-11-17 05:59:44 +00007157
7158 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007159}
7160
Sebastian Redlf677ea32011-02-05 19:23:19 +00007161/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007162bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7163 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007164
Douglas Gregordc355712011-02-25 00:36:19 +00007165 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007166 assert(SourceType &&
7167 "Using decl naming constructor doesn't have type in scope spec.");
7168 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7169
7170 // Check whether the named type is a direct base class.
7171 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7172 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7173 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7174 BaseIt != BaseE; ++BaseIt) {
7175 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7176 if (CanonicalSourceType == BaseType)
7177 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007178 if (BaseIt->getType()->isDependentType())
7179 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007180 }
7181
7182 if (BaseIt == BaseE) {
7183 // Did not find SourceType in the bases.
7184 Diag(UD->getUsingLocation(),
7185 diag::err_using_decl_constructor_not_in_direct_base)
7186 << UD->getNameInfo().getSourceRange()
7187 << QualType(SourceType, 0) << TargetClass;
7188 return true;
7189 }
7190
Richard Smithc5a89a12012-04-02 01:30:27 +00007191 if (!CurContext->isDependentContext())
7192 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007193
7194 return false;
7195}
7196
John McCall9f54ad42009-12-10 09:41:52 +00007197/// Checks that the given using declaration is not an invalid
7198/// redeclaration. Note that this is checking only for the using decl
7199/// itself, not for any ill-formedness among the UsingShadowDecls.
7200bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7201 bool isTypeName,
7202 const CXXScopeSpec &SS,
7203 SourceLocation NameLoc,
7204 const LookupResult &Prev) {
7205 // C++03 [namespace.udecl]p8:
7206 // C++0x [namespace.udecl]p10:
7207 // A using-declaration is a declaration and can therefore be used
7208 // repeatedly where (and only where) multiple declarations are
7209 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007210 //
John McCall8a726212010-11-29 18:01:58 +00007211 // That's in non-member contexts.
7212 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007213 return false;
7214
7215 NestedNameSpecifier *Qual
7216 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7217
7218 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7219 NamedDecl *D = *I;
7220
7221 bool DTypename;
7222 NestedNameSpecifier *DQual;
7223 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7224 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007225 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007226 } else if (UnresolvedUsingValueDecl *UD
7227 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7228 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007229 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007230 } else if (UnresolvedUsingTypenameDecl *UD
7231 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7232 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007233 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007234 } else continue;
7235
7236 // using decls differ if one says 'typename' and the other doesn't.
7237 // FIXME: non-dependent using decls?
7238 if (isTypeName != DTypename) continue;
7239
7240 // using decls differ if they name different scopes (but note that
7241 // template instantiation can cause this check to trigger when it
7242 // didn't before instantiation).
7243 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7244 Context.getCanonicalNestedNameSpecifier(DQual))
7245 continue;
7246
7247 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007248 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007249 return true;
7250 }
7251
7252 return false;
7253}
7254
John McCall604e7f12009-12-08 07:46:18 +00007255
John McCalled976492009-12-04 22:46:56 +00007256/// Checks that the given nested-name qualifier used in a using decl
7257/// in the current context is appropriately related to the current
7258/// scope. If an error is found, diagnoses it and returns true.
7259bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7260 const CXXScopeSpec &SS,
7261 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007262 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007263
John McCall604e7f12009-12-08 07:46:18 +00007264 if (!CurContext->isRecord()) {
7265 // C++03 [namespace.udecl]p3:
7266 // C++0x [namespace.udecl]p8:
7267 // A using-declaration for a class member shall be a member-declaration.
7268
7269 // If we weren't able to compute a valid scope, it must be a
7270 // dependent class scope.
7271 if (!NamedContext || NamedContext->isRecord()) {
7272 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7273 << SS.getRange();
7274 return true;
7275 }
7276
7277 // Otherwise, everything is known to be fine.
7278 return false;
7279 }
7280
7281 // The current scope is a record.
7282
7283 // If the named context is dependent, we can't decide much.
7284 if (!NamedContext) {
7285 // FIXME: in C++0x, we can diagnose if we can prove that the
7286 // nested-name-specifier does not refer to a base class, which is
7287 // still possible in some cases.
7288
7289 // Otherwise we have to conservatively report that things might be
7290 // okay.
7291 return false;
7292 }
7293
7294 if (!NamedContext->isRecord()) {
7295 // Ideally this would point at the last name in the specifier,
7296 // but we don't have that level of source info.
7297 Diag(SS.getRange().getBegin(),
7298 diag::err_using_decl_nested_name_specifier_is_not_class)
7299 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7300 return true;
7301 }
7302
Douglas Gregor6fb07292010-12-21 07:41:49 +00007303 if (!NamedContext->isDependentContext() &&
7304 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7305 return true;
7306
Richard Smith80ad52f2013-01-02 11:42:31 +00007307 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007308 // C++0x [namespace.udecl]p3:
7309 // In a using-declaration used as a member-declaration, the
7310 // nested-name-specifier shall name a base class of the class
7311 // being defined.
7312
7313 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7314 cast<CXXRecordDecl>(NamedContext))) {
7315 if (CurContext == NamedContext) {
7316 Diag(NameLoc,
7317 diag::err_using_decl_nested_name_specifier_is_current_class)
7318 << SS.getRange();
7319 return true;
7320 }
7321
7322 Diag(SS.getRange().getBegin(),
7323 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7324 << (NestedNameSpecifier*) SS.getScopeRep()
7325 << cast<CXXRecordDecl>(CurContext)
7326 << SS.getRange();
7327 return true;
7328 }
7329
7330 return false;
7331 }
7332
7333 // C++03 [namespace.udecl]p4:
7334 // A using-declaration used as a member-declaration shall refer
7335 // to a member of a base class of the class being defined [etc.].
7336
7337 // Salient point: SS doesn't have to name a base class as long as
7338 // lookup only finds members from base classes. Therefore we can
7339 // diagnose here only if we can prove that that can't happen,
7340 // i.e. if the class hierarchies provably don't intersect.
7341
7342 // TODO: it would be nice if "definitely valid" results were cached
7343 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7344 // need to be repeated.
7345
7346 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007347 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007348
7349 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7350 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7351 Data->Bases.insert(Base);
7352 return true;
7353 }
7354
7355 bool hasDependentBases(const CXXRecordDecl *Class) {
7356 return !Class->forallBases(collect, this);
7357 }
7358
7359 /// Returns true if the base is dependent or is one of the
7360 /// accumulated base classes.
7361 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7362 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7363 return !Data->Bases.count(Base);
7364 }
7365
7366 bool mightShareBases(const CXXRecordDecl *Class) {
7367 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7368 }
7369 };
7370
7371 UserData Data;
7372
7373 // Returns false if we find a dependent base.
7374 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7375 return false;
7376
7377 // Returns false if the class has a dependent base or if it or one
7378 // of its bases is present in the base set of the current context.
7379 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7380 return false;
7381
7382 Diag(SS.getRange().getBegin(),
7383 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7384 << (NestedNameSpecifier*) SS.getScopeRep()
7385 << cast<CXXRecordDecl>(CurContext)
7386 << SS.getRange();
7387
7388 return true;
John McCalled976492009-12-04 22:46:56 +00007389}
7390
Richard Smith162e1c12011-04-15 14:24:37 +00007391Decl *Sema::ActOnAliasDeclaration(Scope *S,
7392 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007393 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007394 SourceLocation UsingLoc,
7395 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007396 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007397 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007398 // Skip up to the relevant declaration scope.
7399 while (S->getFlags() & Scope::TemplateParamScope)
7400 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007401 assert((S->getFlags() & Scope::DeclScope) &&
7402 "got alias-declaration outside of declaration scope");
7403
7404 if (Type.isInvalid())
7405 return 0;
7406
7407 bool Invalid = false;
7408 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7409 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007410 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007411
7412 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7413 return 0;
7414
7415 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007416 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007417 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007418 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7419 TInfo->getTypeLoc().getBeginLoc());
7420 }
Richard Smith162e1c12011-04-15 14:24:37 +00007421
7422 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7423 LookupName(Previous, S);
7424
7425 // Warn about shadowing the name of a template parameter.
7426 if (Previous.isSingleResult() &&
7427 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007428 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007429 Previous.clear();
7430 }
7431
7432 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7433 "name in alias declaration must be an identifier");
7434 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7435 Name.StartLocation,
7436 Name.Identifier, TInfo);
7437
7438 NewTD->setAccess(AS);
7439
7440 if (Invalid)
7441 NewTD->setInvalidDecl();
7442
Richard Smith6b3d3e52013-02-20 19:22:51 +00007443 ProcessDeclAttributeList(S, NewTD, AttrList);
7444
Richard Smith3e4c6c42011-05-05 21:57:07 +00007445 CheckTypedefForVariablyModifiedType(S, NewTD);
7446 Invalid |= NewTD->isInvalidDecl();
7447
Richard Smith162e1c12011-04-15 14:24:37 +00007448 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007449
7450 NamedDecl *NewND;
7451 if (TemplateParamLists.size()) {
7452 TypeAliasTemplateDecl *OldDecl = 0;
7453 TemplateParameterList *OldTemplateParams = 0;
7454
7455 if (TemplateParamLists.size() != 1) {
7456 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007457 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7458 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007459 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007460 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007461
7462 // Only consider previous declarations in the same scope.
7463 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7464 /*ExplicitInstantiationOrSpecialization*/false);
7465 if (!Previous.empty()) {
7466 Redeclaration = true;
7467
7468 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7469 if (!OldDecl && !Invalid) {
7470 Diag(UsingLoc, diag::err_redefinition_different_kind)
7471 << Name.Identifier;
7472
7473 NamedDecl *OldD = Previous.getRepresentativeDecl();
7474 if (OldD->getLocation().isValid())
7475 Diag(OldD->getLocation(), diag::note_previous_definition);
7476
7477 Invalid = true;
7478 }
7479
7480 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7481 if (TemplateParameterListsAreEqual(TemplateParams,
7482 OldDecl->getTemplateParameters(),
7483 /*Complain=*/true,
7484 TPL_TemplateMatch))
7485 OldTemplateParams = OldDecl->getTemplateParameters();
7486 else
7487 Invalid = true;
7488
7489 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7490 if (!Invalid &&
7491 !Context.hasSameType(OldTD->getUnderlyingType(),
7492 NewTD->getUnderlyingType())) {
7493 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7494 // but we can't reasonably accept it.
7495 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7496 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7497 if (OldTD->getLocation().isValid())
7498 Diag(OldTD->getLocation(), diag::note_previous_definition);
7499 Invalid = true;
7500 }
7501 }
7502 }
7503
7504 // Merge any previous default template arguments into our parameters,
7505 // and check the parameter list.
7506 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7507 TPC_TypeAliasTemplate))
7508 return 0;
7509
7510 TypeAliasTemplateDecl *NewDecl =
7511 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7512 Name.Identifier, TemplateParams,
7513 NewTD);
7514
7515 NewDecl->setAccess(AS);
7516
7517 if (Invalid)
7518 NewDecl->setInvalidDecl();
7519 else if (OldDecl)
7520 NewDecl->setPreviousDeclaration(OldDecl);
7521
7522 NewND = NewDecl;
7523 } else {
7524 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7525 NewND = NewTD;
7526 }
Richard Smith162e1c12011-04-15 14:24:37 +00007527
7528 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007529 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007530
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007531 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007532 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007533}
7534
John McCalld226f652010-08-21 09:40:31 +00007535Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007536 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007537 SourceLocation AliasLoc,
7538 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007539 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007540 SourceLocation IdentLoc,
7541 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007542
Anders Carlsson81c85c42009-03-28 23:53:49 +00007543 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007544 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7545 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007546
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007547 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007548 NamedDecl *PrevDecl
7549 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7550 ForRedeclaration);
7551 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7552 PrevDecl = 0;
7553
7554 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007555 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007556 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007557 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007558 // FIXME: At some point, we'll want to create the (redundant)
7559 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007560 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007561 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007562 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007563 }
Mike Stump1eb44332009-09-09 15:08:12 +00007564
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007565 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7566 diag::err_redefinition_different_kind;
7567 Diag(AliasLoc, DiagID) << Alias;
7568 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007569 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007570 }
7571
John McCalla24dc2e2009-11-17 02:14:36 +00007572 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007573 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007574
John McCallf36e02d2009-10-09 21:13:30 +00007575 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007576 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007577 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007578 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007579 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007580 }
Mike Stump1eb44332009-09-09 15:08:12 +00007581
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007582 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007583 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007584 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007585 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007586
John McCall3dbd3d52010-02-16 06:53:13 +00007587 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007588 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007589}
7590
Sean Hunt001cad92011-05-10 00:49:42 +00007591Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007592Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7593 CXXMethodDecl *MD) {
7594 CXXRecordDecl *ClassDecl = MD->getParent();
7595
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007596 // C++ [except.spec]p14:
7597 // An implicitly declared special member function (Clause 12) shall have an
7598 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007599 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007600 if (ClassDecl->isInvalidDecl())
7601 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007602
Sebastian Redl60618fa2011-03-12 11:50:43 +00007603 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007604 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7605 BEnd = ClassDecl->bases_end();
7606 B != BEnd; ++B) {
7607 if (B->isVirtual()) // Handled below.
7608 continue;
7609
Douglas Gregor18274032010-07-03 00:47:00 +00007610 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7611 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007612 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7613 // If this is a deleted function, add it anyway. This might be conformant
7614 // with the standard. This might not. I'm not sure. It might not matter.
7615 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007616 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007617 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007618 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007619
7620 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007621 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7622 BEnd = ClassDecl->vbases_end();
7623 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007624 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7625 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007626 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7627 // If this is a deleted function, add it anyway. This might be conformant
7628 // with the standard. This might not. I'm not sure. It might not matter.
7629 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007630 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007631 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007632 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007633
7634 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007635 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7636 FEnd = ClassDecl->field_end();
7637 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007638 if (F->hasInClassInitializer()) {
7639 if (Expr *E = F->getInClassInitializer())
7640 ExceptSpec.CalledExpr(E);
7641 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007642 // DR1351:
7643 // If the brace-or-equal-initializer of a non-static data member
7644 // invokes a defaulted default constructor of its class or of an
7645 // enclosing class in a potentially evaluated subexpression, the
7646 // program is ill-formed.
7647 //
7648 // This resolution is unworkable: the exception specification of the
7649 // default constructor can be needed in an unevaluated context, in
7650 // particular, in the operand of a noexcept-expression, and we can be
7651 // unable to compute an exception specification for an enclosed class.
7652 //
7653 // We do not allow an in-class initializer to require the evaluation
7654 // of the exception specification for any in-class initializer whose
7655 // definition is not lexically complete.
7656 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007657 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007658 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007659 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7660 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7661 // If this is a deleted function, add it anyway. This might be conformant
7662 // with the standard. This might not. I'm not sure. It might not matter.
7663 // In particular, the problem is that this function never gets called. It
7664 // might just be ill-formed because this function attempts to refer to
7665 // a deleted function here.
7666 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007667 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007668 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007669 }
John McCalle23cf432010-12-14 08:05:40 +00007670
Sean Hunt001cad92011-05-10 00:49:42 +00007671 return ExceptSpec;
7672}
7673
Richard Smith07b0fdc2013-03-18 21:12:30 +00007674Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007675Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7676 CXXRecordDecl *ClassDecl = CD->getParent();
7677
7678 // C++ [except.spec]p14:
7679 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007680 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007681 if (ClassDecl->isInvalidDecl())
7682 return ExceptSpec;
7683
7684 // Inherited constructor.
7685 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7686 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7687 // FIXME: Copying or moving the parameters could add extra exceptions to the
7688 // set, as could the default arguments for the inherited constructor. This
7689 // will be addressed when we implement the resolution of core issue 1351.
7690 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7691
7692 // Direct base-class constructors.
7693 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7694 BEnd = ClassDecl->bases_end();
7695 B != BEnd; ++B) {
7696 if (B->isVirtual()) // Handled below.
7697 continue;
7698
7699 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7700 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7701 if (BaseClassDecl == InheritedDecl)
7702 continue;
7703 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7704 if (Constructor)
7705 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7706 }
7707 }
7708
7709 // Virtual base-class constructors.
7710 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7711 BEnd = ClassDecl->vbases_end();
7712 B != BEnd; ++B) {
7713 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7714 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7715 if (BaseClassDecl == InheritedDecl)
7716 continue;
7717 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7718 if (Constructor)
7719 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7720 }
7721 }
7722
7723 // Field constructors.
7724 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7725 FEnd = ClassDecl->field_end();
7726 F != FEnd; ++F) {
7727 if (F->hasInClassInitializer()) {
7728 if (Expr *E = F->getInClassInitializer())
7729 ExceptSpec.CalledExpr(E);
7730 else if (!F->isInvalidDecl())
7731 Diag(CD->getLocation(),
7732 diag::err_in_class_initializer_references_def_ctor) << CD;
7733 } else if (const RecordType *RecordTy
7734 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7735 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7736 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7737 if (Constructor)
7738 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7739 }
7740 }
7741
Richard Smith07b0fdc2013-03-18 21:12:30 +00007742 return ExceptSpec;
7743}
7744
Richard Smithafb49182012-11-29 01:34:07 +00007745namespace {
7746/// RAII object to register a special member as being currently declared.
7747struct DeclaringSpecialMember {
7748 Sema &S;
7749 Sema::SpecialMemberDecl D;
7750 bool WasAlreadyBeingDeclared;
7751
7752 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7753 : S(S), D(RD, CSM) {
7754 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7755 if (WasAlreadyBeingDeclared)
7756 // This almost never happens, but if it does, ensure that our cache
7757 // doesn't contain a stale result.
7758 S.SpecialMemberCache.clear();
7759
7760 // FIXME: Register a note to be produced if we encounter an error while
7761 // declaring the special member.
7762 }
7763 ~DeclaringSpecialMember() {
7764 if (!WasAlreadyBeingDeclared)
7765 S.SpecialMembersBeingDeclared.erase(D);
7766 }
7767
7768 /// \brief Are we already trying to declare this special member?
7769 bool isAlreadyBeingDeclared() const {
7770 return WasAlreadyBeingDeclared;
7771 }
7772};
7773}
7774
Sean Hunt001cad92011-05-10 00:49:42 +00007775CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7776 CXXRecordDecl *ClassDecl) {
7777 // C++ [class.ctor]p5:
7778 // A default constructor for a class X is a constructor of class X
7779 // that can be called without an argument. If there is no
7780 // user-declared constructor for class X, a default constructor is
7781 // implicitly declared. An implicitly-declared default constructor
7782 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007783 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007784 "Should not build implicit default constructor!");
7785
Richard Smithafb49182012-11-29 01:34:07 +00007786 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7787 if (DSM.isAlreadyBeingDeclared())
7788 return 0;
7789
Richard Smith7756afa2012-06-10 05:43:50 +00007790 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7791 CXXDefaultConstructor,
7792 false);
7793
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007794 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007795 CanQualType ClassType
7796 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007797 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007798 DeclarationName Name
7799 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007800 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007801 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007802 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007803 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007804 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007805 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007806 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007807 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007808
7809 // Build an exception specification pointing back at this constructor.
7810 FunctionProtoType::ExtProtoInfo EPI;
7811 EPI.ExceptionSpecType = EST_Unevaluated;
7812 EPI.ExceptionSpecDecl = DefaultCon;
Dmitri Gribenko55431692013-05-05 00:41:58 +00007813 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007814
Richard Smithbc2a35d2012-12-08 08:32:28 +00007815 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7816 // constructors is easy to compute.
7817 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7818
7819 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007820 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007821
Douglas Gregor18274032010-07-03 00:47:00 +00007822 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007823 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007824
Douglas Gregor23c94db2010-07-02 17:43:08 +00007825 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007826 PushOnScopeChains(DefaultCon, S, false);
7827 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007828
Douglas Gregor32df23e2010-07-01 22:02:46 +00007829 return DefaultCon;
7830}
7831
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007832void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7833 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007834 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007835 !Constructor->doesThisDeclarationHaveABody() &&
7836 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007837 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007838
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007839 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007840 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007841
Eli Friedman9a14db32012-10-18 20:14:08 +00007842 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007843 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007844 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007845 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007846 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007847 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007848 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007849 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007850 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007851
7852 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007853 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007854
7855 Constructor->setUsed();
7856 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007857
7858 if (ASTMutationListener *L = getASTMutationListener()) {
7859 L->CompletedImplicitDefinition(Constructor);
7860 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007861}
7862
Richard Smith7a614d82011-06-11 17:19:42 +00007863void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007864 // Check that any explicitly-defaulted methods have exception specifications
7865 // compatible with their implicit exception specifications.
7866 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007867}
7868
Richard Smith4841ca52013-04-10 05:48:59 +00007869namespace {
7870/// Information on inheriting constructors to declare.
7871class InheritingConstructorInfo {
7872public:
7873 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7874 : SemaRef(SemaRef), Derived(Derived) {
7875 // Mark the constructors that we already have in the derived class.
7876 //
7877 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7878 // unless there is a user-declared constructor with the same signature in
7879 // the class where the using-declaration appears.
7880 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7881 }
7882
7883 void inheritAll(CXXRecordDecl *RD) {
7884 visitAll(RD, &InheritingConstructorInfo::inherit);
7885 }
7886
7887private:
7888 /// Information about an inheriting constructor.
7889 struct InheritingConstructor {
7890 InheritingConstructor()
7891 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7892
7893 /// If \c true, a constructor with this signature is already declared
7894 /// in the derived class.
7895 bool DeclaredInDerived;
7896
7897 /// The constructor which is inherited.
7898 const CXXConstructorDecl *BaseCtor;
7899
7900 /// The derived constructor we declared.
7901 CXXConstructorDecl *DerivedCtor;
7902 };
7903
7904 /// Inheriting constructors with a given canonical type. There can be at
7905 /// most one such non-template constructor, and any number of templated
7906 /// constructors.
7907 struct InheritingConstructorsForType {
7908 InheritingConstructor NonTemplate;
7909 llvm::SmallVector<
7910 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7911
7912 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7913 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7914 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7915 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7916 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7917 false, S.TPL_TemplateMatch))
7918 return Templates[I].second;
7919 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7920 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007921 }
Richard Smith4841ca52013-04-10 05:48:59 +00007922
7923 return NonTemplate;
7924 }
7925 };
7926
7927 /// Get or create the inheriting constructor record for a constructor.
7928 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7929 QualType CtorType) {
7930 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7931 .getEntry(SemaRef, Ctor);
7932 }
7933
7934 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7935
7936 /// Process all constructors for a class.
7937 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7938 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7939 CtorE = RD->ctor_end();
7940 CtorIt != CtorE; ++CtorIt)
7941 (this->*Callback)(*CtorIt);
7942 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7943 I(RD->decls_begin()), E(RD->decls_end());
7944 I != E; ++I) {
7945 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7946 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7947 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007948 }
7949 }
Richard Smith4841ca52013-04-10 05:48:59 +00007950
7951 /// Note that a constructor (or constructor template) was declared in Derived.
7952 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7953 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7954 }
7955
7956 /// Inherit a single constructor.
7957 void inherit(const CXXConstructorDecl *Ctor) {
7958 const FunctionProtoType *CtorType =
7959 Ctor->getType()->castAs<FunctionProtoType>();
7960 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7961 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7962
7963 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7964
7965 // Core issue (no number yet): the ellipsis is always discarded.
7966 if (EPI.Variadic) {
7967 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7968 SemaRef.Diag(Ctor->getLocation(),
7969 diag::note_using_decl_constructor_ellipsis);
7970 EPI.Variadic = false;
7971 }
7972
7973 // Declare a constructor for each number of parameters.
7974 //
7975 // C++11 [class.inhctor]p1:
7976 // The candidate set of inherited constructors from the class X named in
7977 // the using-declaration consists of [... modulo defects ...] for each
7978 // constructor or constructor template of X, the set of constructors or
7979 // constructor templates that results from omitting any ellipsis parameter
7980 // specification and successively omitting parameters with a default
7981 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00007982 unsigned MinParams = minParamsToInherit(Ctor);
7983 unsigned Params = Ctor->getNumParams();
7984 if (Params >= MinParams) {
7985 do
7986 declareCtor(UsingLoc, Ctor,
7987 SemaRef.Context.getFunctionType(
7988 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7989 while (Params > MinParams &&
7990 Ctor->getParamDecl(--Params)->hasDefaultArg());
7991 }
Richard Smith4841ca52013-04-10 05:48:59 +00007992 }
7993
7994 /// Find the using-declaration which specified that we should inherit the
7995 /// constructors of \p Base.
7996 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7997 // No fancy lookup required; just look for the base constructor name
7998 // directly within the derived class.
7999 ASTContext &Context = SemaRef.Context;
8000 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8001 Context.getCanonicalType(Context.getRecordType(Base)));
8002 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8003 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8004 }
8005
8006 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8007 // C++11 [class.inhctor]p3:
8008 // [F]or each constructor template in the candidate set of inherited
8009 // constructors, a constructor template is implicitly declared
8010 if (Ctor->getDescribedFunctionTemplate())
8011 return 0;
8012
8013 // For each non-template constructor in the candidate set of inherited
8014 // constructors other than a constructor having no parameters or a
8015 // copy/move constructor having a single parameter, a constructor is
8016 // implicitly declared [...]
8017 if (Ctor->getNumParams() == 0)
8018 return 1;
8019 if (Ctor->isCopyOrMoveConstructor())
8020 return 2;
8021
8022 // Per discussion on core reflector, never inherit a constructor which
8023 // would become a default, copy, or move constructor of Derived either.
8024 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8025 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8026 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8027 }
8028
8029 /// Declare a single inheriting constructor, inheriting the specified
8030 /// constructor, with the given type.
8031 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8032 QualType DerivedType) {
8033 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8034
8035 // C++11 [class.inhctor]p3:
8036 // ... a constructor is implicitly declared with the same constructor
8037 // characteristics unless there is a user-declared constructor with
8038 // the same signature in the class where the using-declaration appears
8039 if (Entry.DeclaredInDerived)
8040 return;
8041
8042 // C++11 [class.inhctor]p7:
8043 // If two using-declarations declare inheriting constructors with the
8044 // same signature, the program is ill-formed
8045 if (Entry.DerivedCtor) {
8046 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8047 // Only diagnose this once per constructor.
8048 if (Entry.DerivedCtor->isInvalidDecl())
8049 return;
8050 Entry.DerivedCtor->setInvalidDecl();
8051
8052 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8053 SemaRef.Diag(BaseCtor->getLocation(),
8054 diag::note_using_decl_constructor_conflict_current_ctor);
8055 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8056 diag::note_using_decl_constructor_conflict_previous_ctor);
8057 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8058 diag::note_using_decl_constructor_conflict_previous_using);
8059 } else {
8060 // Core issue (no number): if the same inheriting constructor is
8061 // produced by multiple base class constructors from the same base
8062 // class, the inheriting constructor is defined as deleted.
8063 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8064 }
8065
8066 return;
8067 }
8068
8069 ASTContext &Context = SemaRef.Context;
8070 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8071 Context.getCanonicalType(Context.getRecordType(Derived)));
8072 DeclarationNameInfo NameInfo(Name, UsingLoc);
8073
8074 TemplateParameterList *TemplateParams = 0;
8075 if (const FunctionTemplateDecl *FTD =
8076 BaseCtor->getDescribedFunctionTemplate()) {
8077 TemplateParams = FTD->getTemplateParameters();
8078 // We're reusing template parameters from a different DeclContext. This
8079 // is questionable at best, but works out because the template depth in
8080 // both places is guaranteed to be 0.
8081 // FIXME: Rebuild the template parameters in the new context, and
8082 // transform the function type to refer to them.
8083 }
8084
8085 // Build type source info pointing at the using-declaration. This is
8086 // required by template instantiation.
8087 TypeSourceInfo *TInfo =
8088 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8089 FunctionProtoTypeLoc ProtoLoc =
8090 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8091
8092 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8093 Context, Derived, UsingLoc, NameInfo, DerivedType,
8094 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8095 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8096
8097 // Build an unevaluated exception specification for this constructor.
8098 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8099 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8100 EPI.ExceptionSpecType = EST_Unevaluated;
8101 EPI.ExceptionSpecDecl = DerivedCtor;
8102 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8103 FPT->getArgTypes(), EPI));
8104
8105 // Build the parameter declarations.
8106 SmallVector<ParmVarDecl *, 16> ParamDecls;
8107 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8108 TypeSourceInfo *TInfo =
8109 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8110 ParmVarDecl *PD = ParmVarDecl::Create(
8111 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8112 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8113 PD->setScopeInfo(0, I);
8114 PD->setImplicit();
8115 ParamDecls.push_back(PD);
8116 ProtoLoc.setArg(I, PD);
8117 }
8118
8119 // Set up the new constructor.
8120 DerivedCtor->setAccess(BaseCtor->getAccess());
8121 DerivedCtor->setParams(ParamDecls);
8122 DerivedCtor->setInheritedConstructor(BaseCtor);
8123 if (BaseCtor->isDeleted())
8124 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8125
8126 // If this is a constructor template, build the template declaration.
8127 if (TemplateParams) {
8128 FunctionTemplateDecl *DerivedTemplate =
8129 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8130 TemplateParams, DerivedCtor);
8131 DerivedTemplate->setAccess(BaseCtor->getAccess());
8132 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8133 Derived->addDecl(DerivedTemplate);
8134 } else {
8135 Derived->addDecl(DerivedCtor);
8136 }
8137
8138 Entry.BaseCtor = BaseCtor;
8139 Entry.DerivedCtor = DerivedCtor;
8140 }
8141
8142 Sema &SemaRef;
8143 CXXRecordDecl *Derived;
8144 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8145 MapType Map;
8146};
8147}
8148
8149void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8150 // Defer declaring the inheriting constructors until the class is
8151 // instantiated.
8152 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008153 return;
8154
Richard Smith4841ca52013-04-10 05:48:59 +00008155 // Find base classes from which we might inherit constructors.
8156 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8157 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8158 BaseE = ClassDecl->bases_end();
8159 BaseIt != BaseE; ++BaseIt)
8160 if (BaseIt->getInheritConstructors())
8161 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008162
Richard Smith4841ca52013-04-10 05:48:59 +00008163 // Go no further if we're not inheriting any constructors.
8164 if (InheritedBases.empty())
8165 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008166
Richard Smith4841ca52013-04-10 05:48:59 +00008167 // Declare the inherited constructors.
8168 InheritingConstructorInfo ICI(*this, ClassDecl);
8169 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8170 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008171}
8172
Richard Smith07b0fdc2013-03-18 21:12:30 +00008173void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8174 CXXConstructorDecl *Constructor) {
8175 CXXRecordDecl *ClassDecl = Constructor->getParent();
8176 assert(Constructor->getInheritedConstructor() &&
8177 !Constructor->doesThisDeclarationHaveABody() &&
8178 !Constructor->isDeleted());
8179
8180 SynthesizedFunctionScope Scope(*this, Constructor);
8181 DiagnosticErrorTrap Trap(Diags);
8182 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8183 Trap.hasErrorOccurred()) {
8184 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8185 << Context.getTagDeclType(ClassDecl);
8186 Constructor->setInvalidDecl();
8187 return;
8188 }
8189
8190 SourceLocation Loc = Constructor->getLocation();
8191 Constructor->setBody(new (Context) CompoundStmt(Loc));
8192
8193 Constructor->setUsed();
8194 MarkVTableUsed(CurrentLocation, ClassDecl);
8195
8196 if (ASTMutationListener *L = getASTMutationListener()) {
8197 L->CompletedImplicitDefinition(Constructor);
8198 }
8199}
8200
8201
Sean Huntcb45a0f2011-05-12 22:46:25 +00008202Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008203Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8204 CXXRecordDecl *ClassDecl = MD->getParent();
8205
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008206 // C++ [except.spec]p14:
8207 // An implicitly declared special member function (Clause 12) shall have
8208 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008209 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008210 if (ClassDecl->isInvalidDecl())
8211 return ExceptSpec;
8212
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008213 // Direct base-class destructors.
8214 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8215 BEnd = ClassDecl->bases_end();
8216 B != BEnd; ++B) {
8217 if (B->isVirtual()) // Handled below.
8218 continue;
8219
8220 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008221 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008222 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008223 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008224
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008225 // Virtual base-class destructors.
8226 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8227 BEnd = ClassDecl->vbases_end();
8228 B != BEnd; ++B) {
8229 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008230 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008231 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008232 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008233
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008234 // Field destructors.
8235 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8236 FEnd = ClassDecl->field_end();
8237 F != FEnd; ++F) {
8238 if (const RecordType *RecordTy
8239 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008240 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008241 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008242 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008243
Sean Huntcb45a0f2011-05-12 22:46:25 +00008244 return ExceptSpec;
8245}
8246
8247CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8248 // C++ [class.dtor]p2:
8249 // If a class has no user-declared destructor, a destructor is
8250 // declared implicitly. An implicitly-declared destructor is an
8251 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008252 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008253
Richard Smithafb49182012-11-29 01:34:07 +00008254 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8255 if (DSM.isAlreadyBeingDeclared())
8256 return 0;
8257
Douglas Gregor4923aa22010-07-02 20:37:36 +00008258 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008259 CanQualType ClassType
8260 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008261 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008262 DeclarationName Name
8263 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008264 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008265 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008266 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8267 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008268 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008269 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008270 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008271 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008272
8273 // Build an exception specification pointing back at this destructor.
8274 FunctionProtoType::ExtProtoInfo EPI;
8275 EPI.ExceptionSpecType = EST_Unevaluated;
8276 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008277 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008278
Richard Smithbc2a35d2012-12-08 08:32:28 +00008279 AddOverriddenMethods(ClassDecl, Destructor);
8280
8281 // We don't need to use SpecialMemberIsTrivial here; triviality for
8282 // destructors is easy to compute.
8283 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8284
8285 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008286 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008287
Douglas Gregor4923aa22010-07-02 20:37:36 +00008288 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008289 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008290
Douglas Gregor4923aa22010-07-02 20:37:36 +00008291 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008292 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008293 PushOnScopeChains(Destructor, S, false);
8294 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008295
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008296 return Destructor;
8297}
8298
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008299void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008300 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008301 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008302 !Destructor->doesThisDeclarationHaveABody() &&
8303 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008304 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008305 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008306 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008307
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008308 if (Destructor->isInvalidDecl())
8309 return;
8310
Eli Friedman9a14db32012-10-18 20:14:08 +00008311 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008312
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008313 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008314 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8315 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008316
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008317 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008318 Diag(CurrentLocation, diag::note_member_synthesized_at)
8319 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8320
8321 Destructor->setInvalidDecl();
8322 return;
8323 }
8324
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008325 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008326 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008327 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008328 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008329 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008330
8331 if (ASTMutationListener *L = getASTMutationListener()) {
8332 L->CompletedImplicitDefinition(Destructor);
8333 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008334}
8335
Richard Smitha4156b82012-04-21 18:42:51 +00008336/// \brief Perform any semantic analysis which needs to be delayed until all
8337/// pending class member declarations have been parsed.
8338void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008339 // If the context is an invalid C++ class, just suppress these checks.
8340 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8341 if (Record->isInvalidDecl()) {
8342 DelayedDestructorExceptionSpecChecks.clear();
8343 return;
8344 }
8345 }
8346
Richard Smitha4156b82012-04-21 18:42:51 +00008347 // Perform any deferred checking of exception specifications for virtual
8348 // destructors.
8349 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8350 i != e; ++i) {
8351 const CXXDestructorDecl *Dtor =
8352 DelayedDestructorExceptionSpecChecks[i].first;
8353 assert(!Dtor->getParent()->isDependentType() &&
8354 "Should not ever add destructors of templates into the list.");
8355 CheckOverridingFunctionExceptionSpec(Dtor,
8356 DelayedDestructorExceptionSpecChecks[i].second);
8357 }
8358 DelayedDestructorExceptionSpecChecks.clear();
8359}
8360
Richard Smithb9d0b762012-07-27 04:22:15 +00008361void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8362 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008363 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008364 "adjusting dtor exception specs was introduced in c++11");
8365
Sebastian Redl0ee33912011-05-19 05:13:44 +00008366 // C++11 [class.dtor]p3:
8367 // A declaration of a destructor that does not have an exception-
8368 // specification is implicitly considered to have the same exception-
8369 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008370 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008371 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008372 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008373 return;
8374
Chandler Carruth3f224b22011-09-20 04:55:26 +00008375 // Replace the destructor's type, building off the existing one. Fortunately,
8376 // the only thing of interest in the destructor type is its extended info.
8377 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008378 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8379 EPI.ExceptionSpecType = EST_Unevaluated;
8380 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008381 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008382
Sebastian Redl0ee33912011-05-19 05:13:44 +00008383 // FIXME: If the destructor has a body that could throw, and the newly created
8384 // spec doesn't allow exceptions, we should emit a warning, because this
8385 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008386 // However, we don't have a body or an exception specification yet, so it
8387 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008388}
8389
Richard Smith8c889532012-11-14 00:50:40 +00008390/// When generating a defaulted copy or move assignment operator, if a field
8391/// should be copied with __builtin_memcpy rather than via explicit assignments,
8392/// do so. This optimization only applies for arrays of scalars, and for arrays
8393/// of class type where the selected copy/move-assignment operator is trivial.
8394static StmtResult
8395buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8396 Expr *To, Expr *From) {
8397 // Compute the size of the memory buffer to be copied.
8398 QualType SizeType = S.Context.getSizeType();
8399 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8400 S.Context.getTypeSizeInChars(T).getQuantity());
8401
8402 // Take the address of the field references for "from" and "to". We
8403 // directly construct UnaryOperators here because semantic analysis
8404 // does not permit us to take the address of an xvalue.
8405 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8406 S.Context.getPointerType(From->getType()),
8407 VK_RValue, OK_Ordinary, Loc);
8408 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8409 S.Context.getPointerType(To->getType()),
8410 VK_RValue, OK_Ordinary, Loc);
8411
8412 const Type *E = T->getBaseElementTypeUnsafe();
8413 bool NeedsCollectableMemCpy =
8414 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8415
8416 // Create a reference to the __builtin_objc_memmove_collectable function
8417 StringRef MemCpyName = NeedsCollectableMemCpy ?
8418 "__builtin_objc_memmove_collectable" :
8419 "__builtin_memcpy";
8420 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8421 Sema::LookupOrdinaryName);
8422 S.LookupName(R, S.TUScope, true);
8423
8424 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8425 if (!MemCpy)
8426 // Something went horribly wrong earlier, and we will have complained
8427 // about it.
8428 return StmtError();
8429
8430 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8431 VK_RValue, Loc, 0);
8432 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8433
8434 Expr *CallArgs[] = {
8435 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8436 };
8437 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8438 Loc, CallArgs, Loc);
8439
8440 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8441 return S.Owned(Call.takeAs<Stmt>());
8442}
8443
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008444/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008445/// \c To.
8446///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008447/// This routine is used to copy/move the members of a class with an
8448/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008449/// copied are arrays, this routine builds for loops to copy them.
8450///
8451/// \param S The Sema object used for type-checking.
8452///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008453/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008454///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008455/// \param T The type of the expressions being copied/moved. Both expressions
8456/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008457///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008458/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008459///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008460/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008461///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008462/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008463/// Otherwise, it's a non-static member subobject.
8464///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008465/// \param Copying Whether we're copying or moving.
8466///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008467/// \param Depth Internal parameter recording the depth of the recursion.
8468///
Richard Smith8c889532012-11-14 00:50:40 +00008469/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8470/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008471static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008472buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8473 Expr *To, Expr *From,
8474 bool CopyingBaseSubobject, bool Copying,
8475 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008476 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008477 // Each subobject is assigned in the manner appropriate to its type:
8478 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008479 // - if the subobject is of class type, as if by a call to operator= with
8480 // the subobject as the object expression and the corresponding
8481 // subobject of x as a single function argument (as if by explicit
8482 // qualification; that is, ignoring any possible virtual overriding
8483 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008484 //
8485 // C++03 [class.copy]p13:
8486 // - if the subobject is of class type, the copy assignment operator for
8487 // the class is used (as if by explicit qualification; that is,
8488 // ignoring any possible virtual overriding functions in more derived
8489 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008490 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8491 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008492
Douglas Gregor06a9f362010-05-01 20:49:11 +00008493 // Look for operator=.
8494 DeclarationName Name
8495 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8496 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8497 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008498
Richard Smith044c8aa2012-11-13 00:54:12 +00008499 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8500 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008501 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008502 LookupResult::Filter F = OpLookup.makeFilter();
8503 while (F.hasNext()) {
8504 NamedDecl *D = F.next();
8505 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8506 if (Method->isCopyAssignmentOperator() ||
8507 (!Copying && Method->isMoveAssignmentOperator()))
8508 continue;
8509
8510 F.erase();
8511 }
8512 F.done();
John McCallb0207482010-03-16 06:11:48 +00008513 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008514
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008515 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008516 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008517 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008518 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008519 // ambiguities), we need to cast "this" to that subobject type; to
8520 // ensure that we don't go through the virtual call mechanism, we need
8521 // to qualify the operator= name with the base class (see below). However,
8522 // this means that if the base class has a protected copy assignment
8523 // operator, the protected member access check will fail. So, we
8524 // rewrite "protected" access to "public" access in this case, since we
8525 // know by construction that we're calling from a derived class.
8526 if (CopyingBaseSubobject) {
8527 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8528 L != LEnd; ++L) {
8529 if (L.getAccess() == AS_protected)
8530 L.setAccess(AS_public);
8531 }
8532 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008533
Douglas Gregor06a9f362010-05-01 20:49:11 +00008534 // Create the nested-name-specifier that will be used to qualify the
8535 // reference to operator=; this is required to suppress the virtual
8536 // call mechanism.
8537 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008538 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008539 SS.MakeTrivial(S.Context,
8540 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008541 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008542 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008543
Douglas Gregor06a9f362010-05-01 20:49:11 +00008544 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008545 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008546 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008547 /*TemplateKWLoc=*/SourceLocation(),
8548 /*FirstQualifierInScope=*/0,
8549 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008550 /*TemplateArgs=*/0,
8551 /*SuppressQualifierCheck=*/true);
8552 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008553 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008554
Douglas Gregor06a9f362010-05-01 20:49:11 +00008555 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008556
Richard Smith044c8aa2012-11-13 00:54:12 +00008557 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008558 OpEqualRef.takeAs<Expr>(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00008559 Loc, From, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008560 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008561 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008562
Richard Smith8c889532012-11-14 00:50:40 +00008563 // If we built a call to a trivial 'operator=' while copying an array,
8564 // bail out. We'll replace the whole shebang with a memcpy.
8565 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8566 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8567 return StmtResult((Stmt*)0);
8568
Richard Smith044c8aa2012-11-13 00:54:12 +00008569 // Convert to an expression-statement, and clean up any produced
8570 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008571 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008572 }
John McCallb0207482010-03-16 06:11:48 +00008573
Richard Smith044c8aa2012-11-13 00:54:12 +00008574 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008575 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008576 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008577 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008578 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008579 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008580 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008581 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008582 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008583
8584 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008585 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008586
Douglas Gregor06a9f362010-05-01 20:49:11 +00008587 // Construct a loop over the array bounds, e.g.,
8588 //
8589 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8590 //
8591 // that will copy each of the array elements.
8592 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008593
Douglas Gregor06a9f362010-05-01 20:49:11 +00008594 // Create the iteration variable.
8595 IdentifierInfo *IterationVarName = 0;
8596 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008597 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008598 llvm::raw_svector_ostream OS(Str);
8599 OS << "__i" << Depth;
8600 IterationVarName = &S.Context.Idents.get(OS.str());
8601 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008602 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008603 IterationVarName, SizeType,
8604 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008605 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008606
Douglas Gregor06a9f362010-05-01 20:49:11 +00008607 // Initialize the iteration variable to zero.
8608 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008609 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008610
8611 // Create a reference to the iteration variable; we'll use this several
8612 // times throughout.
8613 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008614 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008615 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008616 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8617 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8618
Douglas Gregor06a9f362010-05-01 20:49:11 +00008619 // Create the DeclStmt that holds the iteration variable.
8620 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008621
Douglas Gregor06a9f362010-05-01 20:49:11 +00008622 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008623 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008624 IterationVarRefRVal,
8625 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008626 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008627 IterationVarRefRVal,
8628 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008629 if (!Copying) // Cast to rvalue
8630 From = CastForMoving(S, From);
8631
8632 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008633 StmtResult Copy =
8634 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8635 To, From, CopyingBaseSubobject,
8636 Copying, Depth + 1);
8637 // Bail out if copying fails or if we determined that we should use memcpy.
8638 if (Copy.isInvalid() || !Copy.get())
8639 return Copy;
8640
8641 // Create the comparison against the array bound.
8642 llvm::APInt Upper
8643 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8644 Expr *Comparison
8645 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8646 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8647 BO_NE, S.Context.BoolTy,
8648 VK_RValue, OK_Ordinary, Loc, false);
8649
8650 // Create the pre-increment of the iteration variable.
8651 Expr *Increment
8652 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8653 VK_LValue, OK_Ordinary, Loc);
8654
Douglas Gregor06a9f362010-05-01 20:49:11 +00008655 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008656 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008657 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008658 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008659 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008660}
8661
Richard Smith8c889532012-11-14 00:50:40 +00008662static StmtResult
8663buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8664 Expr *To, Expr *From,
8665 bool CopyingBaseSubobject, bool Copying) {
8666 // Maybe we should use a memcpy?
8667 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8668 T.isTriviallyCopyableType(S.Context))
8669 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8670
8671 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8672 CopyingBaseSubobject,
8673 Copying, 0));
8674
8675 // If we ended up picking a trivial assignment operator for an array of a
8676 // non-trivially-copyable class type, just emit a memcpy.
8677 if (!Result.isInvalid() && !Result.get())
8678 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8679
8680 return Result;
8681}
8682
Richard Smithb9d0b762012-07-27 04:22:15 +00008683Sema::ImplicitExceptionSpecification
8684Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8685 CXXRecordDecl *ClassDecl = MD->getParent();
8686
8687 ImplicitExceptionSpecification ExceptSpec(*this);
8688 if (ClassDecl->isInvalidDecl())
8689 return ExceptSpec;
8690
8691 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8692 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8693 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8694
Douglas Gregorb87786f2010-07-01 17:48:08 +00008695 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008696 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008697 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008698
8699 // It is unspecified whether or not an implicit copy assignment operator
8700 // attempts to deduplicate calls to assignment operators of virtual bases are
8701 // made. As such, this exception specification is effectively unspecified.
8702 // Based on a similar decision made for constness in C++0x, we're erring on
8703 // the side of assuming such calls to be made regardless of whether they
8704 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008705 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8706 BaseEnd = ClassDecl->bases_end();
8707 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008708 if (Base->isVirtual())
8709 continue;
8710
Douglas Gregora376d102010-07-02 21:50:04 +00008711 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008712 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008713 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8714 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008715 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008716 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008717
8718 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8719 BaseEnd = ClassDecl->vbases_end();
8720 Base != BaseEnd; ++Base) {
8721 CXXRecordDecl *BaseClassDecl
8722 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8723 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8724 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008725 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008726 }
8727
Douglas Gregorb87786f2010-07-01 17:48:08 +00008728 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8729 FieldEnd = ClassDecl->field_end();
8730 Field != FieldEnd;
8731 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008732 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008733 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8734 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008735 LookupCopyingAssignment(FieldClassDecl,
8736 ArgQuals | FieldType.getCVRQualifiers(),
8737 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008738 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008739 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008740 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008741
Richard Smithb9d0b762012-07-27 04:22:15 +00008742 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008743}
8744
8745CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8746 // Note: The following rules are largely analoguous to the copy
8747 // constructor rules. Note that virtual bases are not taken into account
8748 // for determining the argument type of the operator. Note also that
8749 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008750 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008751
Richard Smithafb49182012-11-29 01:34:07 +00008752 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8753 if (DSM.isAlreadyBeingDeclared())
8754 return 0;
8755
Sean Hunt30de05c2011-05-14 05:23:20 +00008756 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8757 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00008758 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8759 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00008760 ArgType = ArgType.withConst();
8761 ArgType = Context.getLValueReferenceType(ArgType);
8762
Richard Smitha8942d72013-05-07 03:19:20 +00008763 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8764 CXXCopyAssignment,
8765 Const);
8766
Douglas Gregord3c35902010-07-01 16:36:15 +00008767 // An implicitly-declared copy assignment operator is an inline public
8768 // member of its class.
8769 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008770 SourceLocation ClassLoc = ClassDecl->getLocation();
8771 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00008772 CXXMethodDecl *CopyAssignment =
8773 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8774 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8775 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008776 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008777 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008778 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008779
8780 // Build an exception specification pointing back at this member.
8781 FunctionProtoType::ExtProtoInfo EPI;
8782 EPI.ExceptionSpecType = EST_Unevaluated;
8783 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008784 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008785
Douglas Gregord3c35902010-07-01 16:36:15 +00008786 // Add the parameter to the operator.
8787 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008788 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008789 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008790 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008791 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008792
Richard Smithbc2a35d2012-12-08 08:32:28 +00008793 AddOverriddenMethods(ClassDecl, CopyAssignment);
8794
8795 CopyAssignment->setTrivial(
8796 ClassDecl->needsOverloadResolutionForCopyAssignment()
8797 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8798 : ClassDecl->hasTrivialCopyAssignment());
8799
Richard Smitha8942d72013-05-07 03:19:20 +00008800 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00008801 // .... If the class definition does not explicitly declare a copy
8802 // assignment operator, there is no user-declared move constructor, and
8803 // there is no user-declared move assignment operator, a copy assignment
8804 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008805 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008806 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008807
Richard Smithbc2a35d2012-12-08 08:32:28 +00008808 // Note that we have added this copy-assignment operator.
8809 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8810
8811 if (Scope *S = getScopeForContext(ClassDecl))
8812 PushOnScopeChains(CopyAssignment, S, false);
8813 ClassDecl->addDecl(CopyAssignment);
8814
Douglas Gregord3c35902010-07-01 16:36:15 +00008815 return CopyAssignment;
8816}
8817
Douglas Gregor06a9f362010-05-01 20:49:11 +00008818void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8819 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008820 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008821 CopyAssignOperator->isOverloadedOperator() &&
8822 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008823 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8824 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008825 "DefineImplicitCopyAssignment called for wrong function");
8826
8827 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8828
8829 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8830 CopyAssignOperator->setInvalidDecl();
8831 return;
8832 }
8833
8834 CopyAssignOperator->setUsed();
8835
Eli Friedman9a14db32012-10-18 20:14:08 +00008836 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008837 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008838
8839 // C++0x [class.copy]p30:
8840 // The implicitly-defined or explicitly-defaulted copy assignment operator
8841 // for a non-union class X performs memberwise copy assignment of its
8842 // subobjects. The direct base classes of X are assigned first, in the
8843 // order of their declaration in the base-specifier-list, and then the
8844 // immediate non-static data members of X are assigned, in the order in
8845 // which they were declared in the class definition.
8846
8847 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008848 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008849
8850 // The parameter for the "other" object, which we are copying from.
8851 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8852 Qualifiers OtherQuals = Other->getType().getQualifiers();
8853 QualType OtherRefType = Other->getType();
8854 if (const LValueReferenceType *OtherRef
8855 = OtherRefType->getAs<LValueReferenceType>()) {
8856 OtherRefType = OtherRef->getPointeeType();
8857 OtherQuals = OtherRefType.getQualifiers();
8858 }
8859
8860 // Our location for everything implicitly-generated.
8861 SourceLocation Loc = CopyAssignOperator->getLocation();
8862
8863 // Construct a reference to the "other" object. We'll be using this
8864 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008865 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008866 assert(OtherRef && "Reference to parameter cannot fail!");
8867
8868 // Construct the "this" pointer. We'll be using this throughout the generated
8869 // ASTs.
8870 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8871 assert(This && "Reference to this cannot fail!");
8872
8873 // Assign base classes.
8874 bool Invalid = false;
8875 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8876 E = ClassDecl->bases_end(); Base != E; ++Base) {
8877 // Form the assignment:
8878 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8879 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008880 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008881 Invalid = true;
8882 continue;
8883 }
8884
John McCallf871d0c2010-08-07 06:22:56 +00008885 CXXCastPath BasePath;
8886 BasePath.push_back(Base);
8887
Douglas Gregor06a9f362010-05-01 20:49:11 +00008888 // Construct the "from" expression, which is an implicit cast to the
8889 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008890 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008891 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8892 CK_UncheckedDerivedToBase,
8893 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008894
8895 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008896 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008897
8898 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008899 To = ImpCastExprToType(To.take(),
8900 Context.getCVRQualifiedType(BaseType,
8901 CopyAssignOperator->getTypeQualifiers()),
8902 CK_UncheckedDerivedToBase,
8903 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008904
8905 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008906 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008907 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008908 /*CopyingBaseSubobject=*/true,
8909 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008910 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008911 Diag(CurrentLocation, diag::note_member_synthesized_at)
8912 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8913 CopyAssignOperator->setInvalidDecl();
8914 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008915 }
8916
8917 // Success! Record the copy.
8918 Statements.push_back(Copy.takeAs<Expr>());
8919 }
8920
Douglas Gregor06a9f362010-05-01 20:49:11 +00008921 // Assign non-static members.
8922 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8923 FieldEnd = ClassDecl->field_end();
8924 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008925 if (Field->isUnnamedBitfield())
8926 continue;
8927
Douglas Gregor06a9f362010-05-01 20:49:11 +00008928 // Check for members of reference type; we can't copy those.
8929 if (Field->getType()->isReferenceType()) {
8930 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8931 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8932 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008933 Diag(CurrentLocation, diag::note_member_synthesized_at)
8934 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008935 Invalid = true;
8936 continue;
8937 }
8938
8939 // Check for members of const-qualified, non-class type.
8940 QualType BaseType = Context.getBaseElementType(Field->getType());
8941 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8942 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8943 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8944 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008945 Diag(CurrentLocation, diag::note_member_synthesized_at)
8946 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008947 Invalid = true;
8948 continue;
8949 }
John McCallb77115d2011-06-17 00:18:42 +00008950
8951 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008952 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8953 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008954
8955 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008956 if (FieldType->isIncompleteArrayType()) {
8957 assert(ClassDecl->hasFlexibleArrayMember() &&
8958 "Incomplete array type is not valid");
8959 continue;
8960 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008961
8962 // Build references to the field in the object we're copying from and to.
8963 CXXScopeSpec SS; // Intentionally empty
8964 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8965 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008966 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008967 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008968 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008969 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008970 SS, SourceLocation(), 0,
8971 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008972 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008973 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008974 SS, SourceLocation(), 0,
8975 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008976 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8977 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008978
Douglas Gregor06a9f362010-05-01 20:49:11 +00008979 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008980 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008981 To.get(), From.get(),
8982 /*CopyingBaseSubobject=*/false,
8983 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008984 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008985 Diag(CurrentLocation, diag::note_member_synthesized_at)
8986 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8987 CopyAssignOperator->setInvalidDecl();
8988 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008989 }
8990
8991 // Success! Record the copy.
8992 Statements.push_back(Copy.takeAs<Stmt>());
8993 }
8994
8995 if (!Invalid) {
8996 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008997 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008998
John McCall60d7b3a2010-08-24 06:29:42 +00008999 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009000 if (Return.isInvalid())
9001 Invalid = true;
9002 else {
9003 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009004
9005 if (Trap.hasErrorOccurred()) {
9006 Diag(CurrentLocation, diag::note_member_synthesized_at)
9007 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9008 Invalid = true;
9009 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009010 }
9011 }
9012
9013 if (Invalid) {
9014 CopyAssignOperator->setInvalidDecl();
9015 return;
9016 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009017
9018 StmtResult Body;
9019 {
9020 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009021 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009022 /*isStmtExpr=*/false);
9023 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9024 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009025 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009026
9027 if (ASTMutationListener *L = getASTMutationListener()) {
9028 L->CompletedImplicitDefinition(CopyAssignOperator);
9029 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009030}
9031
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009032Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009033Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9034 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009035
Richard Smithb9d0b762012-07-27 04:22:15 +00009036 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009037 if (ClassDecl->isInvalidDecl())
9038 return ExceptSpec;
9039
9040 // C++0x [except.spec]p14:
9041 // An implicitly declared special member function (Clause 12) shall have an
9042 // exception-specification. [...]
9043
9044 // It is unspecified whether or not an implicit move assignment operator
9045 // attempts to deduplicate calls to assignment operators of virtual bases are
9046 // made. As such, this exception specification is effectively unspecified.
9047 // Based on a similar decision made for constness in C++0x, we're erring on
9048 // the side of assuming such calls to be made regardless of whether they
9049 // actually happen.
9050 // Note that a move constructor is not implicitly declared when there are
9051 // virtual bases, but it can still be user-declared and explicitly defaulted.
9052 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9053 BaseEnd = ClassDecl->bases_end();
9054 Base != BaseEnd; ++Base) {
9055 if (Base->isVirtual())
9056 continue;
9057
9058 CXXRecordDecl *BaseClassDecl
9059 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9060 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009061 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009062 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009063 }
9064
9065 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9066 BaseEnd = ClassDecl->vbases_end();
9067 Base != BaseEnd; ++Base) {
9068 CXXRecordDecl *BaseClassDecl
9069 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9070 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009071 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009072 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009073 }
9074
9075 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9076 FieldEnd = ClassDecl->field_end();
9077 Field != FieldEnd;
9078 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009079 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009080 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009081 if (CXXMethodDecl *MoveAssign =
9082 LookupMovingAssignment(FieldClassDecl,
9083 FieldType.getCVRQualifiers(),
9084 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009085 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009086 }
9087 }
9088
9089 return ExceptSpec;
9090}
9091
Richard Smith1c931be2012-04-02 18:40:40 +00009092/// Determine whether the class type has any direct or indirect virtual base
9093/// classes which have a non-trivial move assignment operator.
9094static bool
9095hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9096 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9097 BaseEnd = ClassDecl->vbases_end();
9098 Base != BaseEnd; ++Base) {
9099 CXXRecordDecl *BaseClass =
9100 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9101
9102 // Try to declare the move assignment. If it would be deleted, then the
9103 // class does not have a non-trivial move assignment.
9104 if (BaseClass->needsImplicitMoveAssignment())
9105 S.DeclareImplicitMoveAssignment(BaseClass);
9106
Richard Smith426391c2012-11-16 00:53:38 +00009107 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009108 return true;
9109 }
9110
9111 return false;
9112}
9113
9114/// Determine whether the given type either has a move constructor or is
9115/// trivially copyable.
9116static bool
9117hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9118 Type = S.Context.getBaseElementType(Type);
9119
9120 // FIXME: Technically, non-trivially-copyable non-class types, such as
9121 // reference types, are supposed to return false here, but that appears
9122 // to be a standard defect.
9123 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009124 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009125 return true;
9126
9127 if (Type.isTriviallyCopyableType(S.Context))
9128 return true;
9129
9130 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009131 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9132 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009133 if (ClassDecl->needsImplicitMoveConstructor())
9134 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009135 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009136 }
9137
Richard Smithe5411b72012-12-01 02:35:44 +00009138 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9139 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009140 if (ClassDecl->needsImplicitMoveAssignment())
9141 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009142 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009143}
9144
9145/// Determine whether all non-static data members and direct or virtual bases
9146/// of class \p ClassDecl have either a move operation, or are trivially
9147/// copyable.
9148static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9149 bool IsConstructor) {
9150 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9151 BaseEnd = ClassDecl->bases_end();
9152 Base != BaseEnd; ++Base) {
9153 if (Base->isVirtual())
9154 continue;
9155
9156 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9157 return false;
9158 }
9159
9160 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9161 BaseEnd = ClassDecl->vbases_end();
9162 Base != BaseEnd; ++Base) {
9163 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9164 return false;
9165 }
9166
9167 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9168 FieldEnd = ClassDecl->field_end();
9169 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009170 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009171 return false;
9172 }
9173
9174 return true;
9175}
9176
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009177CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009178 // C++11 [class.copy]p20:
9179 // If the definition of a class X does not explicitly declare a move
9180 // assignment operator, one will be implicitly declared as defaulted
9181 // if and only if:
9182 //
9183 // - [first 4 bullets]
9184 assert(ClassDecl->needsImplicitMoveAssignment());
9185
Richard Smithafb49182012-11-29 01:34:07 +00009186 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9187 if (DSM.isAlreadyBeingDeclared())
9188 return 0;
9189
Richard Smith1c931be2012-04-02 18:40:40 +00009190 // [Checked after we build the declaration]
9191 // - the move assignment operator would not be implicitly defined as
9192 // deleted,
9193
9194 // [DR1402]:
9195 // - X has no direct or indirect virtual base class with a non-trivial
9196 // move assignment operator, and
9197 // - each of X's non-static data members and direct or virtual base classes
9198 // has a type that either has a move assignment operator or is trivially
9199 // copyable.
9200 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9201 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9202 ClassDecl->setFailedImplicitMoveAssignment();
9203 return 0;
9204 }
9205
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009206 // Note: The following rules are largely analoguous to the move
9207 // constructor rules.
9208
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009209 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9210 QualType RetType = Context.getLValueReferenceType(ArgType);
9211 ArgType = Context.getRValueReferenceType(ArgType);
9212
Richard Smitha8942d72013-05-07 03:19:20 +00009213 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9214 CXXMoveAssignment,
9215 false);
9216
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009217 // An implicitly-declared move assignment operator is an inline public
9218 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009219 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9220 SourceLocation ClassLoc = ClassDecl->getLocation();
9221 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009222 CXXMethodDecl *MoveAssignment =
9223 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9224 /*TInfo=*/0, /*StorageClass=*/SC_None,
9225 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009226 MoveAssignment->setAccess(AS_public);
9227 MoveAssignment->setDefaulted();
9228 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009229
Richard Smithb9d0b762012-07-27 04:22:15 +00009230 // Build an exception specification pointing back at this member.
9231 FunctionProtoType::ExtProtoInfo EPI;
9232 EPI.ExceptionSpecType = EST_Unevaluated;
9233 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009234 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009235
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009236 // Add the parameter to the operator.
9237 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9238 ClassLoc, ClassLoc, /*Id=*/0,
9239 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009240 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009241 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009242
Richard Smithbc2a35d2012-12-08 08:32:28 +00009243 AddOverriddenMethods(ClassDecl, MoveAssignment);
9244
9245 MoveAssignment->setTrivial(
9246 ClassDecl->needsOverloadResolutionForMoveAssignment()
9247 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9248 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009249
9250 // C++0x [class.copy]p9:
9251 // If the definition of a class X does not explicitly declare a move
9252 // assignment operator, one will be implicitly declared as defaulted if and
9253 // only if:
9254 // [...]
9255 // - the move assignment operator would not be implicitly defined as
9256 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009257 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009258 // Cache this result so that we don't try to generate this over and over
9259 // on every lookup, leaking memory and wasting time.
9260 ClassDecl->setFailedImplicitMoveAssignment();
9261 return 0;
9262 }
9263
Richard Smithbc2a35d2012-12-08 08:32:28 +00009264 // Note that we have added this copy-assignment operator.
9265 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9266
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009267 if (Scope *S = getScopeForContext(ClassDecl))
9268 PushOnScopeChains(MoveAssignment, S, false);
9269 ClassDecl->addDecl(MoveAssignment);
9270
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009271 return MoveAssignment;
9272}
9273
9274void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9275 CXXMethodDecl *MoveAssignOperator) {
9276 assert((MoveAssignOperator->isDefaulted() &&
9277 MoveAssignOperator->isOverloadedOperator() &&
9278 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009279 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9280 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009281 "DefineImplicitMoveAssignment called for wrong function");
9282
9283 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9284
9285 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9286 MoveAssignOperator->setInvalidDecl();
9287 return;
9288 }
9289
9290 MoveAssignOperator->setUsed();
9291
Eli Friedman9a14db32012-10-18 20:14:08 +00009292 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009293 DiagnosticErrorTrap Trap(Diags);
9294
9295 // C++0x [class.copy]p28:
9296 // The implicitly-defined or move assignment operator for a non-union class
9297 // X performs memberwise move assignment of its subobjects. The direct base
9298 // classes of X are assigned first, in the order of their declaration in the
9299 // base-specifier-list, and then the immediate non-static data members of X
9300 // are assigned, in the order in which they were declared in the class
9301 // definition.
9302
9303 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009304 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009305
9306 // The parameter for the "other" object, which we are move from.
9307 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9308 QualType OtherRefType = Other->getType()->
9309 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009310 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009311 "Bad argument type of defaulted move assignment");
9312
9313 // Our location for everything implicitly-generated.
9314 SourceLocation Loc = MoveAssignOperator->getLocation();
9315
9316 // Construct a reference to the "other" object. We'll be using this
9317 // throughout the generated ASTs.
9318 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9319 assert(OtherRef && "Reference to parameter cannot fail!");
9320 // Cast to rvalue.
9321 OtherRef = CastForMoving(*this, OtherRef);
9322
9323 // Construct the "this" pointer. We'll be using this throughout the generated
9324 // ASTs.
9325 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9326 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009327
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009328 // Assign base classes.
9329 bool Invalid = false;
9330 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9331 E = ClassDecl->bases_end(); Base != E; ++Base) {
9332 // Form the assignment:
9333 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9334 QualType BaseType = Base->getType().getUnqualifiedType();
9335 if (!BaseType->isRecordType()) {
9336 Invalid = true;
9337 continue;
9338 }
9339
9340 CXXCastPath BasePath;
9341 BasePath.push_back(Base);
9342
9343 // Construct the "from" expression, which is an implicit cast to the
9344 // appropriately-qualified base type.
9345 Expr *From = OtherRef;
9346 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009347 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009348
9349 // Dereference "this".
9350 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9351
9352 // Implicitly cast "this" to the appropriately-qualified base type.
9353 To = ImpCastExprToType(To.take(),
9354 Context.getCVRQualifiedType(BaseType,
9355 MoveAssignOperator->getTypeQualifiers()),
9356 CK_UncheckedDerivedToBase,
9357 VK_LValue, &BasePath);
9358
9359 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009360 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009361 To.get(), From,
9362 /*CopyingBaseSubobject=*/true,
9363 /*Copying=*/false);
9364 if (Move.isInvalid()) {
9365 Diag(CurrentLocation, diag::note_member_synthesized_at)
9366 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9367 MoveAssignOperator->setInvalidDecl();
9368 return;
9369 }
9370
9371 // Success! Record the move.
9372 Statements.push_back(Move.takeAs<Expr>());
9373 }
9374
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009375 // Assign non-static members.
9376 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9377 FieldEnd = ClassDecl->field_end();
9378 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009379 if (Field->isUnnamedBitfield())
9380 continue;
9381
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009382 // Check for members of reference type; we can't move those.
9383 if (Field->getType()->isReferenceType()) {
9384 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9385 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9386 Diag(Field->getLocation(), diag::note_declared_at);
9387 Diag(CurrentLocation, diag::note_member_synthesized_at)
9388 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9389 Invalid = true;
9390 continue;
9391 }
9392
9393 // Check for members of const-qualified, non-class type.
9394 QualType BaseType = Context.getBaseElementType(Field->getType());
9395 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9396 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9397 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9398 Diag(Field->getLocation(), diag::note_declared_at);
9399 Diag(CurrentLocation, diag::note_member_synthesized_at)
9400 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9401 Invalid = true;
9402 continue;
9403 }
9404
9405 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009406 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9407 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009408
9409 QualType FieldType = Field->getType().getNonReferenceType();
9410 if (FieldType->isIncompleteArrayType()) {
9411 assert(ClassDecl->hasFlexibleArrayMember() &&
9412 "Incomplete array type is not valid");
9413 continue;
9414 }
9415
9416 // Build references to the field in the object we're copying from and to.
9417 CXXScopeSpec SS; // Intentionally empty
9418 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9419 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009420 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009421 MemberLookup.resolveKind();
9422 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9423 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009424 SS, SourceLocation(), 0,
9425 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009426 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9427 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009428 SS, SourceLocation(), 0,
9429 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009430 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9431 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9432
9433 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9434 "Member reference with rvalue base must be rvalue except for reference "
9435 "members, which aren't allowed for move assignment.");
9436
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009437 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009438 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009439 To.get(), From.get(),
9440 /*CopyingBaseSubobject=*/false,
9441 /*Copying=*/false);
9442 if (Move.isInvalid()) {
9443 Diag(CurrentLocation, diag::note_member_synthesized_at)
9444 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9445 MoveAssignOperator->setInvalidDecl();
9446 return;
9447 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009448
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009449 // Success! Record the copy.
9450 Statements.push_back(Move.takeAs<Stmt>());
9451 }
9452
9453 if (!Invalid) {
9454 // Add a "return *this;"
9455 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9456
9457 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9458 if (Return.isInvalid())
9459 Invalid = true;
9460 else {
9461 Statements.push_back(Return.takeAs<Stmt>());
9462
9463 if (Trap.hasErrorOccurred()) {
9464 Diag(CurrentLocation, diag::note_member_synthesized_at)
9465 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9466 Invalid = true;
9467 }
9468 }
9469 }
9470
9471 if (Invalid) {
9472 MoveAssignOperator->setInvalidDecl();
9473 return;
9474 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009475
9476 StmtResult Body;
9477 {
9478 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009479 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009480 /*isStmtExpr=*/false);
9481 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9482 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009483 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9484
9485 if (ASTMutationListener *L = getASTMutationListener()) {
9486 L->CompletedImplicitDefinition(MoveAssignOperator);
9487 }
9488}
9489
Richard Smithb9d0b762012-07-27 04:22:15 +00009490Sema::ImplicitExceptionSpecification
9491Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9492 CXXRecordDecl *ClassDecl = MD->getParent();
9493
9494 ImplicitExceptionSpecification ExceptSpec(*this);
9495 if (ClassDecl->isInvalidDecl())
9496 return ExceptSpec;
9497
9498 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9499 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9500 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9501
Douglas Gregor0d405db2010-07-01 20:59:04 +00009502 // C++ [except.spec]p14:
9503 // An implicitly declared special member function (Clause 12) shall have an
9504 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009505 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9506 BaseEnd = ClassDecl->bases_end();
9507 Base != BaseEnd;
9508 ++Base) {
9509 // Virtual bases are handled below.
9510 if (Base->isVirtual())
9511 continue;
9512
Douglas Gregor22584312010-07-02 23:41:54 +00009513 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009514 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009515 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009516 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009517 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009518 }
9519 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9520 BaseEnd = ClassDecl->vbases_end();
9521 Base != BaseEnd;
9522 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009523 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009524 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009525 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009526 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009527 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009528 }
9529 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9530 FieldEnd = ClassDecl->field_end();
9531 Field != FieldEnd;
9532 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009533 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009534 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9535 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009536 LookupCopyingConstructor(FieldClassDecl,
9537 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009538 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009539 }
9540 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009541
Richard Smithb9d0b762012-07-27 04:22:15 +00009542 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009543}
9544
9545CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9546 CXXRecordDecl *ClassDecl) {
9547 // C++ [class.copy]p4:
9548 // If the class definition does not explicitly declare a copy
9549 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009550 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009551
Richard Smithafb49182012-11-29 01:34:07 +00009552 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9553 if (DSM.isAlreadyBeingDeclared())
9554 return 0;
9555
Sean Hunt49634cf2011-05-13 06:10:58 +00009556 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9557 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009558 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009559 if (Const)
9560 ArgType = ArgType.withConst();
9561 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009562
Richard Smith7756afa2012-06-10 05:43:50 +00009563 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9564 CXXCopyConstructor,
9565 Const);
9566
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009567 DeclarationName Name
9568 = Context.DeclarationNames.getCXXConstructorName(
9569 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009570 SourceLocation ClassLoc = ClassDecl->getLocation();
9571 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009572
9573 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009574 // member of its class.
9575 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009576 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009577 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009578 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009579 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009580 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009581
Richard Smithb9d0b762012-07-27 04:22:15 +00009582 // Build an exception specification pointing back at this member.
9583 FunctionProtoType::ExtProtoInfo EPI;
9584 EPI.ExceptionSpecType = EST_Unevaluated;
9585 EPI.ExceptionSpecDecl = CopyConstructor;
9586 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009587 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009588
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009589 // Add the parameter to the constructor.
9590 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009591 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009592 /*IdentifierInfo=*/0,
9593 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009594 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009595 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009596
Richard Smithbc2a35d2012-12-08 08:32:28 +00009597 CopyConstructor->setTrivial(
9598 ClassDecl->needsOverloadResolutionForCopyConstructor()
9599 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9600 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009601
Nico Weberafcc96a2012-01-23 03:19:29 +00009602 // C++11 [class.copy]p8:
9603 // ... If the class definition does not explicitly declare a copy
9604 // constructor, there is no user-declared move constructor, and there is no
9605 // user-declared move assignment operator, a copy constructor is implicitly
9606 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009607 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009608 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009609
Richard Smithbc2a35d2012-12-08 08:32:28 +00009610 // Note that we have declared this constructor.
9611 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9612
9613 if (Scope *S = getScopeForContext(ClassDecl))
9614 PushOnScopeChains(CopyConstructor, S, false);
9615 ClassDecl->addDecl(CopyConstructor);
9616
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009617 return CopyConstructor;
9618}
9619
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009620void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009621 CXXConstructorDecl *CopyConstructor) {
9622 assert((CopyConstructor->isDefaulted() &&
9623 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009624 !CopyConstructor->doesThisDeclarationHaveABody() &&
9625 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009626 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009627
Anders Carlsson63010a72010-04-23 16:24:12 +00009628 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009629 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009630
Eli Friedman9a14db32012-10-18 20:14:08 +00009631 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009632 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009633
David Blaikie93c86172013-01-17 05:26:25 +00009634 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009635 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009636 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009637 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009638 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009639 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009640 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009641 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9642 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009643 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009644 /*isStmtExpr=*/false)
9645 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009646 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009647 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009648
9649 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009650 if (ASTMutationListener *L = getASTMutationListener()) {
9651 L->CompletedImplicitDefinition(CopyConstructor);
9652 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009653}
9654
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009655Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009656Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9657 CXXRecordDecl *ClassDecl = MD->getParent();
9658
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009659 // C++ [except.spec]p14:
9660 // An implicitly declared special member function (Clause 12) shall have an
9661 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009662 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009663 if (ClassDecl->isInvalidDecl())
9664 return ExceptSpec;
9665
9666 // Direct base-class constructors.
9667 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9668 BEnd = ClassDecl->bases_end();
9669 B != BEnd; ++B) {
9670 if (B->isVirtual()) // Handled below.
9671 continue;
9672
9673 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9674 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009675 CXXConstructorDecl *Constructor =
9676 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009677 // If this is a deleted function, add it anyway. This might be conformant
9678 // with the standard. This might not. I'm not sure. It might not matter.
9679 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009680 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009681 }
9682 }
9683
9684 // Virtual base-class constructors.
9685 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9686 BEnd = ClassDecl->vbases_end();
9687 B != BEnd; ++B) {
9688 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9689 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009690 CXXConstructorDecl *Constructor =
9691 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009692 // If this is a deleted function, add it anyway. This might be conformant
9693 // with the standard. This might not. I'm not sure. It might not matter.
9694 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009695 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009696 }
9697 }
9698
9699 // Field constructors.
9700 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9701 FEnd = ClassDecl->field_end();
9702 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009703 QualType FieldType = Context.getBaseElementType(F->getType());
9704 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9705 CXXConstructorDecl *Constructor =
9706 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009707 // If this is a deleted function, add it anyway. This might be conformant
9708 // with the standard. This might not. I'm not sure. It might not matter.
9709 // In particular, the problem is that this function never gets called. It
9710 // might just be ill-formed because this function attempts to refer to
9711 // a deleted function here.
9712 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009713 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009714 }
9715 }
9716
9717 return ExceptSpec;
9718}
9719
9720CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9721 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009722 // C++11 [class.copy]p9:
9723 // If the definition of a class X does not explicitly declare a move
9724 // constructor, one will be implicitly declared as defaulted if and only if:
9725 //
9726 // - [first 4 bullets]
9727 assert(ClassDecl->needsImplicitMoveConstructor());
9728
Richard Smithafb49182012-11-29 01:34:07 +00009729 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9730 if (DSM.isAlreadyBeingDeclared())
9731 return 0;
9732
Richard Smith1c931be2012-04-02 18:40:40 +00009733 // [Checked after we build the declaration]
9734 // - the move assignment operator would not be implicitly defined as
9735 // deleted,
9736
9737 // [DR1402]:
9738 // - each of X's non-static data members and direct or virtual base classes
9739 // has a type that either has a move constructor or is trivially copyable.
9740 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9741 ClassDecl->setFailedImplicitMoveConstructor();
9742 return 0;
9743 }
9744
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009745 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9746 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009747
Richard Smith7756afa2012-06-10 05:43:50 +00009748 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9749 CXXMoveConstructor,
9750 false);
9751
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009752 DeclarationName Name
9753 = Context.DeclarationNames.getCXXConstructorName(
9754 Context.getCanonicalType(ClassType));
9755 SourceLocation ClassLoc = ClassDecl->getLocation();
9756 DeclarationNameInfo NameInfo(Name, ClassLoc);
9757
Richard Smitha8942d72013-05-07 03:19:20 +00009758 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009759 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009760 // member of its class.
9761 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009762 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009763 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009764 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009765 MoveConstructor->setAccess(AS_public);
9766 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009767
Richard Smithb9d0b762012-07-27 04:22:15 +00009768 // Build an exception specification pointing back at this member.
9769 FunctionProtoType::ExtProtoInfo EPI;
9770 EPI.ExceptionSpecType = EST_Unevaluated;
9771 EPI.ExceptionSpecDecl = MoveConstructor;
9772 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009773 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009774
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009775 // Add the parameter to the constructor.
9776 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9777 ClassLoc, ClassLoc,
9778 /*IdentifierInfo=*/0,
9779 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009780 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009781 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009782
Richard Smithbc2a35d2012-12-08 08:32:28 +00009783 MoveConstructor->setTrivial(
9784 ClassDecl->needsOverloadResolutionForMoveConstructor()
9785 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9786 : ClassDecl->hasTrivialMoveConstructor());
9787
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009788 // C++0x [class.copy]p9:
9789 // If the definition of a class X does not explicitly declare a move
9790 // constructor, one will be implicitly declared as defaulted if and only if:
9791 // [...]
9792 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009793 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009794 // Cache this result so that we don't try to generate this over and over
9795 // on every lookup, leaking memory and wasting time.
9796 ClassDecl->setFailedImplicitMoveConstructor();
9797 return 0;
9798 }
9799
9800 // Note that we have declared this constructor.
9801 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9802
9803 if (Scope *S = getScopeForContext(ClassDecl))
9804 PushOnScopeChains(MoveConstructor, S, false);
9805 ClassDecl->addDecl(MoveConstructor);
9806
9807 return MoveConstructor;
9808}
9809
9810void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9811 CXXConstructorDecl *MoveConstructor) {
9812 assert((MoveConstructor->isDefaulted() &&
9813 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009814 !MoveConstructor->doesThisDeclarationHaveABody() &&
9815 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009816 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9817
9818 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9819 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9820
Eli Friedman9a14db32012-10-18 20:14:08 +00009821 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009822 DiagnosticErrorTrap Trap(Diags);
9823
David Blaikie93c86172013-01-17 05:26:25 +00009824 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009825 Trap.hasErrorOccurred()) {
9826 Diag(CurrentLocation, diag::note_member_synthesized_at)
9827 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9828 MoveConstructor->setInvalidDecl();
9829 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009830 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009831 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9832 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009833 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009834 /*isStmtExpr=*/false)
9835 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009836 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009837 }
9838
9839 MoveConstructor->setUsed();
9840
9841 if (ASTMutationListener *L = getASTMutationListener()) {
9842 L->CompletedImplicitDefinition(MoveConstructor);
9843 }
9844}
9845
Douglas Gregore4e68d42012-02-15 19:33:52 +00009846bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9847 return FD->isDeleted() &&
9848 (FD->isDefaulted() || FD->isImplicit()) &&
9849 isa<CXXMethodDecl>(FD);
9850}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009851
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009852/// \brief Mark the call operator of the given lambda closure type as "used".
9853static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9854 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009855 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009856 Lambda->lookup(
9857 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009858 CallOperator->setReferenced();
9859 CallOperator->setUsed();
9860}
9861
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009862void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9863 SourceLocation CurrentLocation,
9864 CXXConversionDecl *Conv)
9865{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009866 CXXRecordDecl *Lambda = Conv->getParent();
9867
9868 // Make sure that the lambda call operator is marked used.
9869 markLambdaCallOperatorUsed(*this, Lambda);
9870
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009871 Conv->setUsed();
9872
Eli Friedman9a14db32012-10-18 20:14:08 +00009873 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009874 DiagnosticErrorTrap Trap(Diags);
9875
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009876 // Return the address of the __invoke function.
9877 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9878 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009879 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009880 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9881 VK_LValue, Conv->getLocation()).take();
9882 assert(FunctionRef && "Can't refer to __invoke function?");
9883 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009884 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009885 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009886 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009887
9888 // Fill in the __invoke function with a dummy implementation. IR generation
9889 // will fill in the actual details.
9890 Invoke->setUsed();
9891 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009892 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009893
9894 if (ASTMutationListener *L = getASTMutationListener()) {
9895 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009896 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009897 }
9898}
9899
9900void Sema::DefineImplicitLambdaToBlockPointerConversion(
9901 SourceLocation CurrentLocation,
9902 CXXConversionDecl *Conv)
9903{
9904 Conv->setUsed();
9905
Eli Friedman9a14db32012-10-18 20:14:08 +00009906 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009907 DiagnosticErrorTrap Trap(Diags);
9908
Douglas Gregorac1303e2012-02-22 05:02:47 +00009909 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009910 Expr *This = ActOnCXXThis(CurrentLocation).take();
9911 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009912
Eli Friedman23f02672012-03-01 04:01:32 +00009913 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9914 Conv->getLocation(),
9915 Conv, DerefThis);
9916
9917 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9918 // behavior. Note that only the general conversion function does this
9919 // (since it's unusable otherwise); in the case where we inline the
9920 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009921 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009922 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9923 CK_CopyAndAutoreleaseBlockObject,
9924 BuildBlock.get(), 0, VK_RValue);
9925
9926 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009927 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009928 Conv->setInvalidDecl();
9929 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009930 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009931
Douglas Gregorac1303e2012-02-22 05:02:47 +00009932 // Create the return statement that returns the block from the conversion
9933 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009934 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009935 if (Return.isInvalid()) {
9936 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9937 Conv->setInvalidDecl();
9938 return;
9939 }
9940
9941 // Set the body of the conversion function.
9942 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009943 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009944 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009945 Conv->getLocation()));
9946
Douglas Gregorac1303e2012-02-22 05:02:47 +00009947 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009948 if (ASTMutationListener *L = getASTMutationListener()) {
9949 L->CompletedImplicitDefinition(Conv);
9950 }
9951}
9952
Douglas Gregorf52757d2012-03-10 06:53:13 +00009953/// \brief Determine whether the given list arguments contains exactly one
9954/// "real" (non-default) argument.
9955static bool hasOneRealArgument(MultiExprArg Args) {
9956 switch (Args.size()) {
9957 case 0:
9958 return false;
9959
9960 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009961 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009962 return false;
9963
9964 // fall through
9965 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009966 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009967 }
9968
9969 return false;
9970}
9971
John McCall60d7b3a2010-08-24 06:29:42 +00009972ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009973Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009974 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009975 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009976 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009977 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009978 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009979 unsigned ConstructKind,
9980 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009981 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009982
Douglas Gregor2f599792010-04-02 18:24:57 +00009983 // C++0x [class.copy]p34:
9984 // When certain criteria are met, an implementation is allowed to
9985 // omit the copy/move construction of a class object, even if the
9986 // copy/move constructor and/or destructor for the object have
9987 // side effects. [...]
9988 // - when a temporary class object that has not been bound to a
9989 // reference (12.2) would be copied/moved to a class object
9990 // with the same cv-unqualified type, the copy/move operation
9991 // can be omitted by constructing the temporary object
9992 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009993 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009994 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009995 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009996 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009997 }
Mike Stump1eb44332009-09-09 15:08:12 +00009998
9999 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010000 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010001 IsListInitialization, RequiresZeroInit,
10002 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010003}
10004
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010005/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10006/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010007ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010008Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10009 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010010 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010011 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010012 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010013 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010014 unsigned ConstructKind,
10015 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010016 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010017 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010018 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010019 HadMultipleCandidates,
10020 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010021 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10022 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010023}
10024
John McCall68c6c9a2010-02-02 09:10:11 +000010025void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010026 if (VD->isInvalidDecl()) return;
10027
John McCall68c6c9a2010-02-02 09:10:11 +000010028 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010029 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010030 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010031 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010032
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010033 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010034 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010035 CheckDestructorAccess(VD->getLocation(), Destructor,
10036 PDiag(diag::err_access_dtor_var)
10037 << VD->getDeclName()
10038 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010039 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010040
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010041 if (!VD->hasGlobalStorage()) return;
10042
10043 // Emit warning for non-trivial dtor in global scope (a real global,
10044 // class-static, function-static).
10045 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10046
10047 // TODO: this should be re-enabled for static locals by !CXAAtExit
10048 if (!VD->isStaticLocal())
10049 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010050}
10051
Douglas Gregor39da0b82009-09-09 23:08:42 +000010052/// \brief Given a constructor and the set of arguments provided for the
10053/// constructor, convert the arguments and add any required default arguments
10054/// to form a proper call to this constructor.
10055///
10056/// \returns true if an error occurred, false otherwise.
10057bool
10058Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10059 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010060 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010061 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010062 bool AllowExplicit,
10063 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010064 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10065 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010066 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010067
10068 const FunctionProtoType *Proto
10069 = Constructor->getType()->getAs<FunctionProtoType>();
10070 assert(Proto && "Constructor without a prototype?");
10071 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010072
10073 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010074 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010075 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010076 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010077 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010078
10079 VariadicCallType CallType =
10080 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010081 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010082 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010083 Proto, 0,
10084 llvm::makeArrayRef(Args, NumArgs),
10085 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010086 CallType, AllowExplicit,
10087 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010088 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010089
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010090 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010091
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010092 CheckConstructorCall(Constructor,
10093 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10094 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010095 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010096
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010097 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010098}
10099
Anders Carlsson20d45d22009-12-12 00:32:00 +000010100static inline bool
10101CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10102 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010103 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010104 if (isa<NamespaceDecl>(DC)) {
10105 return SemaRef.Diag(FnDecl->getLocation(),
10106 diag::err_operator_new_delete_declared_in_namespace)
10107 << FnDecl->getDeclName();
10108 }
10109
10110 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010111 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010112 return SemaRef.Diag(FnDecl->getLocation(),
10113 diag::err_operator_new_delete_declared_static)
10114 << FnDecl->getDeclName();
10115 }
10116
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010117 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010118}
10119
Anders Carlsson156c78e2009-12-13 17:53:43 +000010120static inline bool
10121CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10122 CanQualType ExpectedResultType,
10123 CanQualType ExpectedFirstParamType,
10124 unsigned DependentParamTypeDiag,
10125 unsigned InvalidParamTypeDiag) {
10126 QualType ResultType =
10127 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10128
10129 // Check that the result type is not dependent.
10130 if (ResultType->isDependentType())
10131 return SemaRef.Diag(FnDecl->getLocation(),
10132 diag::err_operator_new_delete_dependent_result_type)
10133 << FnDecl->getDeclName() << ExpectedResultType;
10134
10135 // Check that the result type is what we expect.
10136 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10137 return SemaRef.Diag(FnDecl->getLocation(),
10138 diag::err_operator_new_delete_invalid_result_type)
10139 << FnDecl->getDeclName() << ExpectedResultType;
10140
10141 // A function template must have at least 2 parameters.
10142 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10143 return SemaRef.Diag(FnDecl->getLocation(),
10144 diag::err_operator_new_delete_template_too_few_parameters)
10145 << FnDecl->getDeclName();
10146
10147 // The function decl must have at least 1 parameter.
10148 if (FnDecl->getNumParams() == 0)
10149 return SemaRef.Diag(FnDecl->getLocation(),
10150 diag::err_operator_new_delete_too_few_parameters)
10151 << FnDecl->getDeclName();
10152
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010153 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010154 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10155 if (FirstParamType->isDependentType())
10156 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10157 << FnDecl->getDeclName() << ExpectedFirstParamType;
10158
10159 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010160 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010161 ExpectedFirstParamType)
10162 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10163 << FnDecl->getDeclName() << ExpectedFirstParamType;
10164
10165 return false;
10166}
10167
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010168static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010169CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010170 // C++ [basic.stc.dynamic.allocation]p1:
10171 // A program is ill-formed if an allocation function is declared in a
10172 // namespace scope other than global scope or declared static in global
10173 // scope.
10174 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10175 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010176
10177 CanQualType SizeTy =
10178 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10179
10180 // C++ [basic.stc.dynamic.allocation]p1:
10181 // The return type shall be void*. The first parameter shall have type
10182 // std::size_t.
10183 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10184 SizeTy,
10185 diag::err_operator_new_dependent_param_type,
10186 diag::err_operator_new_param_type))
10187 return true;
10188
10189 // C++ [basic.stc.dynamic.allocation]p1:
10190 // The first parameter shall not have an associated default argument.
10191 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010192 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010193 diag::err_operator_new_default_arg)
10194 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10195
10196 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010197}
10198
10199static bool
Richard Smith444d3842012-10-20 08:26:51 +000010200CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010201 // C++ [basic.stc.dynamic.deallocation]p1:
10202 // A program is ill-formed if deallocation functions are declared in a
10203 // namespace scope other than global scope or declared static in global
10204 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010205 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10206 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010207
10208 // C++ [basic.stc.dynamic.deallocation]p2:
10209 // Each deallocation function shall return void and its first parameter
10210 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010211 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10212 SemaRef.Context.VoidPtrTy,
10213 diag::err_operator_delete_dependent_param_type,
10214 diag::err_operator_delete_param_type))
10215 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010216
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010217 return false;
10218}
10219
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010220/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10221/// of this overloaded operator is well-formed. If so, returns false;
10222/// otherwise, emits appropriate diagnostics and returns true.
10223bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010224 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010225 "Expected an overloaded operator declaration");
10226
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010227 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10228
Mike Stump1eb44332009-09-09 15:08:12 +000010229 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010230 // The allocation and deallocation functions, operator new,
10231 // operator new[], operator delete and operator delete[], are
10232 // described completely in 3.7.3. The attributes and restrictions
10233 // found in the rest of this subclause do not apply to them unless
10234 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010235 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010236 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010237
Anders Carlssona3ccda52009-12-12 00:26:23 +000010238 if (Op == OO_New || Op == OO_Array_New)
10239 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010240
10241 // C++ [over.oper]p6:
10242 // An operator function shall either be a non-static member
10243 // function or be a non-member function and have at least one
10244 // parameter whose type is a class, a reference to a class, an
10245 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010246 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10247 if (MethodDecl->isStatic())
10248 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010249 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010250 } else {
10251 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010252 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10253 ParamEnd = FnDecl->param_end();
10254 Param != ParamEnd; ++Param) {
10255 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010256 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10257 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010258 ClassOrEnumParam = true;
10259 break;
10260 }
10261 }
10262
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010263 if (!ClassOrEnumParam)
10264 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010265 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010266 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010267 }
10268
10269 // C++ [over.oper]p8:
10270 // An operator function cannot have default arguments (8.3.6),
10271 // except where explicitly stated below.
10272 //
Mike Stump1eb44332009-09-09 15:08:12 +000010273 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010274 // (C++ [over.call]p1).
10275 if (Op != OO_Call) {
10276 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10277 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010278 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010279 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010280 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010281 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010282 }
10283 }
10284
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010285 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10286 { false, false, false }
10287#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10288 , { Unary, Binary, MemberOnly }
10289#include "clang/Basic/OperatorKinds.def"
10290 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010291
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010292 bool CanBeUnaryOperator = OperatorUses[Op][0];
10293 bool CanBeBinaryOperator = OperatorUses[Op][1];
10294 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010295
10296 // C++ [over.oper]p8:
10297 // [...] Operator functions cannot have more or fewer parameters
10298 // than the number required for the corresponding operator, as
10299 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010300 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010301 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010302 if (Op != OO_Call &&
10303 ((NumParams == 1 && !CanBeUnaryOperator) ||
10304 (NumParams == 2 && !CanBeBinaryOperator) ||
10305 (NumParams < 1) || (NumParams > 2))) {
10306 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010307 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010308 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010309 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010310 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010311 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010312 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010313 assert(CanBeBinaryOperator &&
10314 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010315 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010316 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010317
Chris Lattner416e46f2008-11-21 07:57:12 +000010318 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010319 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010320 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010321
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010322 // Overloaded operators other than operator() cannot be variadic.
10323 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010324 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010325 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010326 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010327 }
10328
10329 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010330 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10331 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010332 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010333 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010334 }
10335
10336 // C++ [over.inc]p1:
10337 // The user-defined function called operator++ implements the
10338 // prefix and postfix ++ operator. If this function is a member
10339 // function with no parameters, or a non-member function with one
10340 // parameter of class or enumeration type, it defines the prefix
10341 // increment operator ++ for objects of that type. If the function
10342 // is a member function with one parameter (which shall be of type
10343 // int) or a non-member function with two parameters (the second
10344 // of which shall be of type int), it defines the postfix
10345 // increment operator ++ for objects of that type.
10346 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10347 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10348 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010349 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010350 ParamIsInt = BT->getKind() == BuiltinType::Int;
10351
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010352 if (!ParamIsInt)
10353 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010354 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010355 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010356 }
10357
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010358 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010359}
Chris Lattner5a003a42008-12-17 07:09:26 +000010360
Sean Hunta6c058d2010-01-13 09:01:02 +000010361/// CheckLiteralOperatorDeclaration - Check whether the declaration
10362/// of this literal operator function is well-formed. If so, returns
10363/// false; otherwise, emits appropriate diagnostics and returns true.
10364bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010365 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010366 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10367 << FnDecl->getDeclName();
10368 return true;
10369 }
10370
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010371 if (FnDecl->isExternC()) {
10372 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10373 return true;
10374 }
10375
Sean Hunta6c058d2010-01-13 09:01:02 +000010376 bool Valid = false;
10377
Richard Smith36f5cfe2012-03-09 08:00:36 +000010378 // This might be the definition of a literal operator template.
10379 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10380 // This might be a specialization of a literal operator template.
10381 if (!TpDecl)
10382 TpDecl = FnDecl->getPrimaryTemplate();
10383
Sean Hunt216c2782010-04-07 23:11:06 +000010384 // template <char...> type operator "" name() is the only valid template
10385 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010386 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010387 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010388 // Must have only one template parameter
10389 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10390 if (Params->size() == 1) {
10391 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010392 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010393
Sean Hunt216c2782010-04-07 23:11:06 +000010394 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010395 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10396 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10397 Valid = true;
10398 }
10399 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010400 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010401 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010402 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10403
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010404 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010405
Sean Hunt30019c02010-04-07 22:57:35 +000010406 // unsigned long long int, long double, and any character type are allowed
10407 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010408 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10409 Context.hasSameType(T, Context.LongDoubleTy) ||
10410 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010411 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010412 Context.hasSameType(T, Context.Char16Ty) ||
10413 Context.hasSameType(T, Context.Char32Ty)) {
10414 if (++Param == FnDecl->param_end())
10415 Valid = true;
10416 goto FinishedParams;
10417 }
10418
Sean Hunt30019c02010-04-07 22:57:35 +000010419 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010420 const PointerType *PT = T->getAs<PointerType>();
10421 if (!PT)
10422 goto FinishedParams;
10423 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010424 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010425 goto FinishedParams;
10426 T = T.getUnqualifiedType();
10427
10428 // Move on to the second parameter;
10429 ++Param;
10430
10431 // If there is no second parameter, the first must be a const char *
10432 if (Param == FnDecl->param_end()) {
10433 if (Context.hasSameType(T, Context.CharTy))
10434 Valid = true;
10435 goto FinishedParams;
10436 }
10437
10438 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10439 // are allowed as the first parameter to a two-parameter function
10440 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010441 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010442 Context.hasSameType(T, Context.Char16Ty) ||
10443 Context.hasSameType(T, Context.Char32Ty)))
10444 goto FinishedParams;
10445
10446 // The second and final parameter must be an std::size_t
10447 T = (*Param)->getType().getUnqualifiedType();
10448 if (Context.hasSameType(T, Context.getSizeType()) &&
10449 ++Param == FnDecl->param_end())
10450 Valid = true;
10451 }
10452
10453 // FIXME: This diagnostic is absolutely terrible.
10454FinishedParams:
10455 if (!Valid) {
10456 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10457 << FnDecl->getDeclName();
10458 return true;
10459 }
10460
Richard Smitha9e88b22012-03-09 08:16:22 +000010461 // A parameter-declaration-clause containing a default argument is not
10462 // equivalent to any of the permitted forms.
10463 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10464 ParamEnd = FnDecl->param_end();
10465 Param != ParamEnd; ++Param) {
10466 if ((*Param)->hasDefaultArg()) {
10467 Diag((*Param)->getDefaultArgRange().getBegin(),
10468 diag::err_literal_operator_default_argument)
10469 << (*Param)->getDefaultArgRange();
10470 break;
10471 }
10472 }
10473
Richard Smith2fb4ae32012-03-08 02:39:21 +000010474 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010475 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10476 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010477 // C++11 [usrlit.suffix]p1:
10478 // Literal suffix identifiers that do not start with an underscore
10479 // are reserved for future standardization.
10480 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010481 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010482
Sean Hunta6c058d2010-01-13 09:01:02 +000010483 return false;
10484}
10485
Douglas Gregor074149e2009-01-05 19:45:36 +000010486/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10487/// linkage specification, including the language and (if present)
10488/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10489/// the location of the language string literal, which is provided
10490/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10491/// the '{' brace. Otherwise, this linkage specification does not
10492/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010493Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10494 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010495 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010496 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010497 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010498 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010499 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010500 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010501 Language = LinkageSpecDecl::lang_cxx;
10502 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010503 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010504 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010505 }
Mike Stump1eb44332009-09-09 15:08:12 +000010506
Chris Lattnercc98eac2008-12-17 07:13:27 +000010507 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010508
Douglas Gregor074149e2009-01-05 19:45:36 +000010509 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010510 ExternLoc, LangLoc, Language,
10511 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010512 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010513 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010514 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010515}
10516
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010517/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010518/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10519/// valid, it's the position of the closing '}' brace in a linkage
10520/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010521Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010522 Decl *LinkageSpec,
10523 SourceLocation RBraceLoc) {
10524 if (LinkageSpec) {
10525 if (RBraceLoc.isValid()) {
10526 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10527 LSDecl->setRBraceLoc(RBraceLoc);
10528 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010529 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010530 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010531 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010532}
10533
Michael Han684aa732013-02-22 17:15:32 +000010534Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10535 AttributeList *AttrList,
10536 SourceLocation SemiLoc) {
10537 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10538 // Attribute declarations appertain to empty declaration so we handle
10539 // them here.
10540 if (AttrList)
10541 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010542
Michael Han684aa732013-02-22 17:15:32 +000010543 CurContext->addDecl(ED);
10544 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010545}
10546
Douglas Gregord308e622009-05-18 20:51:54 +000010547/// \brief Perform semantic analysis for the variable declaration that
10548/// occurs within a C++ catch clause, returning the newly-created
10549/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010550VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010551 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010552 SourceLocation StartLoc,
10553 SourceLocation Loc,
10554 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010555 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010556 QualType ExDeclType = TInfo->getType();
10557
Sebastian Redl4b07b292008-12-22 19:15:10 +000010558 // Arrays and functions decay.
10559 if (ExDeclType->isArrayType())
10560 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10561 else if (ExDeclType->isFunctionType())
10562 ExDeclType = Context.getPointerType(ExDeclType);
10563
10564 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10565 // The exception-declaration shall not denote a pointer or reference to an
10566 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010567 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010568 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010569 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010570 Invalid = true;
10571 }
Douglas Gregord308e622009-05-18 20:51:54 +000010572
Sebastian Redl4b07b292008-12-22 19:15:10 +000010573 QualType BaseType = ExDeclType;
10574 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010575 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010576 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010577 BaseType = Ptr->getPointeeType();
10578 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010579 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010580 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010581 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010582 BaseType = Ref->getPointeeType();
10583 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010584 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010585 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010586 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010587 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010588 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010589
Mike Stump1eb44332009-09-09 15:08:12 +000010590 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010591 RequireNonAbstractType(Loc, ExDeclType,
10592 diag::err_abstract_type_in_decl,
10593 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010594 Invalid = true;
10595
John McCall5a180392010-07-24 00:37:23 +000010596 // Only the non-fragile NeXT runtime currently supports C++ catches
10597 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010598 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010599 QualType T = ExDeclType;
10600 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10601 T = RT->getPointeeType();
10602
10603 if (T->isObjCObjectType()) {
10604 Diag(Loc, diag::err_objc_object_catch);
10605 Invalid = true;
10606 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010607 // FIXME: should this be a test for macosx-fragile specifically?
10608 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010609 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010610 }
10611 }
10612
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010613 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010614 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010615 ExDecl->setExceptionVariable(true);
10616
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010617 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010618 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010619 Invalid = true;
10620
Douglas Gregorc41b8782011-07-06 18:14:43 +000010621 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010622 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010623 // Insulate this from anything else we might currently be parsing.
10624 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10625
Douglas Gregor6d182892010-03-05 23:38:39 +000010626 // C++ [except.handle]p16:
10627 // The object declared in an exception-declaration or, if the
10628 // exception-declaration does not specify a name, a temporary (12.2) is
10629 // copy-initialized (8.5) from the exception object. [...]
10630 // The object is destroyed when the handler exits, after the destruction
10631 // of any automatic objects initialized within the handler.
10632 //
10633 // We just pretend to initialize the object with itself, then make sure
10634 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010635 QualType initType = ExDeclType;
10636
10637 InitializedEntity entity =
10638 InitializedEntity::InitializeVariable(ExDecl);
10639 InitializationKind initKind =
10640 InitializationKind::CreateCopy(Loc, SourceLocation());
10641
10642 Expr *opaqueValue =
10643 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010644 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10645 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010646 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010647 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010648 else {
10649 // If the constructor used was non-trivial, set this as the
10650 // "initializer".
10651 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10652 if (!construct->getConstructor()->isTrivial()) {
10653 Expr *init = MaybeCreateExprWithCleanups(construct);
10654 ExDecl->setInit(init);
10655 }
10656
10657 // And make sure it's destructable.
10658 FinalizeVarWithDestructor(ExDecl, recordType);
10659 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010660 }
10661 }
10662
Douglas Gregord308e622009-05-18 20:51:54 +000010663 if (Invalid)
10664 ExDecl->setInvalidDecl();
10665
10666 return ExDecl;
10667}
10668
10669/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10670/// handler.
John McCalld226f652010-08-21 09:40:31 +000010671Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010672 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010673 bool Invalid = D.isInvalidType();
10674
10675 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010676 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10677 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010678 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10679 D.getIdentifierLoc());
10680 Invalid = true;
10681 }
10682
Sebastian Redl4b07b292008-12-22 19:15:10 +000010683 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010684 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010685 LookupOrdinaryName,
10686 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010687 // The scope should be freshly made just for us. There is just no way
10688 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010689 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010690 if (PrevDecl->isTemplateParameter()) {
10691 // Maybe we will complain about the shadowed template parameter.
10692 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010693 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010694 }
10695 }
10696
Chris Lattnereaaebc72009-04-25 08:06:05 +000010697 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010698 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10699 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010700 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010701 }
10702
Douglas Gregor83cb9422010-09-09 17:09:21 +000010703 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010704 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010705 D.getIdentifierLoc(),
10706 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010707 if (Invalid)
10708 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010709
Sebastian Redl4b07b292008-12-22 19:15:10 +000010710 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010711 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010712 PushOnScopeChains(ExDecl, S);
10713 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010714 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010715
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010716 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010717 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010718}
Anders Carlssonfb311762009-03-14 00:25:26 +000010719
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010720Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010721 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010722 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010723 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010724 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010725
Richard Smithe3f470a2012-07-11 22:37:56 +000010726 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10727 return 0;
10728
10729 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10730 AssertMessage, RParenLoc, false);
10731}
10732
10733Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10734 Expr *AssertExpr,
10735 StringLiteral *AssertMessage,
10736 SourceLocation RParenLoc,
10737 bool Failed) {
10738 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10739 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010740 // In a static_assert-declaration, the constant-expression shall be a
10741 // constant expression that can be contextually converted to bool.
10742 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10743 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010744 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010745
Richard Smithdaaefc52011-12-14 23:32:26 +000010746 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010747 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010748 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010749 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010750 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010751
Richard Smithe3f470a2012-07-11 22:37:56 +000010752 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010753 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010754 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010755 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010756 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010757 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010758 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010759 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010760 }
Mike Stump1eb44332009-09-09 15:08:12 +000010761
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010762 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010763 AssertExpr, AssertMessage, RParenLoc,
10764 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010765
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010766 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010767 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010768}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010769
Douglas Gregor1d869352010-04-07 16:53:43 +000010770/// \brief Perform semantic analysis of the given friend type declaration.
10771///
10772/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010773FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010774 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010775 TypeSourceInfo *TSInfo) {
10776 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10777
10778 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010779 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010780
Richard Smith6b130222011-10-18 21:39:00 +000010781 // C++03 [class.friend]p2:
10782 // An elaborated-type-specifier shall be used in a friend declaration
10783 // for a class.*
10784 //
10785 // * The class-key of the elaborated-type-specifier is required.
10786 if (!ActiveTemplateInstantiations.empty()) {
10787 // Do not complain about the form of friend template types during
10788 // template instantiation; we will already have complained when the
10789 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010790 } else {
10791 if (!T->isElaboratedTypeSpecifier()) {
10792 // If we evaluated the type to a record type, suggest putting
10793 // a tag in front.
10794 if (const RecordType *RT = T->getAs<RecordType>()) {
10795 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010796
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010797 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010798
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010799 Diag(TypeRange.getBegin(),
10800 getLangOpts().CPlusPlus11 ?
10801 diag::warn_cxx98_compat_unelaborated_friend_type :
10802 diag::ext_unelaborated_friend_type)
10803 << (unsigned) RD->getTagKind()
10804 << T
10805 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10806 InsertionText);
10807 } else {
10808 Diag(FriendLoc,
10809 getLangOpts().CPlusPlus11 ?
10810 diag::warn_cxx98_compat_nonclass_type_friend :
10811 diag::ext_nonclass_type_friend)
10812 << T
10813 << TypeRange;
10814 }
10815 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010816 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010817 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010818 diag::warn_cxx98_compat_enum_friend :
10819 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010820 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010821 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010822 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010823
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010824 // C++11 [class.friend]p3:
10825 // A friend declaration that does not declare a function shall have one
10826 // of the following forms:
10827 // friend elaborated-type-specifier ;
10828 // friend simple-type-specifier ;
10829 // friend typename-specifier ;
10830 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10831 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10832 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010833
Douglas Gregor06245bf2010-04-07 17:57:12 +000010834 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010835 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010836 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010837 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010838}
10839
John McCall9a34edb2010-10-19 01:40:49 +000010840/// Handle a friend tag declaration where the scope specifier was
10841/// templated.
10842Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10843 unsigned TagSpec, SourceLocation TagLoc,
10844 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010845 IdentifierInfo *Name,
10846 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010847 AttributeList *Attr,
10848 MultiTemplateParamsArg TempParamLists) {
10849 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10850
10851 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010852 bool Invalid = false;
10853
10854 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010855 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010856 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010857 TempParamLists.size(),
10858 /*friend*/ true,
10859 isExplicitSpecialization,
10860 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010861 if (TemplateParams->size() > 0) {
10862 // This is a declaration of a class template.
10863 if (Invalid)
10864 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010865
Eric Christopher4110e132011-07-21 05:34:24 +000010866 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10867 SS, Name, NameLoc, Attr,
10868 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010869 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010870 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010871 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010872 } else {
10873 // The "template<>" header is extraneous.
10874 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10875 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10876 isExplicitSpecialization = true;
10877 }
10878 }
10879
10880 if (Invalid) return 0;
10881
John McCall9a34edb2010-10-19 01:40:49 +000010882 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010883 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010884 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010885 isAllExplicitSpecializations = false;
10886 break;
10887 }
10888 }
10889
10890 // FIXME: don't ignore attributes.
10891
10892 // If it's explicit specializations all the way down, just forget
10893 // about the template header and build an appropriate non-templated
10894 // friend. TODO: for source fidelity, remember the headers.
10895 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010896 if (SS.isEmpty()) {
10897 bool Owned = false;
10898 bool IsDependent = false;
10899 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10900 Attr, AS_public,
10901 /*ModulePrivateLoc=*/SourceLocation(),
10902 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010903 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010904 /*ScopedEnumUsesClassTag=*/false,
10905 /*UnderlyingType=*/TypeResult());
10906 }
10907
Douglas Gregor2494dd02011-03-01 01:34:45 +000010908 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010909 ElaboratedTypeKeyword Keyword
10910 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010911 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010912 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010913 if (T.isNull())
10914 return 0;
10915
10916 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10917 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010918 DependentNameTypeLoc TL =
10919 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010920 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010921 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010922 TL.setNameLoc(NameLoc);
10923 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010924 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010925 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010926 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010927 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010928 }
10929
10930 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010931 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010932 Friend->setAccess(AS_public);
10933 CurContext->addDecl(Friend);
10934 return Friend;
10935 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010936
10937 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10938
10939
John McCall9a34edb2010-10-19 01:40:49 +000010940
10941 // Handle the case of a templated-scope friend class. e.g.
10942 // template <class T> class A<T>::B;
10943 // FIXME: we don't support these right now.
10944 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10945 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10946 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010947 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010948 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010949 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010950 TL.setNameLoc(NameLoc);
10951
10952 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010953 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010954 Friend->setAccess(AS_public);
10955 Friend->setUnsupportedFriend(true);
10956 CurContext->addDecl(Friend);
10957 return Friend;
10958}
10959
10960
John McCalldd4a3b02009-09-16 22:47:08 +000010961/// Handle a friend type declaration. This works in tandem with
10962/// ActOnTag.
10963///
10964/// Notes on friend class templates:
10965///
10966/// We generally treat friend class declarations as if they were
10967/// declaring a class. So, for example, the elaborated type specifier
10968/// in a friend declaration is required to obey the restrictions of a
10969/// class-head (i.e. no typedefs in the scope chain), template
10970/// parameters are required to match up with simple template-ids, &c.
10971/// However, unlike when declaring a template specialization, it's
10972/// okay to refer to a template specialization without an empty
10973/// template parameter declaration, e.g.
10974/// friend class A<T>::B<unsigned>;
10975/// We permit this as a special case; if there are any template
10976/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010977/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010978Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010979 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010980 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010981
10982 assert(DS.isFriendSpecified());
10983 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10984
John McCalldd4a3b02009-09-16 22:47:08 +000010985 // Try to convert the decl specifier to a type. This works for
10986 // friend templates because ActOnTag never produces a ClassTemplateDecl
10987 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010988 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010989 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10990 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010991 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010992 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010993
Douglas Gregor6ccab972010-12-16 01:14:37 +000010994 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10995 return 0;
10996
John McCalldd4a3b02009-09-16 22:47:08 +000010997 // This is definitely an error in C++98. It's probably meant to
10998 // be forbidden in C++0x, too, but the specification is just
10999 // poorly written.
11000 //
11001 // The problem is with declarations like the following:
11002 // template <T> friend A<T>::foo;
11003 // where deciding whether a class C is a friend or not now hinges
11004 // on whether there exists an instantiation of A that causes
11005 // 'foo' to equal C. There are restrictions on class-heads
11006 // (which we declare (by fiat) elaborated friend declarations to
11007 // be) that makes this tractable.
11008 //
11009 // FIXME: handle "template <> friend class A<T>;", which
11010 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011011 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011012 Diag(Loc, diag::err_tagless_friend_type_template)
11013 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011014 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011015 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011016
John McCall02cace72009-08-28 07:59:38 +000011017 // C++98 [class.friend]p1: A friend of a class is a function
11018 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011019 // This is fixed in DR77, which just barely didn't make the C++03
11020 // deadline. It's also a very silly restriction that seriously
11021 // affects inner classes and which nobody else seems to implement;
11022 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011023 //
11024 // But note that we could warn about it: it's always useless to
11025 // friend one of your own members (it's not, however, worthless to
11026 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011027
John McCalldd4a3b02009-09-16 22:47:08 +000011028 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011029 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011030 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011031 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011032 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011033 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011034 DS.getFriendSpecLoc());
11035 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011036 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011037
11038 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011039 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011040
John McCalldd4a3b02009-09-16 22:47:08 +000011041 D->setAccess(AS_public);
11042 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011043
John McCalld226f652010-08-21 09:40:31 +000011044 return D;
John McCall02cace72009-08-28 07:59:38 +000011045}
11046
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011047NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11048 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011049 const DeclSpec &DS = D.getDeclSpec();
11050
11051 assert(DS.isFriendSpecified());
11052 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11053
11054 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011055 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011056
11057 // C++ [class.friend]p1
11058 // A friend of a class is a function or class....
11059 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011060 // It *doesn't* see through dependent types, which is correct
11061 // according to [temp.arg.type]p3:
11062 // If a declaration acquires a function type through a
11063 // type dependent on a template-parameter and this causes
11064 // a declaration that does not use the syntactic form of a
11065 // function declarator to have a function type, the program
11066 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011067 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011068 Diag(Loc, diag::err_unexpected_friend);
11069
11070 // It might be worthwhile to try to recover by creating an
11071 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011072 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011073 }
11074
11075 // C++ [namespace.memdef]p3
11076 // - If a friend declaration in a non-local class first declares a
11077 // class or function, the friend class or function is a member
11078 // of the innermost enclosing namespace.
11079 // - The name of the friend is not found by simple name lookup
11080 // until a matching declaration is provided in that namespace
11081 // scope (either before or after the class declaration granting
11082 // friendship).
11083 // - If a friend function is called, its name may be found by the
11084 // name lookup that considers functions from namespaces and
11085 // classes associated with the types of the function arguments.
11086 // - When looking for a prior declaration of a class or a function
11087 // declared as a friend, scopes outside the innermost enclosing
11088 // namespace scope are not considered.
11089
John McCall337ec3d2010-10-12 23:13:28 +000011090 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011091 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11092 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011093 assert(Name);
11094
Douglas Gregor6ccab972010-12-16 01:14:37 +000011095 // Check for unexpanded parameter packs.
11096 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11097 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11098 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11099 return 0;
11100
John McCall67d1a672009-08-06 02:15:43 +000011101 // The context we found the declaration in, or in which we should
11102 // create the declaration.
11103 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011104 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011105 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011106 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011107
John McCall337ec3d2010-10-12 23:13:28 +000011108 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000011109
John McCall337ec3d2010-10-12 23:13:28 +000011110 // There are four cases here.
11111 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000011112 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000011113 // there as appropriate.
11114 // Recover from invalid scope qualifiers as if they just weren't there.
11115 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000011116 // C++0x [namespace.memdef]p3:
11117 // If the name in a friend declaration is neither qualified nor
11118 // a template-id and the declaration is a function or an
11119 // elaborated-type-specifier, the lookup to determine whether
11120 // the entity has been previously declared shall not consider
11121 // any scopes outside the innermost enclosing namespace.
11122 // C++0x [class.friend]p11:
11123 // If a friend declaration appears in a local class and the name
11124 // specified is an unqualified name, a prior declaration is
11125 // looked up without considering scopes that are outside the
11126 // innermost enclosing non-class scope. For a friend function
11127 // declaration, if there is no prior declaration, the program is
11128 // ill-formed.
11129 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000011130 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011131
John McCall29ae6e52010-10-13 05:45:15 +000011132 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011133 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011134
Rafael Espindola11dc6342013-04-25 20:12:36 +000011135 // Skip class contexts. If someone can cite chapter and verse
11136 // for this behavior, that would be nice --- it's what GCC and
11137 // EDG do, and it seems like a reasonable intent, but the spec
11138 // really only says that checks for unqualified existing
11139 // declarations should stop at the nearest enclosing namespace,
11140 // not that they should only consider the nearest enclosing
11141 // namespace.
11142 while (DC->isRecord())
11143 DC = DC->getParent();
11144
11145 DeclContext *LookupDC = DC;
11146 while (LookupDC->isTransparentContext())
11147 LookupDC = LookupDC->getParent();
11148
11149 while (true) {
11150 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011151
11152 // TODO: decide what we think about using declarations.
Rafael Espindola11dc6342013-04-25 20:12:36 +000011153 if (isLocal)
John McCall67d1a672009-08-06 02:15:43 +000011154 break;
John McCall29ae6e52010-10-13 05:45:15 +000011155
Rafael Espindola11dc6342013-04-25 20:12:36 +000011156 if (!Previous.empty()) {
11157 DC = LookupDC;
11158 break;
John McCall8a407372010-10-14 22:22:28 +000011159 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011160
11161 if (isTemplateId) {
11162 if (isa<TranslationUnitDecl>(LookupDC)) break;
11163 } else {
11164 if (LookupDC->isFileContext()) break;
11165 }
11166 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011167 }
11168
John McCall380aaa42010-10-13 06:22:15 +000011169 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011170
Douglas Gregor883af832011-10-10 01:11:59 +000011171 // C++ [class.friend]p6:
11172 // A function can be defined in a friend declaration of a class if and
11173 // only if the class is a non-local class (9.8), the function name is
11174 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011175 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011176 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11177 }
11178
John McCall337ec3d2010-10-12 23:13:28 +000011179 // - There's a non-dependent scope specifier, in which case we
11180 // compute it and do a previous lookup there for a function
11181 // or function template.
11182 } else if (!SS.getScopeRep()->isDependent()) {
11183 DC = computeDeclContext(SS);
11184 if (!DC) return 0;
11185
11186 if (RequireCompleteDeclContext(SS, DC)) return 0;
11187
11188 LookupQualifiedName(Previous, DC);
11189
11190 // Ignore things found implicitly in the wrong scope.
11191 // TODO: better diagnostics for this case. Suggesting the right
11192 // qualified scope would be nice...
11193 LookupResult::Filter F = Previous.makeFilter();
11194 while (F.hasNext()) {
11195 NamedDecl *D = F.next();
11196 if (!DC->InEnclosingNamespaceSetOf(
11197 D->getDeclContext()->getRedeclContext()))
11198 F.erase();
11199 }
11200 F.done();
11201
11202 if (Previous.empty()) {
11203 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011204 Diag(Loc, diag::err_qualified_friend_not_found)
11205 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011206 return 0;
11207 }
11208
11209 // C++ [class.friend]p1: A friend of a class is a function or
11210 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011211 if (DC->Equals(CurContext))
11212 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011213 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011214 diag::warn_cxx98_compat_friend_is_member :
11215 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011216
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011217 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011218 // C++ [class.friend]p6:
11219 // A function can be defined in a friend declaration of a class if and
11220 // only if the class is a non-local class (9.8), the function name is
11221 // unqualified, and the function has namespace scope.
11222 SemaDiagnosticBuilder DB
11223 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11224
11225 DB << SS.getScopeRep();
11226 if (DC->isFileContext())
11227 DB << FixItHint::CreateRemoval(SS.getRange());
11228 SS.clear();
11229 }
John McCall337ec3d2010-10-12 23:13:28 +000011230
11231 // - There's a scope specifier that does not match any template
11232 // parameter lists, in which case we use some arbitrary context,
11233 // create a method or method template, and wait for instantiation.
11234 // - There's a scope specifier that does match some template
11235 // parameter lists, which we don't handle right now.
11236 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011237 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011238 // C++ [class.friend]p6:
11239 // A function can be defined in a friend declaration of a class if and
11240 // only if the class is a non-local class (9.8), the function name is
11241 // unqualified, and the function has namespace scope.
11242 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11243 << SS.getScopeRep();
11244 }
11245
John McCall337ec3d2010-10-12 23:13:28 +000011246 DC = CurContext;
11247 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011248 }
Douglas Gregor883af832011-10-10 01:11:59 +000011249
John McCall29ae6e52010-10-13 05:45:15 +000011250 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011251 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011252 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11253 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11254 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011255 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011256 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11257 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011258 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011259 }
John McCall67d1a672009-08-06 02:15:43 +000011260 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011261
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011262 // FIXME: This is an egregious hack to cope with cases where the scope stack
11263 // does not contain the declaration context, i.e., in an out-of-line
11264 // definition of a class.
11265 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11266 if (!DCScope) {
11267 FakeDCScope.setEntity(DC);
11268 DCScope = &FakeDCScope;
11269 }
11270
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011271 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011272 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011273 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011274 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011275
Douglas Gregor182ddf02009-09-28 00:08:27 +000011276 assert(ND->getDeclContext() == DC);
11277 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011278
John McCallab88d972009-08-31 22:39:49 +000011279 // Add the function declaration to the appropriate lookup tables,
11280 // adjusting the redeclarations list as necessary. We don't
11281 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011282 //
John McCallab88d972009-08-31 22:39:49 +000011283 // Also update the scope-based lookup if the target context's
11284 // lookup context is in lexical scope.
11285 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011286 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011287 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011288 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011289 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011290 }
John McCall02cace72009-08-28 07:59:38 +000011291
11292 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011293 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011294 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011295 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011296 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011297
John McCall1f2e1a92012-08-10 03:15:35 +000011298 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011299 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011300 } else {
11301 if (DC->isRecord()) CheckFriendAccess(ND);
11302
John McCall6102ca12010-10-16 06:59:13 +000011303 FunctionDecl *FD;
11304 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11305 FD = FTD->getTemplatedDecl();
11306 else
11307 FD = cast<FunctionDecl>(ND);
11308
11309 // Mark templated-scope function declarations as unsupported.
11310 if (FD->getNumTemplateParameterLists())
11311 FrD->setUnsupportedFriend(true);
11312 }
John McCall337ec3d2010-10-12 23:13:28 +000011313
John McCalld226f652010-08-21 09:40:31 +000011314 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011315}
11316
John McCalld226f652010-08-21 09:40:31 +000011317void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11318 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011319
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011320 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011321 if (!Fn) {
11322 Diag(DelLoc, diag::err_deleted_non_function);
11323 return;
11324 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011325
Douglas Gregoref96ee02012-01-14 16:38:05 +000011326 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011327 // Don't consider the implicit declaration we generate for explicit
11328 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011329 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11330 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011331 Diag(DelLoc, diag::err_deleted_decl_not_first);
11332 Diag(Prev->getLocation(), diag::note_previous_declaration);
11333 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011334 // If the declaration wasn't the first, we delete the function anyway for
11335 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011336 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011337 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011338
11339 if (Fn->isDeleted())
11340 return;
11341
11342 // See if we're deleting a function which is already known to override a
11343 // non-deleted virtual function.
11344 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11345 bool IssuedDiagnostic = false;
11346 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11347 E = MD->end_overridden_methods();
11348 I != E; ++I) {
11349 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11350 if (!IssuedDiagnostic) {
11351 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11352 IssuedDiagnostic = true;
11353 }
11354 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11355 }
11356 }
11357 }
11358
Sean Hunt10620eb2011-05-06 20:44:56 +000011359 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011360}
Sebastian Redl13e88542009-04-27 21:33:24 +000011361
Sean Hunte4246a62011-05-12 06:15:49 +000011362void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011363 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011364
11365 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011366 if (MD->getParent()->isDependentType()) {
11367 MD->setDefaulted();
11368 MD->setExplicitlyDefaulted();
11369 return;
11370 }
11371
Sean Hunte4246a62011-05-12 06:15:49 +000011372 CXXSpecialMember Member = getSpecialMember(MD);
11373 if (Member == CXXInvalid) {
11374 Diag(DefaultLoc, diag::err_default_special_members);
11375 return;
11376 }
11377
11378 MD->setDefaulted();
11379 MD->setExplicitlyDefaulted();
11380
Sean Huntcd10dec2011-05-23 23:14:04 +000011381 // If this definition appears within the record, do the checking when
11382 // the record is complete.
11383 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011384 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011385 // Find the uninstantiated declaration that actually had the '= default'
11386 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011387 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011388
Richard Smith12fef492013-03-27 00:22:47 +000011389 // If the method was defaulted on its first declaration, we will have
11390 // already performed the checking in CheckCompletedCXXClass. Such a
11391 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011392 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011393 return;
11394
Richard Smithb9d0b762012-07-27 04:22:15 +000011395 CheckExplicitlyDefaultedSpecialMember(MD);
11396
Richard Smith1d28caf2012-12-11 01:14:52 +000011397 // The exception specification is needed because we are defining the
11398 // function.
11399 ResolveExceptionSpec(DefaultLoc,
11400 MD->getType()->castAs<FunctionProtoType>());
11401
Sean Hunte4246a62011-05-12 06:15:49 +000011402 switch (Member) {
11403 case CXXDefaultConstructor: {
11404 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011405 if (!CD->isInvalidDecl())
11406 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11407 break;
11408 }
11409
11410 case CXXCopyConstructor: {
11411 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011412 if (!CD->isInvalidDecl())
11413 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011414 break;
11415 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011416
Sean Hunt2b188082011-05-14 05:23:28 +000011417 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011418 if (!MD->isInvalidDecl())
11419 DefineImplicitCopyAssignment(DefaultLoc, MD);
11420 break;
11421 }
11422
Sean Huntcb45a0f2011-05-12 22:46:25 +000011423 case CXXDestructor: {
11424 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011425 if (!DD->isInvalidDecl())
11426 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011427 break;
11428 }
11429
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011430 case CXXMoveConstructor: {
11431 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011432 if (!CD->isInvalidDecl())
11433 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011434 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011435 }
Sean Hunt82713172011-05-25 23:16:36 +000011436
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011437 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011438 if (!MD->isInvalidDecl())
11439 DefineImplicitMoveAssignment(DefaultLoc, MD);
11440 break;
11441 }
11442
11443 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011444 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011445 }
11446 } else {
11447 Diag(DefaultLoc, diag::err_default_special_members);
11448 }
11449}
11450
Sebastian Redl13e88542009-04-27 21:33:24 +000011451static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011452 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011453 Stmt *SubStmt = *CI;
11454 if (!SubStmt)
11455 continue;
11456 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011457 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011458 diag::err_return_in_constructor_handler);
11459 if (!isa<Expr>(SubStmt))
11460 SearchForReturnInStmt(Self, SubStmt);
11461 }
11462}
11463
11464void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11465 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11466 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11467 SearchForReturnInStmt(*this, Handler);
11468 }
11469}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011470
David Blaikie299adab2013-01-18 23:03:15 +000011471bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011472 const CXXMethodDecl *Old) {
11473 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11474 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11475
11476 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11477
11478 // If the calling conventions match, everything is fine
11479 if (NewCC == OldCC)
11480 return false;
11481
11482 // If either of the calling conventions are set to "default", we need to pick
11483 // something more sensible based on the target. This supports code where the
11484 // one method explicitly sets thiscall, and another has no explicit calling
11485 // convention.
11486 CallingConv Default =
11487 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11488 if (NewCC == CC_Default)
11489 NewCC = Default;
11490 if (OldCC == CC_Default)
11491 OldCC = Default;
11492
11493 // If the calling conventions still don't match, then report the error
11494 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011495 Diag(New->getLocation(),
11496 diag::err_conflicting_overriding_cc_attributes)
11497 << New->getDeclName() << New->getType() << Old->getType();
11498 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11499 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011500 }
11501
11502 return false;
11503}
11504
Mike Stump1eb44332009-09-09 15:08:12 +000011505bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011506 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011507 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11508 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011509
Chandler Carruth73857792010-02-15 11:53:20 +000011510 if (Context.hasSameType(NewTy, OldTy) ||
11511 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011512 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011513
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011514 // Check if the return types are covariant
11515 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011516
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011517 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011518 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11519 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011520 NewClassTy = NewPT->getPointeeType();
11521 OldClassTy = OldPT->getPointeeType();
11522 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011523 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11524 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11525 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11526 NewClassTy = NewRT->getPointeeType();
11527 OldClassTy = OldRT->getPointeeType();
11528 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011529 }
11530 }
Mike Stump1eb44332009-09-09 15:08:12 +000011531
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011532 // The return types aren't either both pointers or references to a class type.
11533 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011534 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011535 diag::err_different_return_type_for_overriding_virtual_function)
11536 << New->getDeclName() << NewTy << OldTy;
11537 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011538
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011539 return true;
11540 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011541
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011542 // C++ [class.virtual]p6:
11543 // If the return type of D::f differs from the return type of B::f, the
11544 // class type in the return type of D::f shall be complete at the point of
11545 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011546 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11547 if (!RT->isBeingDefined() &&
11548 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011549 diag::err_covariant_return_incomplete,
11550 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011551 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011552 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011553
Douglas Gregora4923eb2009-11-16 21:35:15 +000011554 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011555 // Check if the new class derives from the old class.
11556 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11557 Diag(New->getLocation(),
11558 diag::err_covariant_return_not_derived)
11559 << New->getDeclName() << NewTy << OldTy;
11560 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11561 return true;
11562 }
Mike Stump1eb44332009-09-09 15:08:12 +000011563
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011564 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011565 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011566 diag::err_covariant_return_inaccessible_base,
11567 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11568 // FIXME: Should this point to the return type?
11569 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011570 // FIXME: this note won't trigger for delayed access control
11571 // diagnostics, and it's impossible to get an undelayed error
11572 // here from access control during the original parse because
11573 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011574 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11575 return true;
11576 }
11577 }
Mike Stump1eb44332009-09-09 15:08:12 +000011578
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011579 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011580 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011581 Diag(New->getLocation(),
11582 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011583 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011584 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11585 return true;
11586 };
Mike Stump1eb44332009-09-09 15:08:12 +000011587
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011588
11589 // The new class type must have the same or less qualifiers as the old type.
11590 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11591 Diag(New->getLocation(),
11592 diag::err_covariant_return_type_class_type_more_qualified)
11593 << New->getDeclName() << NewTy << OldTy;
11594 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11595 return true;
11596 };
Mike Stump1eb44332009-09-09 15:08:12 +000011597
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011598 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011599}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011600
Douglas Gregor4ba31362009-12-01 17:24:26 +000011601/// \brief Mark the given method pure.
11602///
11603/// \param Method the method to be marked pure.
11604///
11605/// \param InitRange the source range that covers the "0" initializer.
11606bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011607 SourceLocation EndLoc = InitRange.getEnd();
11608 if (EndLoc.isValid())
11609 Method->setRangeEnd(EndLoc);
11610
Douglas Gregor4ba31362009-12-01 17:24:26 +000011611 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11612 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011613 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011614 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011615
11616 if (!Method->isInvalidDecl())
11617 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11618 << Method->getDeclName() << InitRange;
11619 return true;
11620}
11621
Douglas Gregor552e2992012-02-21 02:22:07 +000011622/// \brief Determine whether the given declaration is a static data member.
11623static bool isStaticDataMember(Decl *D) {
11624 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11625 if (!Var)
11626 return false;
11627
11628 return Var->isStaticDataMember();
11629}
John McCall731ad842009-12-19 09:28:58 +000011630/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11631/// an initializer for the out-of-line declaration 'Dcl'. The scope
11632/// is a fresh scope pushed for just this purpose.
11633///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011634/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11635/// static data member of class X, names should be looked up in the scope of
11636/// class X.
John McCalld226f652010-08-21 09:40:31 +000011637void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011638 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011639 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011640
John McCall731ad842009-12-19 09:28:58 +000011641 // We should only get called for declarations with scope specifiers, like:
11642 // int foo::bar;
11643 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011644 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011645
11646 // If we are parsing the initializer for a static data member, push a
11647 // new expression evaluation context that is associated with this static
11648 // data member.
11649 if (isStaticDataMember(D))
11650 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011651}
11652
11653/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011654/// initializer for the out-of-line declaration 'D'.
11655void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011656 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011657 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011658
Douglas Gregor552e2992012-02-21 02:22:07 +000011659 if (isStaticDataMember(D))
11660 PopExpressionEvaluationContext();
11661
John McCall731ad842009-12-19 09:28:58 +000011662 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011663 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011664}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011665
11666/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11667/// C++ if/switch/while/for statement.
11668/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011669DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011670 // C++ 6.4p2:
11671 // The declarator shall not specify a function or an array.
11672 // The type-specifier-seq shall not contain typedef and shall not declare a
11673 // new class or enumeration.
11674 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11675 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011676
11677 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011678 if (!Dcl)
11679 return true;
11680
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011681 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11682 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011683 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011684 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011685 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011686
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011687 return Dcl;
11688}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011689
Douglas Gregordfe65432011-07-28 19:11:31 +000011690void Sema::LoadExternalVTableUses() {
11691 if (!ExternalSource)
11692 return;
11693
11694 SmallVector<ExternalVTableUse, 4> VTables;
11695 ExternalSource->ReadUsedVTables(VTables);
11696 SmallVector<VTableUse, 4> NewUses;
11697 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11698 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11699 = VTablesUsed.find(VTables[I].Record);
11700 // Even if a definition wasn't required before, it may be required now.
11701 if (Pos != VTablesUsed.end()) {
11702 if (!Pos->second && VTables[I].DefinitionRequired)
11703 Pos->second = true;
11704 continue;
11705 }
11706
11707 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11708 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11709 }
11710
11711 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11712}
11713
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011714void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11715 bool DefinitionRequired) {
11716 // Ignore any vtable uses in unevaluated operands or for classes that do
11717 // not have a vtable.
11718 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011719 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011720 return;
11721
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011722 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011723 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011724 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11725 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11726 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11727 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011728 // If we already had an entry, check to see if we are promoting this vtable
11729 // to required a definition. If so, we need to reappend to the VTableUses
11730 // list, since we may have already processed the first entry.
11731 if (DefinitionRequired && !Pos.first->second) {
11732 Pos.first->second = true;
11733 } else {
11734 // Otherwise, we can early exit.
11735 return;
11736 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011737 }
11738
11739 // Local classes need to have their virtual members marked
11740 // immediately. For all other classes, we mark their virtual members
11741 // at the end of the translation unit.
11742 if (Class->isLocalClass())
11743 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011744 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011745 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011746}
11747
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011748bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011749 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011750 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011751 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011752
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011753 // Note: The VTableUses vector could grow as a result of marking
11754 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011755 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011756 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011757 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011758 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011759 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011760 if (!Class)
11761 continue;
11762
11763 SourceLocation Loc = VTableUses[I].second;
11764
Richard Smithb9d0b762012-07-27 04:22:15 +000011765 bool DefineVTable = true;
11766
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011767 // If this class has a key function, but that key function is
11768 // defined in another translation unit, we don't need to emit the
11769 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011770 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011771 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011772 switch (KeyFunction->getTemplateSpecializationKind()) {
11773 case TSK_Undeclared:
11774 case TSK_ExplicitSpecialization:
11775 case TSK_ExplicitInstantiationDeclaration:
11776 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011777 DefineVTable = false;
11778 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011779
11780 case TSK_ExplicitInstantiationDefinition:
11781 case TSK_ImplicitInstantiation:
11782 // We will be instantiating the key function.
11783 break;
11784 }
11785 } else if (!KeyFunction) {
11786 // If we have a class with no key function that is the subject
11787 // of an explicit instantiation declaration, suppress the
11788 // vtable; it will live with the explicit instantiation
11789 // definition.
11790 bool IsExplicitInstantiationDeclaration
11791 = Class->getTemplateSpecializationKind()
11792 == TSK_ExplicitInstantiationDeclaration;
11793 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11794 REnd = Class->redecls_end();
11795 R != REnd; ++R) {
11796 TemplateSpecializationKind TSK
11797 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11798 if (TSK == TSK_ExplicitInstantiationDeclaration)
11799 IsExplicitInstantiationDeclaration = true;
11800 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11801 IsExplicitInstantiationDeclaration = false;
11802 break;
11803 }
11804 }
11805
11806 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011807 DefineVTable = false;
11808 }
11809
11810 // The exception specifications for all virtual members may be needed even
11811 // if we are not providing an authoritative form of the vtable in this TU.
11812 // We may choose to emit it available_externally anyway.
11813 if (!DefineVTable) {
11814 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11815 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011816 }
11817
11818 // Mark all of the virtual members of this class as referenced, so
11819 // that we can build a vtable. Then, tell the AST consumer that a
11820 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011821 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011822 MarkVirtualMembersReferenced(Loc, Class);
11823 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11824 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11825
11826 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000011827 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011828 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011829 const FunctionDecl *KeyFunctionDef = 0;
11830 if (!KeyFunction ||
11831 (KeyFunction->hasBody(KeyFunctionDef) &&
11832 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011833 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11834 TSK_ExplicitInstantiationDefinition
11835 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11836 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011837 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011838 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011839 VTableUses.clear();
11840
Douglas Gregor78844032011-04-22 22:25:37 +000011841 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011842}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011843
Richard Smithb9d0b762012-07-27 04:22:15 +000011844void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11845 const CXXRecordDecl *RD) {
11846 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11847 E = RD->method_end(); I != E; ++I)
11848 if ((*I)->isVirtual() && !(*I)->isPure())
11849 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11850}
11851
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011852void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11853 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011854 // Mark all functions which will appear in RD's vtable as used.
11855 CXXFinalOverriderMap FinalOverriders;
11856 RD->getFinalOverriders(FinalOverriders);
11857 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11858 E = FinalOverriders.end();
11859 I != E; ++I) {
11860 for (OverridingMethods::const_iterator OI = I->second.begin(),
11861 OE = I->second.end();
11862 OI != OE; ++OI) {
11863 assert(OI->second.size() > 0 && "no final overrider");
11864 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011865
Richard Smithff817f72012-07-07 06:59:51 +000011866 // C++ [basic.def.odr]p2:
11867 // [...] A virtual member function is used if it is not pure. [...]
11868 if (!Overrider->isPure())
11869 MarkFunctionReferenced(Loc, Overrider);
11870 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011871 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011872
11873 // Only classes that have virtual bases need a VTT.
11874 if (RD->getNumVBases() == 0)
11875 return;
11876
11877 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11878 e = RD->bases_end(); i != e; ++i) {
11879 const CXXRecordDecl *Base =
11880 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011881 if (Base->getNumVBases() == 0)
11882 continue;
11883 MarkVirtualMembersReferenced(Loc, Base);
11884 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011885}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011886
11887/// SetIvarInitializers - This routine builds initialization ASTs for the
11888/// Objective-C implementation whose ivars need be initialized.
11889void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011890 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011891 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011892 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011893 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011894 CollectIvarsToConstructOrDestruct(OID, ivars);
11895 if (ivars.empty())
11896 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011897 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011898 for (unsigned i = 0; i < ivars.size(); i++) {
11899 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011900 if (Field->isInvalidDecl())
11901 continue;
11902
Sean Huntcbb67482011-01-08 20:30:50 +000011903 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011904 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11905 InitializationKind InitKind =
11906 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011907
11908 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
11909 ExprResult MemberInit =
11910 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000011911 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011912 // Note, MemberInit could actually come back empty if no initialization
11913 // is required (e.g., because it would call a trivial default constructor)
11914 if (!MemberInit.get() || MemberInit.isInvalid())
11915 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011916
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011917 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011918 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11919 SourceLocation(),
11920 MemberInit.takeAs<Expr>(),
11921 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011922 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011923
11924 // Be sure that the destructor is accessible and is marked as referenced.
11925 if (const RecordType *RecordTy
11926 = Context.getBaseElementType(Field->getType())
11927 ->getAs<RecordType>()) {
11928 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011929 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011930 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011931 CheckDestructorAccess(Field->getLocation(), Destructor,
11932 PDiag(diag::err_access_dtor_ivar)
11933 << Context.getBaseElementType(Field->getType()));
11934 }
11935 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011936 }
11937 ObjCImplementation->setIvarInitializers(Context,
11938 AllToInit.data(), AllToInit.size());
11939 }
11940}
Sean Huntfe57eef2011-05-04 05:57:24 +000011941
Sean Huntebcbe1d2011-05-04 23:29:54 +000011942static
11943void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11944 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11945 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11946 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11947 Sema &S) {
11948 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11949 CE = Current.end();
11950 if (Ctor->isInvalidDecl())
11951 return;
11952
Richard Smitha8eaf002012-08-23 06:16:52 +000011953 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11954
11955 // Target may not be determinable yet, for instance if this is a dependent
11956 // call in an uninstantiated template.
11957 if (Target) {
11958 const FunctionDecl *FNTarget = 0;
11959 (void)Target->hasBody(FNTarget);
11960 Target = const_cast<CXXConstructorDecl*>(
11961 cast_or_null<CXXConstructorDecl>(FNTarget));
11962 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011963
11964 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11965 // Avoid dereferencing a null pointer here.
11966 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11967
11968 if (!Current.insert(Canonical))
11969 return;
11970
11971 // We know that beyond here, we aren't chaining into a cycle.
11972 if (!Target || !Target->isDelegatingConstructor() ||
11973 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11974 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11975 Valid.insert(*CI);
11976 Current.clear();
11977 // We've hit a cycle.
11978 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11979 Current.count(TCanonical)) {
11980 // If we haven't diagnosed this cycle yet, do so now.
11981 if (!Invalid.count(TCanonical)) {
11982 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011983 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011984 << Ctor;
11985
Richard Smitha8eaf002012-08-23 06:16:52 +000011986 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011987 if (TCanonical != Canonical)
11988 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11989
11990 CXXConstructorDecl *C = Target;
11991 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011992 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011993 (void)C->getTargetConstructor()->hasBody(FNTarget);
11994 assert(FNTarget && "Ctor cycle through bodiless function");
11995
Richard Smitha8eaf002012-08-23 06:16:52 +000011996 C = const_cast<CXXConstructorDecl*>(
11997 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011998 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11999 }
12000 }
12001
12002 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12003 Invalid.insert(*CI);
12004 Current.clear();
12005 } else {
12006 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12007 }
12008}
12009
12010
Sean Huntfe57eef2011-05-04 05:57:24 +000012011void Sema::CheckDelegatingCtorCycles() {
12012 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12013
Sean Huntebcbe1d2011-05-04 23:29:54 +000012014 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12015 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000012016
Douglas Gregor0129b562011-07-27 21:57:17 +000012017 for (DelegatingCtorDeclsType::iterator
12018 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012019 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012020 I != E; ++I)
12021 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012022
12023 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12024 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012025}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012026
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012027namespace {
12028 /// \brief AST visitor that finds references to the 'this' expression.
12029 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12030 Sema &S;
12031
12032 public:
12033 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12034
12035 bool VisitCXXThisExpr(CXXThisExpr *E) {
12036 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12037 << E->isImplicit();
12038 return false;
12039 }
12040 };
12041}
12042
12043bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12044 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12045 if (!TSInfo)
12046 return false;
12047
12048 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012049 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012050 if (!ProtoTL)
12051 return false;
12052
12053 // C++11 [expr.prim.general]p3:
12054 // [The expression this] shall not appear before the optional
12055 // cv-qualifier-seq and it shall not appear within the declaration of a
12056 // static member function (although its type and value category are defined
12057 // within a static member function as they are within a non-static member
12058 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012059 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012060 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012061 FindCXXThisExpr Finder(*this);
12062
12063 // If the return type came after the cv-qualifier-seq, check it now.
12064 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012065 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012066 return true;
12067
12068 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012069 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12070 return true;
12071
12072 return checkThisInStaticMemberFunctionAttributes(Method);
12073}
12074
12075bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12076 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12077 if (!TSInfo)
12078 return false;
12079
12080 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012081 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012082 if (!ProtoTL)
12083 return false;
12084
David Blaikie39e6ab42013-02-18 22:06:02 +000012085 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012086 FindCXXThisExpr Finder(*this);
12087
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012088 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012089 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012090 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012091 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012092 case EST_DynamicNone:
12093 case EST_MSAny:
12094 case EST_None:
12095 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012096
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012097 case EST_ComputedNoexcept:
12098 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12099 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012100
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012101 case EST_Dynamic:
12102 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012103 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012104 E != EEnd; ++E) {
12105 if (!Finder.TraverseType(*E))
12106 return true;
12107 }
12108 break;
12109 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012110
12111 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012112}
12113
12114bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12115 FindCXXThisExpr Finder(*this);
12116
12117 // Check attributes.
12118 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12119 A != AEnd; ++A) {
12120 // FIXME: This should be emitted by tblgen.
12121 Expr *Arg = 0;
12122 ArrayRef<Expr *> Args;
12123 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12124 Arg = G->getArg();
12125 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12126 Arg = G->getArg();
12127 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12128 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12129 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12130 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12131 else if (ExclusiveLockFunctionAttr *ELF
12132 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12133 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12134 else if (SharedLockFunctionAttr *SLF
12135 = dyn_cast<SharedLockFunctionAttr>(*A))
12136 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12137 else if (ExclusiveTrylockFunctionAttr *ETLF
12138 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12139 Arg = ETLF->getSuccessValue();
12140 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12141 } else if (SharedTrylockFunctionAttr *STLF
12142 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12143 Arg = STLF->getSuccessValue();
12144 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12145 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12146 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12147 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12148 Arg = LR->getArg();
12149 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12150 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12151 else if (ExclusiveLocksRequiredAttr *ELR
12152 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12153 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12154 else if (SharedLocksRequiredAttr *SLR
12155 = dyn_cast<SharedLocksRequiredAttr>(*A))
12156 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12157
12158 if (Arg && !Finder.TraverseStmt(Arg))
12159 return true;
12160
12161 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12162 if (!Finder.TraverseStmt(Args[I]))
12163 return true;
12164 }
12165 }
12166
12167 return false;
12168}
12169
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012170void
12171Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12172 ArrayRef<ParsedType> DynamicExceptions,
12173 ArrayRef<SourceRange> DynamicExceptionRanges,
12174 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012175 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012176 FunctionProtoType::ExtProtoInfo &EPI) {
12177 Exceptions.clear();
12178 EPI.ExceptionSpecType = EST;
12179 if (EST == EST_Dynamic) {
12180 Exceptions.reserve(DynamicExceptions.size());
12181 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12182 // FIXME: Preserve type source info.
12183 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12184
12185 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12186 collectUnexpandedParameterPacks(ET, Unexpanded);
12187 if (!Unexpanded.empty()) {
12188 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12189 UPPC_ExceptionType,
12190 Unexpanded);
12191 continue;
12192 }
12193
12194 // Check that the type is valid for an exception spec, and
12195 // drop it if not.
12196 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12197 Exceptions.push_back(ET);
12198 }
12199 EPI.NumExceptions = Exceptions.size();
12200 EPI.Exceptions = Exceptions.data();
12201 return;
12202 }
12203
12204 if (EST == EST_ComputedNoexcept) {
12205 // If an error occurred, there's no expression here.
12206 if (NoexceptExpr) {
12207 assert((NoexceptExpr->isTypeDependent() ||
12208 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12209 Context.BoolTy) &&
12210 "Parser should have made sure that the expression is boolean");
12211 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12212 EPI.ExceptionSpecType = EST_BasicNoexcept;
12213 return;
12214 }
12215
12216 if (!NoexceptExpr->isValueDependent())
12217 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012218 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012219 /*AllowFold*/ false).take();
12220 EPI.NoexceptExpr = NoexceptExpr;
12221 }
12222 return;
12223 }
12224}
12225
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012226/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12227Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12228 // Implicitly declared functions (e.g. copy constructors) are
12229 // __host__ __device__
12230 if (D->isImplicit())
12231 return CFT_HostDevice;
12232
12233 if (D->hasAttr<CUDAGlobalAttr>())
12234 return CFT_Global;
12235
12236 if (D->hasAttr<CUDADeviceAttr>()) {
12237 if (D->hasAttr<CUDAHostAttr>())
12238 return CFT_HostDevice;
12239 else
12240 return CFT_Device;
12241 }
12242
12243 return CFT_Host;
12244}
12245
12246bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12247 CUDAFunctionTarget CalleeTarget) {
12248 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12249 // Callable from the device only."
12250 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12251 return true;
12252
12253 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12254 // Callable from the host only."
12255 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12256 // Callable from the host only."
12257 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12258 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12259 return true;
12260
12261 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12262 return true;
12263
12264 return false;
12265}
John McCall76da55d2013-04-16 07:28:30 +000012266
12267/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12268///
12269MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12270 SourceLocation DeclStart,
12271 Declarator &D, Expr *BitWidth,
12272 InClassInitStyle InitStyle,
12273 AccessSpecifier AS,
12274 AttributeList *MSPropertyAttr) {
12275 IdentifierInfo *II = D.getIdentifier();
12276 if (!II) {
12277 Diag(DeclStart, diag::err_anonymous_property);
12278 return NULL;
12279 }
12280 SourceLocation Loc = D.getIdentifierLoc();
12281
12282 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12283 QualType T = TInfo->getType();
12284 if (getLangOpts().CPlusPlus) {
12285 CheckExtraCXXDefaultArguments(D);
12286
12287 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12288 UPPC_DataMemberType)) {
12289 D.setInvalidType();
12290 T = Context.IntTy;
12291 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12292 }
12293 }
12294
12295 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12296
12297 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12298 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12299 diag::err_invalid_thread)
12300 << DeclSpec::getSpecifierName(TSCS);
12301
12302 // Check to see if this name was declared as a member previously
12303 NamedDecl *PrevDecl = 0;
12304 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12305 LookupName(Previous, S);
12306 switch (Previous.getResultKind()) {
12307 case LookupResult::Found:
12308 case LookupResult::FoundUnresolvedValue:
12309 PrevDecl = Previous.getAsSingle<NamedDecl>();
12310 break;
12311
12312 case LookupResult::FoundOverloaded:
12313 PrevDecl = Previous.getRepresentativeDecl();
12314 break;
12315
12316 case LookupResult::NotFound:
12317 case LookupResult::NotFoundInCurrentInstantiation:
12318 case LookupResult::Ambiguous:
12319 break;
12320 }
12321
12322 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12323 // Maybe we will complain about the shadowed template parameter.
12324 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12325 // Just pretend that we didn't see the previous declaration.
12326 PrevDecl = 0;
12327 }
12328
12329 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12330 PrevDecl = 0;
12331
12332 SourceLocation TSSL = D.getLocStart();
12333 MSPropertyDecl *NewPD;
12334 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12335 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12336 II, T, TInfo, TSSL,
12337 Data.GetterId, Data.SetterId);
12338 ProcessDeclAttributes(TUScope, NewPD, D);
12339 NewPD->setAccess(AS);
12340
12341 if (NewPD->isInvalidDecl())
12342 Record->setInvalidDecl();
12343
12344 if (D.getDeclSpec().isModulePrivateSpecified())
12345 NewPD->setModulePrivate();
12346
12347 if (NewPD->isInvalidDecl() && PrevDecl) {
12348 // Don't introduce NewFD into scope; there's already something
12349 // with the same name in the same scope.
12350 } else if (II) {
12351 PushOnScopeChains(NewPD, S);
12352 } else
12353 Record->addDecl(NewPD);
12354
12355 return NewPD;
12356}