blob: 008bb73dc804109103367b22d2e0abb20aecf2ce [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000040#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000041#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner8123a952008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattner9e979552008-04-12 23:52:44 +000049namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 public:
Mike Stump1eb44332009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000068 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000069 };
Chris Lattner8123a952008-04-10 02:22:51 +000070
Chris Lattner9e979552008-04-12 23:52:44 +000071 /// VisitExpr - Visit all of the children of this expression.
72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000074 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000075 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000076 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000077 }
78
Chris Lattner9e979552008-04-12 23:52:44 +000079 /// VisitDeclRefExpr - Visit a reference to a declaration, to
80 /// determine whether this declaration can be used in the default
81 /// argument expression.
82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000083 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000084 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85 // C++ [dcl.fct.default]p9
86 // Default arguments are evaluated each time the function is
87 // called. The order of evaluation of function arguments is
88 // unspecified. Consequently, parameters of a function shall not
89 // be used in default argument expressions, even if they are not
90 // evaluated. Parameters of a function declared before a default
91 // argument expression are in scope and can hide namespace and
92 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000093 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000095 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000096 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000097 // C++ [dcl.fct.default]p7
98 // Local variables shall not be used in default argument
99 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000100 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000101 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000103 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000104 }
Chris Lattner8123a952008-04-10 02:22:51 +0000105
Douglas Gregor3996f232008-11-04 13:41:56 +0000106 return false;
107 }
Chris Lattner9e979552008-04-12 23:52:44 +0000108
Douglas Gregor796da182008-11-04 14:32:21 +0000109 /// VisitCXXThisExpr - Visit a C++ "this" expression.
110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111 // C++ [dcl.fct.default]p8:
112 // The keyword this shall not be used in a default argument of a
113 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000114 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000115 diag::err_param_default_argument_references_this)
116 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000117 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000118
John McCall045d2522013-04-09 01:56:28 +0000119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120 bool Invalid = false;
121 for (PseudoObjectExpr::semantics_iterator
122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123 Expr *E = *i;
124
125 // Look through bindings.
126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127 E = OVE->getSourceExpr();
128 assert(E && "pseudo-object binding without source expression?");
129 }
130
131 Invalid |= Visit(E);
132 }
133 return Invalid;
134 }
135
Douglas Gregorf0459f82012-02-10 23:30:22 +0000136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137 // C++11 [expr.lambda.prim]p13:
138 // A lambda-expression appearing in a default argument shall not
139 // implicitly or explicitly capture any entity.
140 if (Lambda->capture_begin() == Lambda->capture_end())
141 return false;
142
143 return S->Diag(Lambda->getLocStart(),
144 diag::err_lambda_capture_default_arg);
145 }
Chris Lattner8123a952008-04-10 02:22:51 +0000146}
147
Richard Smith0b0ca472013-04-10 06:11:48 +0000148void
149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000151 // If we have an MSAny spec already, don't bother.
152 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000153 return;
154
155 const FunctionProtoType *Proto
156 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158 if (!Proto)
159 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000160
161 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162
163 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000164 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000165 ClearExceptions();
166 ComputedEST = EST;
167 return;
168 }
169
Richard Smith7a614d82011-06-11 17:19:42 +0000170 // FIXME: If the call to this decl is using any of its default arguments, we
171 // need to search them for potentially-throwing calls.
172
Sean Hunt001cad92011-05-10 00:49:42 +0000173 // If this function has a basic noexcept, it doesn't affect the outcome.
174 if (EST == EST_BasicNoexcept)
175 return;
176
177 // If we have a throw-all spec at this point, ignore the function.
178 if (ComputedEST == EST_None)
179 return;
180
181 // If we're still at noexcept(true) and there's a nothrow() callee,
182 // change to that specification.
183 if (EST == EST_DynamicNone) {
184 if (ComputedEST == EST_BasicNoexcept)
185 ComputedEST = EST_DynamicNone;
186 return;
187 }
188
189 // Check out noexcept specs.
190 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
198
199 // noexcept(false) -> no spec on the new function
200 if (NR == FunctionProtoType::NR_Throw) {
201 ClearExceptions();
202 ComputedEST = EST_None;
203 }
204 // noexcept(true) won't change anything either.
205 return;
206 }
207
208 assert(EST == EST_Dynamic && "EST case not considered earlier.");
209 assert(ComputedEST != EST_None &&
210 "Shouldn't collect exceptions when throw-all is guaranteed.");
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214 EEnd = Proto->exception_end();
215 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000217 Exceptions.push_back(*E);
218}
219
Richard Smith7a614d82011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithe6975e92012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssoned961f92009-08-25 02:29:20 +0000249bool
John McCall9ae2f072010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param)
343 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Anders Carlsson5e300d12009-06-12 16:51:40 +0000358 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000359}
360
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367 // C++ [dcl.fct.default]p3
368 // A default argument expression shall be specified only in the
369 // parameter-declaration-clause of a function declaration or in a
370 // template-parameter (14.1). It shall not be specified for a
371 // parameter pack. If it is specified in a
372 // parameter-declaration-clause, it shall not occur within a
373 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000378 if (MightBeFunction) {
379 // This is a function declaration. It can have default arguments, but
380 // keep looking in case its return type is a function type with default
381 // arguments.
382 MightBeFunction = false;
383 continue;
384 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000393 delete Toks;
394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000395 } else if (Param->getDefaultArg()) {
396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397 << Param->getDefaultArg()->getSourceRange();
398 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000399 }
400 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000403 }
404 }
405}
406
Craig Topper1a6eac82012-09-21 04:33:26 +0000407/// MergeCXXFunctionDecl - Merge two declarations of the same C++
408/// function, once we already know that they have the same
409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
410/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
412 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000413 bool Invalid = false;
414
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000416 // For non-template functions, default arguments can be added in
417 // later declarations of a function in the same
418 // scope. Declarations in different scopes have completely
419 // distinct sets of default arguments. That is, declarations in
420 // inner scopes do not acquire default arguments from
421 // declarations in outer scopes, and vice versa. In a given
422 // function declaration, all parameters subsequent to a
423 // parameter with a default argument shall have default
424 // arguments supplied in this or previous declarations. A
425 // default argument shall not be redefined by a later
426 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000427 //
428 // C++ [dcl.fct.default]p6:
429 // Except for member functions of class templates, the default arguments
430 // in a member function definition that appears outside of the class
431 // definition are added to the set of default arguments provided by the
432 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000433 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
434 ParmVarDecl *OldParam = Old->getParamDecl(p);
435 ParmVarDecl *NewParam = New->getParamDecl(p);
436
James Molloy9cda03f2012-03-13 08:55:35 +0000437 bool OldParamHasDfl = OldParam->hasDefaultArg();
438 bool NewParamHasDfl = NewParam->hasDefaultArg();
439
440 NamedDecl *ND = Old;
441 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
442 // Ignore default parameters of old decl if they are not in
443 // the same scope.
444 OldParamHasDfl = false;
445
446 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000447
Francois Pichet8d051e02011-04-10 03:03:52 +0000448 unsigned DiagDefaultParamID =
449 diag::err_param_default_argument_redefinition;
450
451 // MSVC accepts that default parameters be redefined for member functions
452 // of template class. The new default parameter's value is ignored.
453 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000454 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000455 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
456 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000457 // Merge the old default argument into the new parameter.
458 NewParam->setHasInheritedDefaultArg();
459 if (OldParam->hasUninstantiatedDefaultArg())
460 NewParam->setUninstantiatedDefaultArg(
461 OldParam->getUninstantiatedDefaultArg());
462 else
463 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000464 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000465 Invalid = false;
466 }
467 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000468
Francois Pichet8cf90492011-04-10 04:58:30 +0000469 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
470 // hint here. Alternatively, we could walk the type-source information
471 // for NewParam to find the last source location in the type... but it
472 // isn't worth the effort right now. This is the kind of test case that
473 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000474 // int f(int);
475 // void g(int (*fp)(int) = f);
476 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000477 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000478 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000479
480 // Look for the function declaration where the default argument was
481 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000482 for (FunctionDecl *Older = Old->getPreviousDecl();
483 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000484 if (!Older->getParamDecl(p)->hasDefaultArg())
485 break;
486
487 OldParam = Older->getParamDecl(p);
488 }
489
490 Diag(OldParam->getLocation(), diag::note_previous_definition)
491 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000492 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000493 // Merge the old default argument into the new parameter.
494 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000495 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000496 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000497 if (OldParam->hasUninstantiatedDefaultArg())
498 NewParam->setUninstantiatedDefaultArg(
499 OldParam->getUninstantiatedDefaultArg());
500 else
John McCall3d6c1782010-05-04 01:53:42 +0000501 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000502 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000503 if (New->getDescribedFunctionTemplate()) {
504 // Paragraph 4, quoted above, only applies to non-template functions.
505 Diag(NewParam->getLocation(),
506 diag::err_param_default_argument_template_redecl)
507 << NewParam->getDefaultArgRange();
508 Diag(Old->getLocation(), diag::note_template_prev_declaration)
509 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000510 } else if (New->getTemplateSpecializationKind()
511 != TSK_ImplicitInstantiation &&
512 New->getTemplateSpecializationKind() != TSK_Undeclared) {
513 // C++ [temp.expr.spec]p21:
514 // Default function arguments shall not be specified in a declaration
515 // or a definition for one of the following explicit specializations:
516 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000517 // - the explicit specialization of a member function template;
518 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000519 // template where the class template specialization to which the
520 // member function specialization belongs is implicitly
521 // instantiated.
522 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
523 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
524 << New->getDeclName()
525 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000526 } else if (New->getDeclContext()->isDependentContext()) {
527 // C++ [dcl.fct.default]p6 (DR217):
528 // Default arguments for a member function of a class template shall
529 // be specified on the initial declaration of the member function
530 // within the class template.
531 //
532 // Reading the tea leaves a bit in DR217 and its reference to DR205
533 // leads me to the conclusion that one cannot add default function
534 // arguments for an out-of-line definition of a member function of a
535 // dependent type.
536 int WhichKind = 2;
537 if (CXXRecordDecl *Record
538 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
539 if (Record->getDescribedClassTemplate())
540 WhichKind = 0;
541 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
542 WhichKind = 1;
543 else
544 WhichKind = 2;
545 }
546
547 Diag(NewParam->getLocation(),
548 diag::err_param_default_argument_member_template_redecl)
549 << WhichKind
550 << NewParam->getDefaultArgRange();
551 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000552 }
553 }
554
Richard Smithb8abff62012-11-28 03:45:24 +0000555 // DR1344: If a default argument is added outside a class definition and that
556 // default argument makes the function a special member function, the program
557 // is ill-formed. This can only happen for constructors.
558 if (isa<CXXConstructorDecl>(New) &&
559 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
560 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
561 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
562 if (NewSM != OldSM) {
563 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
564 assert(NewParam->hasDefaultArg());
565 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
566 << NewParam->getDefaultArgRange() << NewSM;
567 Diag(Old->getLocation(), diag::note_previous_declaration);
568 }
569 }
570
Richard Smithff234882012-02-20 23:28:05 +0000571 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000572 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000573 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000574 if (New->isConstexpr() != Old->isConstexpr()) {
575 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
576 << New << New->isConstexpr();
577 Diag(Old->getLocation(), diag::note_previous_declaration);
578 Invalid = true;
579 }
580
Douglas Gregore13ad832010-02-12 07:32:17 +0000581 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000582 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000583
Douglas Gregorcda9c672009-02-16 17:45:42 +0000584 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585}
586
Sebastian Redl60618fa2011-03-12 11:50:43 +0000587/// \brief Merge the exception specifications of two variable declarations.
588///
589/// This is called when there's a redeclaration of a VarDecl. The function
590/// checks if the redeclaration might have an exception specification and
591/// validates compatibility and merges the specs if necessary.
592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
593 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000594 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000595 return;
596
597 assert(Context.hasSameType(New->getType(), Old->getType()) &&
598 "Should only be called if types are otherwise the same.");
599
600 QualType NewType = New->getType();
601 QualType OldType = Old->getType();
602
603 // We're only interested in pointers and references to functions, as well
604 // as pointers to member functions.
605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
606 NewType = R->getPointeeType();
607 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
608 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
609 NewType = P->getPointeeType();
610 OldType = OldType->getAs<PointerType>()->getPointeeType();
611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
612 NewType = M->getPointeeType();
613 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
614 }
615
616 if (!NewType->isFunctionProtoType())
617 return;
618
619 // There's lots of special cases for functions. For function pointers, system
620 // libraries are hopefully not as broken so that we don't need these
621 // workarounds.
622 if (CheckEquivalentExceptionSpec(
623 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
624 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
625 New->setInvalidDecl();
626 }
627}
628
Chris Lattner3d1cee32008-04-08 05:04:30 +0000629/// CheckCXXDefaultArguments - Verify that the default arguments for a
630/// function declaration are well-formed according to C++
631/// [dcl.fct.default].
632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
633 unsigned NumParams = FD->getNumParams();
634 unsigned p;
635
636 // Find first parameter with a default argument
637 for (p = 0; p < NumParams; ++p) {
638 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000639 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 break;
641 }
642
643 // C++ [dcl.fct.default]p4:
644 // In a given function declaration, all parameters
645 // subsequent to a parameter with a default argument shall
646 // have default arguments supplied in this or previous
647 // declarations. A default argument shall not be redefined
648 // by a later declaration (not even to the same value).
649 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000650 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000652 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000653 if (Param->isInvalidDecl())
654 /* We already complained about this parameter. */;
655 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000656 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000657 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000658 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000659 else
Mike Stump1eb44332009-09-09 15:08:12 +0000660 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000661 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663 LastMissingDefaultArg = p;
664 }
665 }
666
667 if (LastMissingDefaultArg > 0) {
668 // Some default arguments were missing. Clear out all of the
669 // default arguments up to (and including) the last missing
670 // default argument, so that we leave the function parameters
671 // in a semantically valid state.
672 for (p = 0; p <= LastMissingDefaultArg; ++p) {
673 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000674 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000675 Param->setDefaultArg(0);
676 }
677 }
678 }
679}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000680
Richard Smith9f569cc2011-10-01 02:31:28 +0000681// CheckConstexprParameterTypes - Check whether a function's parameter types
682// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000683// diagnostic and return false.
684static bool CheckConstexprParameterTypes(Sema &SemaRef,
685 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000686 unsigned ArgIndex = 0;
687 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
688 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
689 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
690 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
691 SourceLocation ParamLoc = PD->getLocation();
692 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000693 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000694 diag::err_constexpr_non_literal_param,
695 ArgIndex+1, PD->getSourceRange(),
696 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000697 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000698 }
Joao Matos17d35c32012-08-31 22:18:20 +0000699 return true;
700}
701
702/// \brief Get diagnostic %select index for tag kind for
703/// record diagnostic message.
704/// WARNING: Indexes apply to particular diagnostics only!
705///
706/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000707static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000708 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000709 case TTK_Struct: return 0;
710 case TTK_Interface: return 1;
711 case TTK_Class: return 2;
712 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000713 }
Joao Matos17d35c32012-08-31 22:18:20 +0000714}
715
716// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
717// the requirements of a constexpr function definition or a constexpr
718// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000719// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000720//
Richard Smith86c3ae42012-02-13 03:54:03 +0000721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
722bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000723 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
724 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000725 // C++11 [dcl.constexpr]p4:
726 // The definition of a constexpr constructor shall satisfy the following
727 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000729 const CXXRecordDecl *RD = MD->getParent();
730 if (RD->getNumVBases()) {
731 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
732 << isa<CXXConstructorDecl>(NewFD)
733 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
734 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
735 E = RD->vbases_end(); I != E; ++I)
736 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000737 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000738 return false;
739 }
Richard Smith35340502012-01-13 04:54:00 +0000740 }
741
742 if (!isa<CXXConstructorDecl>(NewFD)) {
743 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000744 // The definition of a constexpr function shall satisfy the following
745 // constraints:
746 // - it shall not be virtual;
747 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
748 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000750
Richard Smith86c3ae42012-02-13 03:54:03 +0000751 // If it's not obvious why this function is virtual, find an overridden
752 // function which uses the 'virtual' keyword.
753 const CXXMethodDecl *WrittenVirtual = Method;
754 while (!WrittenVirtual->isVirtualAsWritten())
755 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
756 if (WrittenVirtual != Method)
757 Diag(WrittenVirtual->getLocation(),
758 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000759 return false;
760 }
761
762 // - its return type shall be a literal type;
763 QualType RT = NewFD->getResultType();
764 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000765 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000766 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000768 }
769
Richard Smith35340502012-01-13 04:54:00 +0000770 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000771 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000772 return false;
773
Richard Smith9f569cc2011-10-01 02:31:28 +0000774 return true;
775}
776
777/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000778/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000779///
Richard Smitha10b9782013-04-22 15:31:51 +0000780/// \return true if the body is OK (maybe only as an extension), false if we
781/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000782static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000783 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
784 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000785 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
786 // contain only
787 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
788 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
789 switch ((*DclIt)->getKind()) {
790 case Decl::StaticAssert:
791 case Decl::Using:
792 case Decl::UsingShadow:
793 case Decl::UsingDirective:
794 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000795 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 // - static_assert-declarations
797 // - using-declarations,
798 // - using-directives,
799 continue;
800
801 case Decl::Typedef:
802 case Decl::TypeAlias: {
803 // - typedef declarations and alias-declarations that do not define
804 // classes or enumerations,
805 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
806 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
807 // Don't allow variably-modified types in constexpr functions.
808 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
809 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
810 << TL.getSourceRange() << TL.getType()
811 << isa<CXXConstructorDecl>(Dcl);
812 return false;
813 }
814 continue;
815 }
816
817 case Decl::Enum:
818 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000819 // C++1y allows types to be defined, not just declared.
820 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
821 SemaRef.Diag(DS->getLocStart(),
822 SemaRef.getLangOpts().CPlusPlus1y
823 ? diag::warn_cxx11_compat_constexpr_type_definition
824 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000825 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000826 continue;
827
Richard Smitha10b9782013-04-22 15:31:51 +0000828 case Decl::EnumConstant:
829 case Decl::IndirectField:
830 case Decl::ParmVar:
831 // These can only appear with other declarations which are banned in
832 // C++11 and permitted in C++1y, so ignore them.
833 continue;
834
835 case Decl::Var: {
836 // C++1y [dcl.constexpr]p3 allows anything except:
837 // a definition of a variable of non-literal type or of static or
838 // thread storage duration or for which no initialization is performed.
839 VarDecl *VD = cast<VarDecl>(*DclIt);
840 if (VD->isThisDeclarationADefinition()) {
841 if (VD->isStaticLocal()) {
842 SemaRef.Diag(VD->getLocation(),
843 diag::err_constexpr_local_var_static)
844 << isa<CXXConstructorDecl>(Dcl)
845 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
846 return false;
847 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000848 if (!VD->getType()->isDependentType() &&
849 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000850 VD->getLocation(), VD->getType(),
851 diag::err_constexpr_local_var_non_literal_type,
852 isa<CXXConstructorDecl>(Dcl)))
853 return false;
854 if (!VD->hasInit()) {
855 SemaRef.Diag(VD->getLocation(),
856 diag::err_constexpr_local_var_no_init)
857 << isa<CXXConstructorDecl>(Dcl);
858 return false;
859 }
860 }
861 SemaRef.Diag(VD->getLocation(),
862 SemaRef.getLangOpts().CPlusPlus1y
863 ? diag::warn_cxx11_compat_constexpr_local_var
864 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000865 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000866 continue;
867 }
868
869 case Decl::NamespaceAlias:
870 case Decl::Function:
871 // These are disallowed in C++11 and permitted in C++1y. Allow them
872 // everywhere as an extension.
873 if (!Cxx1yLoc.isValid())
874 Cxx1yLoc = DS->getLocStart();
875 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000876
877 default:
878 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882 }
883
884 return true;
885}
886
887/// Check that the given field is initialized within a constexpr constructor.
888///
889/// \param Dcl The constexpr constructor being checked.
890/// \param Field The field being checked. This may be a member of an anonymous
891/// struct or union nested within the class being checked.
892/// \param Inits All declarations, including anonymous struct/union members and
893/// indirect members, for which any initialization was provided.
894/// \param Diagnosed Set to true if an error is produced.
895static void CheckConstexprCtorInitializer(Sema &SemaRef,
896 const FunctionDecl *Dcl,
897 FieldDecl *Field,
898 llvm::SmallSet<Decl*, 16> &Inits,
899 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000900 if (Field->isUnnamedBitfield())
901 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000902
903 if (Field->isAnonymousStructOrUnion() &&
904 Field->getType()->getAsCXXRecordDecl()->isEmpty())
905 return;
906
Richard Smith9f569cc2011-10-01 02:31:28 +0000907 if (!Inits.count(Field)) {
908 if (!Diagnosed) {
909 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
910 Diagnosed = true;
911 }
912 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
913 } else if (Field->isAnonymousStructOrUnion()) {
914 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
915 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
916 I != E; ++I)
917 // If an anonymous union contains an anonymous struct of which any member
918 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000919 if (!RD->isUnion() || Inits.count(*I))
920 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000921 }
922}
923
Richard Smitha10b9782013-04-22 15:31:51 +0000924/// Check the provided statement is allowed in a constexpr function
925/// definition.
926static bool
927CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
928 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
929 SourceLocation &Cxx1yLoc) {
930 // - its function-body shall be [...] a compound-statement that contains only
931 switch (S->getStmtClass()) {
932 case Stmt::NullStmtClass:
933 // - null statements,
934 return true;
935
936 case Stmt::DeclStmtClass:
937 // - static_assert-declarations
938 // - using-declarations,
939 // - using-directives,
940 // - typedef declarations and alias-declarations that do not define
941 // classes or enumerations,
942 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
943 return false;
944 return true;
945
946 case Stmt::ReturnStmtClass:
947 // - and exactly one return statement;
948 if (isa<CXXConstructorDecl>(Dcl)) {
949 // C++1y allows return statements in constexpr constructors.
950 if (!Cxx1yLoc.isValid())
951 Cxx1yLoc = S->getLocStart();
952 return true;
953 }
954
955 ReturnStmts.push_back(S->getLocStart());
956 return true;
957
958 case Stmt::CompoundStmtClass: {
959 // C++1y allows compound-statements.
960 if (!Cxx1yLoc.isValid())
961 Cxx1yLoc = S->getLocStart();
962
963 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
964 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
965 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
966 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
967 Cxx1yLoc))
968 return false;
969 }
970 return true;
971 }
972
973 case Stmt::AttributedStmtClass:
974 if (!Cxx1yLoc.isValid())
975 Cxx1yLoc = S->getLocStart();
976 return true;
977
978 case Stmt::IfStmtClass: {
979 // C++1y allows if-statements.
980 if (!Cxx1yLoc.isValid())
981 Cxx1yLoc = S->getLocStart();
982
983 IfStmt *If = cast<IfStmt>(S);
984 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
985 Cxx1yLoc))
986 return false;
987 if (If->getElse() &&
988 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
989 Cxx1yLoc))
990 return false;
991 return true;
992 }
993
994 case Stmt::WhileStmtClass:
995 case Stmt::DoStmtClass:
996 case Stmt::ForStmtClass:
997 case Stmt::CXXForRangeStmtClass:
998 case Stmt::ContinueStmtClass:
999 // C++1y allows all of these. We don't allow them as extensions in C++11,
1000 // because they don't make sense without variable mutation.
1001 if (!SemaRef.getLangOpts().CPlusPlus1y)
1002 break;
1003 if (!Cxx1yLoc.isValid())
1004 Cxx1yLoc = S->getLocStart();
1005 for (Stmt::child_range Children = S->children(); Children; ++Children)
1006 if (*Children &&
1007 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1008 Cxx1yLoc))
1009 return false;
1010 return true;
1011
1012 case Stmt::SwitchStmtClass:
1013 case Stmt::CaseStmtClass:
1014 case Stmt::DefaultStmtClass:
1015 case Stmt::BreakStmtClass:
1016 // C++1y allows switch-statements, and since they don't need variable
1017 // mutation, we can reasonably allow them in C++11 as an extension.
1018 if (!Cxx1yLoc.isValid())
1019 Cxx1yLoc = S->getLocStart();
1020 for (Stmt::child_range Children = S->children(); Children; ++Children)
1021 if (*Children &&
1022 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1023 Cxx1yLoc))
1024 return false;
1025 return true;
1026
1027 default:
1028 if (!isa<Expr>(S))
1029 break;
1030
1031 // C++1y allows expression-statements.
1032 if (!Cxx1yLoc.isValid())
1033 Cxx1yLoc = S->getLocStart();
1034 return true;
1035 }
1036
1037 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1038 << isa<CXXConstructorDecl>(Dcl);
1039 return false;
1040}
1041
Richard Smith9f569cc2011-10-01 02:31:28 +00001042/// Check the body for the given constexpr function declaration only contains
1043/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1044///
1045/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001046bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001047 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001048 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001049 // The definition of a constexpr function shall satisfy the following
1050 // constraints: [...]
1051 // - its function-body shall be = delete, = default, or a
1052 // compound-statement
1053 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001054 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001055 // In the definition of a constexpr constructor, [...]
1056 // - its function-body shall not be a function-try-block;
1057 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1058 << isa<CXXConstructorDecl>(Dcl);
1059 return false;
1060 }
1061
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001062 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001063
1064 // - its function-body shall be [...] a compound-statement that contains only
1065 // [... list of cases ...]
1066 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1067 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001068 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1069 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001070 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1071 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001072 }
1073
Richard Smitha10b9782013-04-22 15:31:51 +00001074 if (Cxx1yLoc.isValid())
1075 Diag(Cxx1yLoc,
1076 getLangOpts().CPlusPlus1y
1077 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1078 : diag::ext_constexpr_body_invalid_stmt)
1079 << isa<CXXConstructorDecl>(Dcl);
1080
Richard Smith9f569cc2011-10-01 02:31:28 +00001081 if (const CXXConstructorDecl *Constructor
1082 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1083 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001084 // DR1359:
1085 // - every non-variant non-static data member and base class sub-object
1086 // shall be initialized;
1087 // - if the class is a non-empty union, or for each non-empty anonymous
1088 // union member of a non-union class, exactly one non-static data member
1089 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001090 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001091 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001092 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1093 return false;
1094 }
Richard Smith6e433752011-10-10 16:38:04 +00001095 } else if (!Constructor->isDependentContext() &&
1096 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001097 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1098
1099 // Skip detailed checking if we have enough initializers, and we would
1100 // allow at most one initializer per member.
1101 bool AnyAnonStructUnionMembers = false;
1102 unsigned Fields = 0;
1103 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1104 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001105 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001106 AnyAnonStructUnionMembers = true;
1107 break;
1108 }
1109 }
1110 if (AnyAnonStructUnionMembers ||
1111 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1112 // Check initialization of non-static data members. Base classes are
1113 // always initialized so do not need to be checked. Dependent bases
1114 // might not have initializers in the member initializer list.
1115 llvm::SmallSet<Decl*, 16> Inits;
1116 for (CXXConstructorDecl::init_const_iterator
1117 I = Constructor->init_begin(), E = Constructor->init_end();
1118 I != E; ++I) {
1119 if (FieldDecl *FD = (*I)->getMember())
1120 Inits.insert(FD);
1121 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1122 Inits.insert(ID->chain_begin(), ID->chain_end());
1123 }
1124
1125 bool Diagnosed = false;
1126 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1127 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001128 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001129 if (Diagnosed)
1130 return false;
1131 }
1132 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001133 } else {
1134 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001135 // C++1y doesn't require constexpr functions to contain a 'return'
1136 // statement. We still do, unless the return type is void, because
1137 // otherwise if there's no return statement, the function cannot
1138 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001139 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001140 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001141 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1142 : diag::err_constexpr_body_no_return);
1143 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001144 }
1145 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001146 Diag(ReturnStmts.back(),
1147 getLangOpts().CPlusPlus1y
1148 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1149 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001150 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1151 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001152 }
1153 }
1154
Richard Smith5ba73e12012-02-04 00:33:54 +00001155 // C++11 [dcl.constexpr]p5:
1156 // if no function argument values exist such that the function invocation
1157 // substitution would produce a constant expression, the program is
1158 // ill-formed; no diagnostic required.
1159 // C++11 [dcl.constexpr]p3:
1160 // - every constructor call and implicit conversion used in initializing the
1161 // return value shall be one of those allowed in a constant expression.
1162 // C++11 [dcl.constexpr]p4:
1163 // - every constructor involved in initializing non-static data members and
1164 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001165 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001166 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001167 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001168 << isa<CXXConstructorDecl>(Dcl);
1169 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1170 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001171 // Don't return false here: we allow this for compatibility in
1172 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001173 }
1174
Richard Smith9f569cc2011-10-01 02:31:28 +00001175 return true;
1176}
1177
Douglas Gregorb48fe382008-10-31 09:07:45 +00001178/// isCurrentClassName - Determine whether the identifier II is the
1179/// name of the class type currently being defined. In the case of
1180/// nested classes, this will only return true if II is the name of
1181/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001182bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1183 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001184 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001185
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001186 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001187 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001188 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001189 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1190 } else
1191 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1192
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001193 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001194 return &II == CurDecl->getIdentifier();
1195 else
1196 return false;
1197}
1198
Douglas Gregor229d47a2012-11-10 07:24:09 +00001199/// \brief Determine whether the given class is a base class of the given
1200/// class, including looking at dependent bases.
1201static bool findCircularInheritance(const CXXRecordDecl *Class,
1202 const CXXRecordDecl *Current) {
1203 SmallVector<const CXXRecordDecl*, 8> Queue;
1204
1205 Class = Class->getCanonicalDecl();
1206 while (true) {
1207 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1208 E = Current->bases_end();
1209 I != E; ++I) {
1210 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1211 if (!Base)
1212 continue;
1213
1214 Base = Base->getDefinition();
1215 if (!Base)
1216 continue;
1217
1218 if (Base->getCanonicalDecl() == Class)
1219 return true;
1220
1221 Queue.push_back(Base);
1222 }
1223
1224 if (Queue.empty())
1225 return false;
1226
1227 Current = Queue.back();
1228 Queue.pop_back();
1229 }
1230
1231 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001232}
1233
Mike Stump1eb44332009-09-09 15:08:12 +00001234/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001235///
1236/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1237/// and returns NULL otherwise.
1238CXXBaseSpecifier *
1239Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1240 SourceRange SpecifierRange,
1241 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001242 TypeSourceInfo *TInfo,
1243 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001244 QualType BaseType = TInfo->getType();
1245
Douglas Gregor2943aed2009-03-03 04:44:36 +00001246 // C++ [class.union]p1:
1247 // A union shall not have base classes.
1248 if (Class->isUnion()) {
1249 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1250 << SpecifierRange;
1251 return 0;
1252 }
1253
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001254 if (EllipsisLoc.isValid() &&
1255 !TInfo->getType()->containsUnexpandedParameterPack()) {
1256 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1257 << TInfo->getTypeLoc().getSourceRange();
1258 EllipsisLoc = SourceLocation();
1259 }
Douglas Gregord777e282012-11-10 01:18:17 +00001260
1261 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1262
1263 if (BaseType->isDependentType()) {
1264 // Make sure that we don't have circular inheritance among our dependent
1265 // bases. For non-dependent bases, the check for completeness below handles
1266 // this.
1267 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1268 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1269 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001270 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001271 Diag(BaseLoc, diag::err_circular_inheritance)
1272 << BaseType << Context.getTypeDeclType(Class);
1273
1274 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1275 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1276 << BaseType;
1277
1278 return 0;
1279 }
1280 }
1281
Mike Stump1eb44332009-09-09 15:08:12 +00001282 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001283 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001284 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001285 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001286
1287 // Base specifiers must be record types.
1288 if (!BaseType->isRecordType()) {
1289 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1290 return 0;
1291 }
1292
1293 // C++ [class.union]p1:
1294 // A union shall not be used as a base class.
1295 if (BaseType->isUnionType()) {
1296 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1297 return 0;
1298 }
1299
1300 // C++ [class.derived]p2:
1301 // The class-name in a base-specifier shall not be an incompletely
1302 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001303 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001304 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001305 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001306 return 0;
John McCall572fc622010-08-17 07:23:57 +00001307 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001308
Eli Friedman1d954f62009-08-15 21:55:26 +00001309 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001310 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001312 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001313 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer585bee42013-06-06 23:43:20 +00001314 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001315 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001316
Anders Carlsson1d209272011-03-25 14:55:14 +00001317 // C++ [class]p3:
1318 // If a class is marked final and it appears as a base-type-specifier in
1319 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001320 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001321 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1322 << CXXBaseDecl->getDeclName();
1323 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1324 << CXXBaseDecl->getDeclName();
1325 return 0;
1326 }
1327
John McCall572fc622010-08-17 07:23:57 +00001328 if (BaseDecl->isInvalidDecl())
1329 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001330
1331 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001332 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001333 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001334 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001335}
1336
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001337/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1338/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001339/// example:
1340/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001341/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001342BaseResult
John McCalld226f652010-08-21 09:40:31 +00001343Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001344 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001345 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001346 ParsedType basetype, SourceLocation BaseLoc,
1347 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001348 if (!classdecl)
1349 return true;
1350
Douglas Gregor40808ce2009-03-09 23:48:35 +00001351 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001352 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001353 if (!Class)
1354 return true;
1355
Richard Smith05321402013-02-19 23:47:15 +00001356 // We do not support any C++11 attributes on base-specifiers yet.
1357 // Diagnose any attributes we see.
1358 if (!Attributes.empty()) {
1359 for (AttributeList *Attr = Attributes.getList(); Attr;
1360 Attr = Attr->getNext()) {
1361 if (Attr->isInvalid() ||
1362 Attr->getKind() == AttributeList::IgnoredAttribute)
1363 continue;
1364 Diag(Attr->getLoc(),
1365 Attr->getKind() == AttributeList::UnknownAttribute
1366 ? diag::warn_unknown_attribute_ignored
1367 : diag::err_base_specifier_attribute)
1368 << Attr->getName();
1369 }
1370 }
1371
Nick Lewycky56062202010-07-26 16:56:01 +00001372 TypeSourceInfo *TInfo = 0;
1373 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001374
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001375 if (EllipsisLoc.isInvalid() &&
1376 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001377 UPPC_BaseType))
1378 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001379
Douglas Gregor2943aed2009-03-03 04:44:36 +00001380 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001381 Virtual, Access, TInfo,
1382 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001383 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001384 else
1385 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Douglas Gregor2943aed2009-03-03 04:44:36 +00001387 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001388}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001389
Douglas Gregor2943aed2009-03-03 04:44:36 +00001390/// \brief Performs the actual work of attaching the given base class
1391/// specifiers to a C++ class.
1392bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1393 unsigned NumBases) {
1394 if (NumBases == 0)
1395 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001396
1397 // Used to keep track of which base types we have already seen, so
1398 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001399 // that the key is always the unqualified canonical type of the base
1400 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001401 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1402
1403 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001404 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001405 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001406 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001407 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001408 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001409 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001410
1411 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1412 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001413 // C++ [class.mi]p3:
1414 // A class shall not be specified as a direct base class of a
1415 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001416 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001417 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001418 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001419 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001420
1421 // Delete the duplicate base class specifier; we're going to
1422 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001423 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001424
1425 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001426 } else {
1427 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001428 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001429 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001430 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1431 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1432 if (Class->isInterface() &&
1433 (!RD->isInterface() ||
1434 KnownBase->getAccessSpecifier() != AS_public)) {
1435 // The Microsoft extension __interface does not permit bases that
1436 // are not themselves public interfaces.
1437 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1438 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1439 << RD->getSourceRange();
1440 Invalid = true;
1441 }
1442 if (RD->hasAttr<WeakAttr>())
1443 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1444 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001445 }
1446 }
1447
1448 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001449 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001450
1451 // Delete the remaining (good) base class specifiers, since their
1452 // data has been copied into the CXXRecordDecl.
1453 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001454 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001455
1456 return Invalid;
1457}
1458
1459/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1460/// class, after checking whether there are any duplicate base
1461/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001462void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001463 unsigned NumBases) {
1464 if (!ClassDecl || !Bases || !NumBases)
1465 return;
1466
1467 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001468 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001469 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001470}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001471
Douglas Gregora8f32e02009-10-06 17:59:45 +00001472/// \brief Determine whether the type \p Derived is a C++ class that is
1473/// derived from the type \p Base.
1474bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001475 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001476 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001477
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001478 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001479 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001480 return false;
1481
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001482 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001483 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001484 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001485
1486 // If either the base or the derived type is invalid, don't try to
1487 // check whether one is derived from the other.
1488 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1489 return false;
1490
John McCall86ff3082010-02-04 22:26:26 +00001491 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1492 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001493}
1494
1495/// \brief Determine whether the type \p Derived is a C++ class that is
1496/// derived from the type \p Base.
1497bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001498 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001499 return false;
1500
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001501 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001502 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001503 return false;
1504
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001505 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001506 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001507 return false;
1508
Douglas Gregora8f32e02009-10-06 17:59:45 +00001509 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1510}
1511
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001512void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001513 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001514 assert(BasePathArray.empty() && "Base path array must be empty!");
1515 assert(Paths.isRecordingPaths() && "Must record paths!");
1516
1517 const CXXBasePath &Path = Paths.front();
1518
1519 // We first go backward and check if we have a virtual base.
1520 // FIXME: It would be better if CXXBasePath had the base specifier for
1521 // the nearest virtual base.
1522 unsigned Start = 0;
1523 for (unsigned I = Path.size(); I != 0; --I) {
1524 if (Path[I - 1].Base->isVirtual()) {
1525 Start = I - 1;
1526 break;
1527 }
1528 }
1529
1530 // Now add all bases.
1531 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001532 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001533}
1534
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001535/// \brief Determine whether the given base path includes a virtual
1536/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001537bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1538 for (CXXCastPath::const_iterator B = BasePath.begin(),
1539 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001540 B != BEnd; ++B)
1541 if ((*B)->isVirtual())
1542 return true;
1543
1544 return false;
1545}
1546
Douglas Gregora8f32e02009-10-06 17:59:45 +00001547/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1548/// conversion (where Derived and Base are class types) is
1549/// well-formed, meaning that the conversion is unambiguous (and
1550/// that all of the base classes are accessible). Returns true
1551/// and emits a diagnostic if the code is ill-formed, returns false
1552/// otherwise. Loc is the location where this routine should point to
1553/// if there is an error, and Range is the source range to highlight
1554/// if there is an error.
1555bool
1556Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001557 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001558 unsigned AmbigiousBaseConvID,
1559 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001560 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001561 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001562 // First, determine whether the path from Derived to Base is
1563 // ambiguous. This is slightly more expensive than checking whether
1564 // the Derived to Base conversion exists, because here we need to
1565 // explore multiple paths to determine if there is an ambiguity.
1566 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1567 /*DetectVirtual=*/false);
1568 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1569 assert(DerivationOkay &&
1570 "Can only be used with a derived-to-base conversion");
1571 (void)DerivationOkay;
1572
1573 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001574 if (InaccessibleBaseID) {
1575 // Check that the base class can be accessed.
1576 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1577 InaccessibleBaseID)) {
1578 case AR_inaccessible:
1579 return true;
1580 case AR_accessible:
1581 case AR_dependent:
1582 case AR_delayed:
1583 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001584 }
John McCall6b2accb2010-02-10 09:31:12 +00001585 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001586
1587 // Build a base path if necessary.
1588 if (BasePath)
1589 BuildBasePathArray(Paths, *BasePath);
1590 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001591 }
1592
1593 // We know that the derived-to-base conversion is ambiguous, and
1594 // we're going to produce a diagnostic. Perform the derived-to-base
1595 // search just one more time to compute all of the possible paths so
1596 // that we can print them out. This is more expensive than any of
1597 // the previous derived-to-base checks we've done, but at this point
1598 // performance isn't as much of an issue.
1599 Paths.clear();
1600 Paths.setRecordingPaths(true);
1601 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1602 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1603 (void)StillOkay;
1604
1605 // Build up a textual representation of the ambiguous paths, e.g.,
1606 // D -> B -> A, that will be used to illustrate the ambiguous
1607 // conversions in the diagnostic. We only print one of the paths
1608 // to each base class subobject.
1609 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1610
1611 Diag(Loc, AmbigiousBaseConvID)
1612 << Derived << Base << PathDisplayStr << Range << Name;
1613 return true;
1614}
1615
1616bool
1617Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001618 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001619 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001620 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001621 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001622 IgnoreAccess ? 0
1623 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001624 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001625 Loc, Range, DeclarationName(),
1626 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001627}
1628
1629
1630/// @brief Builds a string representing ambiguous paths from a
1631/// specific derived class to different subobjects of the same base
1632/// class.
1633///
1634/// This function builds a string that can be used in error messages
1635/// to show the different paths that one can take through the
1636/// inheritance hierarchy to go from the derived class to different
1637/// subobjects of a base class. The result looks something like this:
1638/// @code
1639/// struct D -> struct B -> struct A
1640/// struct D -> struct C -> struct A
1641/// @endcode
1642std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1643 std::string PathDisplayStr;
1644 std::set<unsigned> DisplayedPaths;
1645 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1646 Path != Paths.end(); ++Path) {
1647 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1648 // We haven't displayed a path to this particular base
1649 // class subobject yet.
1650 PathDisplayStr += "\n ";
1651 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1652 for (CXXBasePath::const_iterator Element = Path->begin();
1653 Element != Path->end(); ++Element)
1654 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1655 }
1656 }
1657
1658 return PathDisplayStr;
1659}
1660
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001661//===----------------------------------------------------------------------===//
1662// C++ class member Handling
1663//===----------------------------------------------------------------------===//
1664
Abramo Bagnara6206d532010-06-05 05:09:32 +00001665/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001666bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1667 SourceLocation ASLoc,
1668 SourceLocation ColonLoc,
1669 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001670 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001671 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001672 ASLoc, ColonLoc);
1673 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001674 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001675}
1676
Richard Smitha4b39652012-08-06 03:25:17 +00001677/// CheckOverrideControl - Check C++11 override control semantics.
1678void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001679 if (D->isInvalidDecl())
1680 return;
1681
Chris Lattner5f9e2722011-07-23 10:55:15 +00001682 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001683
Richard Smitha4b39652012-08-06 03:25:17 +00001684 // Do we know which functions this declaration might be overriding?
1685 bool OverridesAreKnown = !MD ||
1686 (!MD->getParent()->hasAnyDependentBases() &&
1687 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001688
Richard Smitha4b39652012-08-06 03:25:17 +00001689 if (!MD || !MD->isVirtual()) {
1690 if (OverridesAreKnown) {
1691 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1692 Diag(OA->getLocation(),
1693 diag::override_keyword_only_allowed_on_virtual_member_functions)
1694 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1695 D->dropAttr<OverrideAttr>();
1696 }
1697 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1698 Diag(FA->getLocation(),
1699 diag::override_keyword_only_allowed_on_virtual_member_functions)
1700 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1701 D->dropAttr<FinalAttr>();
1702 }
1703 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001704 return;
1705 }
Richard Smitha4b39652012-08-06 03:25:17 +00001706
1707 if (!OverridesAreKnown)
1708 return;
1709
1710 // C++11 [class.virtual]p5:
1711 // If a virtual function is marked with the virt-specifier override and
1712 // does not override a member function of a base class, the program is
1713 // ill-formed.
1714 bool HasOverriddenMethods =
1715 MD->begin_overridden_methods() != MD->end_overridden_methods();
1716 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1717 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1718 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001719}
1720
Richard Smitha4b39652012-08-06 03:25:17 +00001721/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001722/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001723/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001724bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1725 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001726 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001727 return false;
1728
1729 Diag(New->getLocation(), diag::err_final_function_overridden)
1730 << New->getDeclName();
1731 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1732 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001733}
1734
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001735static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001736 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1737 // FIXME: Destruction of ObjC lifetime types has side-effects.
1738 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1739 return !RD->isCompleteDefinition() ||
1740 !RD->hasTrivialDefaultConstructor() ||
1741 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001742 return false;
1743}
1744
John McCall76da55d2013-04-16 07:28:30 +00001745static AttributeList *getMSPropertyAttr(AttributeList *list) {
1746 for (AttributeList* it = list; it != 0; it = it->getNext())
1747 if (it->isDeclspecPropertyAttribute())
1748 return it;
1749 return 0;
1750}
1751
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001752/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1753/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001754/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001755/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1756/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001757NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001758Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001759 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001760 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001761 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001762 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001763 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1764 DeclarationName Name = NameInfo.getName();
1765 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001766
1767 // For anonymous bitfields, the location should point to the type.
1768 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001769 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001770
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001771 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001772
John McCall4bde1e12010-06-04 08:34:12 +00001773 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001774 assert(!DS.isFriendSpecified());
1775
Richard Smith1ab0d902011-06-25 02:28:38 +00001776 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001777
John McCalle402e722012-09-25 07:32:39 +00001778 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1779 // The Microsoft extension __interface only permits public member functions
1780 // and prohibits constructors, destructors, operators, non-public member
1781 // functions, static methods and data members.
1782 unsigned InvalidDecl;
1783 bool ShowDeclName = true;
1784 if (!isFunc)
1785 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1786 else if (AS != AS_public)
1787 InvalidDecl = 2;
1788 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1789 InvalidDecl = 3;
1790 else switch (Name.getNameKind()) {
1791 case DeclarationName::CXXConstructorName:
1792 InvalidDecl = 4;
1793 ShowDeclName = false;
1794 break;
1795
1796 case DeclarationName::CXXDestructorName:
1797 InvalidDecl = 5;
1798 ShowDeclName = false;
1799 break;
1800
1801 case DeclarationName::CXXOperatorName:
1802 case DeclarationName::CXXConversionFunctionName:
1803 InvalidDecl = 6;
1804 break;
1805
1806 default:
1807 InvalidDecl = 0;
1808 break;
1809 }
1810
1811 if (InvalidDecl) {
1812 if (ShowDeclName)
1813 Diag(Loc, diag::err_invalid_member_in_interface)
1814 << (InvalidDecl-1) << Name;
1815 else
1816 Diag(Loc, diag::err_invalid_member_in_interface)
1817 << (InvalidDecl-1) << "";
1818 return 0;
1819 }
1820 }
1821
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001822 // C++ 9.2p6: A member shall not be declared to have automatic storage
1823 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001824 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1825 // data members and cannot be applied to names declared const or static,
1826 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001827 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001828 case DeclSpec::SCS_unspecified:
1829 case DeclSpec::SCS_typedef:
1830 case DeclSpec::SCS_static:
1831 break;
1832 case DeclSpec::SCS_mutable:
1833 if (isFunc) {
1834 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Richard Smithec642442013-04-12 22:46:28 +00001836 // FIXME: It would be nicer if the keyword was ignored only for this
1837 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001838 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001839 }
1840 break;
1841 default:
1842 Diag(DS.getStorageClassSpecLoc(),
1843 diag::err_storageclass_invalid_for_member);
1844 D.getMutableDeclSpec().ClearStorageClassSpecs();
1845 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001846 }
1847
Sebastian Redl669d5d72008-11-14 23:42:31 +00001848 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1849 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001850 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001851
David Blaikie1d87fba2013-01-30 01:22:18 +00001852 if (DS.isConstexprSpecified() && isInstField) {
1853 SemaDiagnosticBuilder B =
1854 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1855 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1856 if (InitStyle == ICIS_NoInit) {
1857 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1858 D.getMutableDeclSpec().ClearConstexprSpec();
1859 const char *PrevSpec;
1860 unsigned DiagID;
1861 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1862 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001863 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001864 assert(!Failed && "Making a constexpr member const shouldn't fail");
1865 } else {
1866 B << 1;
1867 const char *PrevSpec;
1868 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001869 if (D.getMutableDeclSpec().SetStorageClassSpec(
1870 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001871 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001872 "This is the only DeclSpec that should fail to be applied");
1873 B << 1;
1874 } else {
1875 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1876 isInstField = false;
1877 }
1878 }
1879 }
1880
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001881 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001882 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001883 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001884
1885 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001886 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001887 Diag(Loc, diag::err_bad_variable_name)
1888 << Name;
1889 return 0;
1890 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001891
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001892 IdentifierInfo *II = Name.getAsIdentifierInfo();
1893
Douglas Gregorf2503652011-09-21 14:40:46 +00001894 // Member field could not be with "template" keyword.
1895 // So TemplateParameterLists should be empty in this case.
1896 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001897 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001898 if (TemplateParams->size()) {
1899 // There is no such thing as a member field template.
1900 Diag(D.getIdentifierLoc(), diag::err_template_member)
1901 << II
1902 << SourceRange(TemplateParams->getTemplateLoc(),
1903 TemplateParams->getRAngleLoc());
1904 } else {
1905 // There is an extraneous 'template<>' for this member.
1906 Diag(TemplateParams->getTemplateLoc(),
1907 diag::err_template_member_noparams)
1908 << II
1909 << SourceRange(TemplateParams->getTemplateLoc(),
1910 TemplateParams->getRAngleLoc());
1911 }
1912 return 0;
1913 }
1914
Douglas Gregor922fff22010-10-13 22:19:53 +00001915 if (SS.isSet() && !SS.isInvalid()) {
1916 // The user provided a superfluous scope specifier inside a class
1917 // definition:
1918 //
1919 // class X {
1920 // int X::member;
1921 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001922 if (DeclContext *DC = computeDeclContext(SS, false))
1923 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001924 else
1925 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1926 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001927
Douglas Gregor922fff22010-10-13 22:19:53 +00001928 SS.clear();
1929 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001930
John McCall76da55d2013-04-16 07:28:30 +00001931 AttributeList *MSPropertyAttr =
1932 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1933 if (MSPropertyAttr) {
1934 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1935 BitWidth, InitStyle, AS, MSPropertyAttr);
1936 isInstField = false;
1937 } else {
1938 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1939 BitWidth, InitStyle, AS);
1940 }
Chris Lattner6f8ce142009-03-05 23:03:49 +00001941 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001942 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001943 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001944
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001945 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001946 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001947 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001948 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001949
1950 // Non-instance-fields can't have a bitfield.
1951 if (BitWidth) {
1952 if (Member->isInvalidDecl()) {
1953 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001954 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001955 // C++ 9.6p3: A bit-field shall not be a static member.
1956 // "static member 'A' cannot be a bit-field"
1957 Diag(Loc, diag::err_static_not_bitfield)
1958 << Name << BitWidth->getSourceRange();
1959 } else if (isa<TypedefDecl>(Member)) {
1960 // "typedef member 'x' cannot be a bit-field"
1961 Diag(Loc, diag::err_typedef_not_bitfield)
1962 << Name << BitWidth->getSourceRange();
1963 } else {
1964 // A function typedef ("typedef int f(); f a;").
1965 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1966 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001967 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001968 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001969 }
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Chris Lattner8b963ef2009-03-05 23:01:03 +00001971 BitWidth = 0;
1972 Member->setInvalidDecl();
1973 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001974
1975 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Douglas Gregor37b372b2009-08-20 22:52:58 +00001977 // If we have declared a member function template, set the access of the
1978 // templated declaration as well.
1979 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1980 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001981 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001982
Richard Smitha4b39652012-08-06 03:25:17 +00001983 if (VS.isOverrideSpecified())
1984 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1985 if (VS.isFinalSpecified())
1986 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001987
Douglas Gregorf5251602011-03-08 17:10:18 +00001988 if (VS.getLastLocation().isValid()) {
1989 // Update the end location of a method that has a virt-specifiers.
1990 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1991 MD->setRangeEnd(VS.getLastLocation());
1992 }
Richard Smitha4b39652012-08-06 03:25:17 +00001993
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001994 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001995
Douglas Gregor10bd3682008-11-17 22:58:34 +00001996 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001997
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001998 if (isInstField) {
1999 FieldDecl *FD = cast<FieldDecl>(Member);
2000 FieldCollector->Add(FD);
2001
2002 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2003 FD->getLocation())
2004 != DiagnosticsEngine::Ignored) {
2005 // Remember all explicit private FieldDecls that have a name, no side
2006 // effects and are not part of a dependent type declaration.
2007 if (!FD->isImplicit() && FD->getDeclName() &&
2008 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002009 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002010 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002011 !InitializationHasSideEffects(*FD))
2012 UnusedPrivateFields.insert(FD);
2013 }
2014 }
2015
John McCalld226f652010-08-21 09:40:31 +00002016 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002017}
2018
Hans Wennborg471f9852012-09-18 15:58:06 +00002019namespace {
2020 class UninitializedFieldVisitor
2021 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2022 Sema &S;
2023 ValueDecl *VD;
2024 public:
2025 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2026 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002027 S(S) {
2028 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2029 this->VD = IFD->getAnonField();
2030 else
2031 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002032 }
2033
2034 void HandleExpr(Expr *E) {
2035 if (!E) return;
2036
2037 // Expressions like x(x) sometimes lack the surrounding expressions
2038 // but need to be checked anyways.
2039 HandleValue(E);
2040 Visit(E);
2041 }
2042
2043 void HandleValue(Expr *E) {
2044 E = E->IgnoreParens();
2045
2046 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2047 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002048 return;
2049
2050 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2051 // or union.
2052 MemberExpr *FieldME = ME;
2053
Hans Wennborg471f9852012-09-18 15:58:06 +00002054 Expr *Base = E;
2055 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002056 ME = cast<MemberExpr>(Base);
2057
2058 if (isa<VarDecl>(ME->getMemberDecl()))
2059 return;
2060
2061 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2062 if (!FD->isAnonymousStructOrUnion())
2063 FieldME = ME;
2064
Hans Wennborg471f9852012-09-18 15:58:06 +00002065 Base = ME->getBase();
2066 }
2067
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002068 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002069 unsigned diag = VD->getType()->isReferenceType()
2070 ? diag::warn_reference_field_is_uninit
2071 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002072 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002073 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002074 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002075 }
2076
2077 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2078 HandleValue(CO->getTrueExpr());
2079 HandleValue(CO->getFalseExpr());
2080 return;
2081 }
2082
2083 if (BinaryConditionalOperator *BCO =
2084 dyn_cast<BinaryConditionalOperator>(E)) {
2085 HandleValue(BCO->getCommon());
2086 HandleValue(BCO->getFalseExpr());
2087 return;
2088 }
2089
2090 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2091 switch (BO->getOpcode()) {
2092 default:
2093 return;
2094 case(BO_PtrMemD):
2095 case(BO_PtrMemI):
2096 HandleValue(BO->getLHS());
2097 return;
2098 case(BO_Comma):
2099 HandleValue(BO->getRHS());
2100 return;
2101 }
2102 }
2103 }
2104
2105 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2106 if (E->getCastKind() == CK_LValueToRValue)
2107 HandleValue(E->getSubExpr());
2108
2109 Inherited::VisitImplicitCastExpr(E);
2110 }
2111
2112 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2113 Expr *Callee = E->getCallee();
2114 if (isa<MemberExpr>(Callee))
2115 HandleValue(Callee);
2116
2117 Inherited::VisitCXXMemberCallExpr(E);
2118 }
2119 };
2120 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2121 ValueDecl *VD) {
2122 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2123 }
2124} // namespace
2125
Richard Smith7a614d82011-06-11 17:19:42 +00002126/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002127/// in-class initializer for a non-static C++ class member, and after
2128/// instantiating an in-class initializer in a class template. Such actions
2129/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002130void
Richard Smithca523302012-06-10 03:12:00 +00002131Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002132 Expr *InitExpr) {
2133 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002134 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2135 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002136
2137 if (!InitExpr) {
2138 FD->setInvalidDecl();
2139 FD->removeInClassInitializer();
2140 return;
2141 }
2142
Peter Collingbournefef21892011-10-23 18:59:44 +00002143 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2144 FD->setInvalidDecl();
2145 FD->removeInClassInitializer();
2146 return;
2147 }
2148
Hans Wennborg471f9852012-09-18 15:58:06 +00002149 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2150 != DiagnosticsEngine::Ignored) {
2151 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2152 }
2153
Richard Smith7a614d82011-06-11 17:19:42 +00002154 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002155 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00002156 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002157 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00002158 << /*at end of ctor*/1 << InitExpr->getSourceRange();
2159 }
Sebastian Redl33deb352012-02-22 10:50:08 +00002160 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002161 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002162 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002163 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002164 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2165 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002166 if (Init.isInvalid()) {
2167 FD->setInvalidDecl();
2168 return;
2169 }
Richard Smith7a614d82011-06-11 17:19:42 +00002170 }
2171
Richard Smith41956372013-01-14 22:39:08 +00002172 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002173 // The initialization of each base and member constitutes a
2174 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002175 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002176 if (Init.isInvalid()) {
2177 FD->setInvalidDecl();
2178 return;
2179 }
2180
2181 InitExpr = Init.release();
2182
2183 FD->setInClassInitializer(InitExpr);
2184}
2185
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002186/// \brief Find the direct and/or virtual base specifiers that
2187/// correspond to the given base type, for use in base initialization
2188/// within a constructor.
2189static bool FindBaseInitializer(Sema &SemaRef,
2190 CXXRecordDecl *ClassDecl,
2191 QualType BaseType,
2192 const CXXBaseSpecifier *&DirectBaseSpec,
2193 const CXXBaseSpecifier *&VirtualBaseSpec) {
2194 // First, check for a direct base class.
2195 DirectBaseSpec = 0;
2196 for (CXXRecordDecl::base_class_const_iterator Base
2197 = ClassDecl->bases_begin();
2198 Base != ClassDecl->bases_end(); ++Base) {
2199 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2200 // We found a direct base of this type. That's what we're
2201 // initializing.
2202 DirectBaseSpec = &*Base;
2203 break;
2204 }
2205 }
2206
2207 // Check for a virtual base class.
2208 // FIXME: We might be able to short-circuit this if we know in advance that
2209 // there are no virtual bases.
2210 VirtualBaseSpec = 0;
2211 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2212 // We haven't found a base yet; search the class hierarchy for a
2213 // virtual base class.
2214 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2215 /*DetectVirtual=*/false);
2216 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2217 BaseType, Paths)) {
2218 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2219 Path != Paths.end(); ++Path) {
2220 if (Path->back().Base->isVirtual()) {
2221 VirtualBaseSpec = Path->back().Base;
2222 break;
2223 }
2224 }
2225 }
2226 }
2227
2228 return DirectBaseSpec || VirtualBaseSpec;
2229}
2230
Sebastian Redl6df65482011-09-24 17:48:25 +00002231/// \brief Handle a C++ member initializer using braced-init-list syntax.
2232MemInitResult
2233Sema::ActOnMemInitializer(Decl *ConstructorD,
2234 Scope *S,
2235 CXXScopeSpec &SS,
2236 IdentifierInfo *MemberOrBase,
2237 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002238 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002239 SourceLocation IdLoc,
2240 Expr *InitList,
2241 SourceLocation EllipsisLoc) {
2242 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002243 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002244 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002245}
2246
2247/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002248MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002249Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002250 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002251 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002252 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002253 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002254 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002255 SourceLocation IdLoc,
2256 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002257 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002258 SourceLocation RParenLoc,
2259 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002260 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002261 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002262 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002263 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002264}
2265
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002266namespace {
2267
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002268// Callback to only accept typo corrections that can be a valid C++ member
2269// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002270class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2271 public:
2272 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2273 : ClassDecl(ClassDecl) {}
2274
2275 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2276 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2277 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2278 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2279 else
2280 return isa<TypeDecl>(ND);
2281 }
2282 return false;
2283 }
2284
2285 private:
2286 CXXRecordDecl *ClassDecl;
2287};
2288
2289}
2290
Sebastian Redl6df65482011-09-24 17:48:25 +00002291/// \brief Handle a C++ member initializer.
2292MemInitResult
2293Sema::BuildMemInitializer(Decl *ConstructorD,
2294 Scope *S,
2295 CXXScopeSpec &SS,
2296 IdentifierInfo *MemberOrBase,
2297 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002298 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002299 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002300 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002301 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002302 if (!ConstructorD)
2303 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002305 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002306
2307 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002308 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002309 if (!Constructor) {
2310 // The user wrote a constructor initializer on a function that is
2311 // not a C++ constructor. Ignore the error for now, because we may
2312 // have more member initializers coming; we'll diagnose it just
2313 // once in ActOnMemInitializers.
2314 return true;
2315 }
2316
2317 CXXRecordDecl *ClassDecl = Constructor->getParent();
2318
2319 // C++ [class.base.init]p2:
2320 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002321 // constructor's class and, if not found in that scope, are looked
2322 // up in the scope containing the constructor's definition.
2323 // [Note: if the constructor's class contains a member with the
2324 // same name as a direct or virtual base class of the class, a
2325 // mem-initializer-id naming the member or base class and composed
2326 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002327 // mem-initializer-id for the hidden base class may be specified
2328 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002329 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002330 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002331 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002332 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002333 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002334 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002335 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2336 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002337 if (EllipsisLoc.isValid())
2338 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002339 << MemberOrBase
2340 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002341
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002342 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002343 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002344 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002345 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002346 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002347 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002348 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002349
2350 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002351 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002352 } else if (DS.getTypeSpecType() == TST_decltype) {
2353 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002354 } else {
2355 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2356 LookupParsedName(R, S, &SS);
2357
2358 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2359 if (!TyD) {
2360 if (R.isAmbiguous()) return true;
2361
John McCallfd225442010-04-09 19:01:14 +00002362 // We don't want access-control diagnostics here.
2363 R.suppressDiagnostics();
2364
Douglas Gregor7a886e12010-01-19 06:46:48 +00002365 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2366 bool NotUnknownSpecialization = false;
2367 DeclContext *DC = computeDeclContext(SS, false);
2368 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2369 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2370
2371 if (!NotUnknownSpecialization) {
2372 // When the scope specifier can refer to a member of an unknown
2373 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002374 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2375 SS.getWithLocInContext(Context),
2376 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002377 if (BaseType.isNull())
2378 return true;
2379
Douglas Gregor7a886e12010-01-19 06:46:48 +00002380 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002381 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002382 }
2383 }
2384
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002385 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002386 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002387 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002388 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002389 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002390 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002391 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2392 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002393 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002394 // We have found a non-static data member with a similar
2395 // name to what was typed; complain and initialize that
2396 // member.
2397 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2398 << MemberOrBase << true << CorrectedQuotedStr
2399 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2400 Diag(Member->getLocation(), diag::note_previous_decl)
2401 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002402
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002403 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002404 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002405 const CXXBaseSpecifier *DirectBaseSpec;
2406 const CXXBaseSpecifier *VirtualBaseSpec;
2407 if (FindBaseInitializer(*this, ClassDecl,
2408 Context.getTypeDeclType(Type),
2409 DirectBaseSpec, VirtualBaseSpec)) {
2410 // We have found a direct or virtual base class with a
2411 // similar name to what was typed; complain and initialize
2412 // that base class.
2413 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002414 << MemberOrBase << false << CorrectedQuotedStr
2415 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002416
2417 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2418 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002419 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002420 diag::note_base_class_specified_here)
2421 << BaseSpec->getType()
2422 << BaseSpec->getSourceRange();
2423
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002424 TyD = Type;
2425 }
2426 }
2427 }
2428
Douglas Gregor7a886e12010-01-19 06:46:48 +00002429 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002430 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002431 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002432 return true;
2433 }
John McCall2b194412009-12-21 10:41:20 +00002434 }
2435
Douglas Gregor7a886e12010-01-19 06:46:48 +00002436 if (BaseType.isNull()) {
2437 BaseType = Context.getTypeDeclType(TyD);
2438 if (SS.isSet()) {
2439 NestedNameSpecifier *Qualifier =
2440 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002441
Douglas Gregor7a886e12010-01-19 06:46:48 +00002442 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002443 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002444 }
John McCall2b194412009-12-21 10:41:20 +00002445 }
2446 }
Mike Stump1eb44332009-09-09 15:08:12 +00002447
John McCalla93c9342009-12-07 02:54:59 +00002448 if (!TInfo)
2449 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002450
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002451 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002452}
2453
Chandler Carruth81c64772011-09-03 01:14:15 +00002454/// Checks a member initializer expression for cases where reference (or
2455/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002456static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2457 Expr *Init,
2458 SourceLocation IdLoc) {
2459 QualType MemberTy = Member->getType();
2460
2461 // We only handle pointers and references currently.
2462 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2463 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2464 return;
2465
2466 const bool IsPointer = MemberTy->isPointerType();
2467 if (IsPointer) {
2468 if (const UnaryOperator *Op
2469 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2470 // The only case we're worried about with pointers requires taking the
2471 // address.
2472 if (Op->getOpcode() != UO_AddrOf)
2473 return;
2474
2475 Init = Op->getSubExpr();
2476 } else {
2477 // We only handle address-of expression initializers for pointers.
2478 return;
2479 }
2480 }
2481
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002482 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2483 // Taking the address of a temporary will be diagnosed as a hard error.
2484 if (IsPointer)
2485 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002486
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002487 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2488 << Member << Init->getSourceRange();
2489 } else if (const DeclRefExpr *DRE
2490 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2491 // We only warn when referring to a non-reference parameter declaration.
2492 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2493 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002494 return;
2495
2496 S.Diag(Init->getExprLoc(),
2497 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2498 : diag::warn_bind_ref_member_to_parameter)
2499 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002500 } else {
2501 // Other initializers are fine.
2502 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002503 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002504
2505 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2506 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002507}
2508
John McCallf312b1e2010-08-26 23:41:50 +00002509MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002510Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002511 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002512 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2513 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2514 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002515 "Member must be a FieldDecl or IndirectFieldDecl");
2516
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002517 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002518 return true;
2519
Douglas Gregor464b2f02010-11-05 22:21:31 +00002520 if (Member->isInvalidDecl())
2521 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002522
John McCallb4190042009-11-04 23:02:40 +00002523 // Diagnose value-uses of fields to initialize themselves, e.g.
2524 // foo(foo)
2525 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002526 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002527 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002528 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002529 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002530 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002531 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002532 } else {
2533 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002534 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002535 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002536
Richard Trieude5e75c2012-06-14 23:11:34 +00002537 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2538 != DiagnosticsEngine::Ignored)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002539 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieude5e75c2012-06-14 23:11:34 +00002540 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002541 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002542 // initializing the i'th field, throw a warning if any of the >= i'th
2543 // fields are used, as they are not yet initialized.
2544 // Right now we are only handling the case where the i'th field uses
2545 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002546 // Also need to take into account that some fields may be initialized by
2547 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002548 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002549
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002550 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002551
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002552 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002553 // Can't check initialization for a member of dependent type or when
2554 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002555 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002556 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002557 bool InitList = false;
2558 if (isa<InitListExpr>(Init)) {
2559 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002560 Args = Init;
Sebastian Redl772291a2012-02-19 16:31:05 +00002561
2562 if (isStdInitializerList(Member->getType(), 0)) {
2563 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2564 << /*at end of ctor*/1 << InitRange;
2565 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002566 }
2567
Chandler Carruth894aed92010-12-06 09:23:57 +00002568 // Initialize the member.
2569 InitializedEntity MemberEntity =
2570 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2571 : InitializedEntity::InitializeMember(IndirectMember, 0);
2572 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002573 InitList ? InitializationKind::CreateDirectList(IdLoc)
2574 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2575 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002576
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002577 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2578 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002579 if (MemberInit.isInvalid())
2580 return true;
2581
Richard Smith8a07cd32013-06-12 20:42:33 +00002582 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2583
Richard Smith41956372013-01-14 22:39:08 +00002584 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002585 // The initialization of each base and member constitutes a
2586 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002587 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002588 if (MemberInit.isInvalid())
2589 return true;
2590
Richard Smithc83c2302012-12-19 01:39:02 +00002591 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002592 }
2593
Chandler Carruth894aed92010-12-06 09:23:57 +00002594 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002595 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2596 InitRange.getBegin(), Init,
2597 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002598 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002599 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2600 InitRange.getBegin(), Init,
2601 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002602 }
Eli Friedman59c04372009-07-29 19:44:27 +00002603}
2604
John McCallf312b1e2010-08-26 23:41:50 +00002605MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002606Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002607 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002608 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002609 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002610 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002611 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002612 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002613
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002614 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002615 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002616 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2617 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002618 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002619 }
2620
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002621 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002622 // Initialize the object.
2623 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2624 QualType(ClassDecl->getTypeForDecl(), 0));
2625 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002626 InitList ? InitializationKind::CreateDirectList(NameLoc)
2627 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2628 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002629 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002630 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002631 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002632 if (DelegationInit.isInvalid())
2633 return true;
2634
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002635 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2636 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002637
Richard Smith41956372013-01-14 22:39:08 +00002638 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002639 // The initialization of each base and member constitutes a
2640 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002641 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2642 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002643 if (DelegationInit.isInvalid())
2644 return true;
2645
Eli Friedmand21016f2012-05-19 23:35:23 +00002646 // If we are in a dependent context, template instantiation will
2647 // perform this type-checking again. Just save the arguments that we
2648 // received in a ParenListExpr.
2649 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2650 // of the information that we have about the base
2651 // initializer. However, deconstructing the ASTs is a dicey process,
2652 // and this approach is far more likely to get the corner cases right.
2653 if (CurContext->isDependentContext())
2654 DelegationInit = Owned(Init);
2655
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002656 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002657 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002658 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002659}
2660
2661MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002662Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002663 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002664 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002665 SourceLocation BaseLoc
2666 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002667
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002668 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2669 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2670 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2671
2672 // C++ [class.base.init]p2:
2673 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002674 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002675 // of that class, the mem-initializer is ill-formed. A
2676 // mem-initializer-list can initialize a base class using any
2677 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002678 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002679
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002680 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002681 if (EllipsisLoc.isValid()) {
2682 // This is a pack expansion.
2683 if (!BaseType->containsUnexpandedParameterPack()) {
2684 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002685 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002686
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002687 EllipsisLoc = SourceLocation();
2688 }
2689 } else {
2690 // Check for any unexpanded parameter packs.
2691 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2692 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002693
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002694 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002695 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002696 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002697
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002698 // Check for direct and virtual base classes.
2699 const CXXBaseSpecifier *DirectBaseSpec = 0;
2700 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2701 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002702 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2703 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002704 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002705
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002706 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2707 VirtualBaseSpec);
2708
2709 // C++ [base.class.init]p2:
2710 // Unless the mem-initializer-id names a nonstatic data member of the
2711 // constructor's class or a direct or virtual base of that class, the
2712 // mem-initializer is ill-formed.
2713 if (!DirectBaseSpec && !VirtualBaseSpec) {
2714 // If the class has any dependent bases, then it's possible that
2715 // one of those types will resolve to the same type as
2716 // BaseType. Therefore, just treat this as a dependent base
2717 // class initialization. FIXME: Should we try to check the
2718 // initialization anyway? It seems odd.
2719 if (ClassDecl->hasAnyDependentBases())
2720 Dependent = true;
2721 else
2722 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2723 << BaseType << Context.getTypeDeclType(ClassDecl)
2724 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2725 }
2726 }
2727
2728 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002729 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002730
Sebastian Redl6df65482011-09-24 17:48:25 +00002731 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2732 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002733 InitRange.getBegin(), Init,
2734 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002735 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002736
2737 // C++ [base.class.init]p2:
2738 // If a mem-initializer-id is ambiguous because it designates both
2739 // a direct non-virtual base class and an inherited virtual base
2740 // class, the mem-initializer is ill-formed.
2741 if (DirectBaseSpec && VirtualBaseSpec)
2742 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002743 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002744
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002745 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002746 if (!BaseSpec)
2747 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2748
2749 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002750 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002751 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002752 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002753 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002754 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002755 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002756
2757 InitializedEntity BaseEntity =
2758 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2759 InitializationKind Kind =
2760 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2761 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2762 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002763 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2764 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002765 if (BaseInit.isInvalid())
2766 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002767
Richard Smith41956372013-01-14 22:39:08 +00002768 // C++11 [class.base.init]p7:
2769 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002770 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002771 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002772 if (BaseInit.isInvalid())
2773 return true;
2774
2775 // If we are in a dependent context, template instantiation will
2776 // perform this type-checking again. Just save the arguments that we
2777 // received in a ParenListExpr.
2778 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2779 // of the information that we have about the base
2780 // initializer. However, deconstructing the ASTs is a dicey process,
2781 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002782 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002783 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002784
Sean Huntcbb67482011-01-08 20:30:50 +00002785 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002786 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002787 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002788 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002789 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002790}
2791
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002792// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002793static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2794 if (T.isNull()) T = E->getType();
2795 QualType TargetType = SemaRef.BuildReferenceType(
2796 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002797 SourceLocation ExprLoc = E->getLocStart();
2798 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2799 TargetType, ExprLoc);
2800
2801 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2802 SourceRange(ExprLoc, ExprLoc),
2803 E->getSourceRange()).take();
2804}
2805
Anders Carlssone5ef7402010-04-23 03:10:23 +00002806/// ImplicitInitializerKind - How an implicit base or member initializer should
2807/// initialize its base or member.
2808enum ImplicitInitializerKind {
2809 IIK_Default,
2810 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002811 IIK_Move,
2812 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002813};
2814
Anders Carlssondefefd22010-04-23 02:00:02 +00002815static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002816BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002817 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002818 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002819 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002820 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002821 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002822 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2823 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002824
John McCall60d7b3a2010-08-24 06:29:42 +00002825 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002826
2827 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002828 case IIK_Inherit: {
2829 const CXXRecordDecl *Inherited =
2830 Constructor->getInheritedConstructor()->getParent();
2831 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2832 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2833 // C++11 [class.inhctor]p8:
2834 // Each expression in the expression-list is of the form
2835 // static_cast<T&&>(p), where p is the name of the corresponding
2836 // constructor parameter and T is the declared type of p.
2837 SmallVector<Expr*, 16> Args;
2838 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2839 ParmVarDecl *PD = Constructor->getParamDecl(I);
2840 ExprResult ArgExpr =
2841 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2842 VK_LValue, SourceLocation());
2843 if (ArgExpr.isInvalid())
2844 return true;
2845 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2846 }
2847
2848 InitializationKind InitKind = InitializationKind::CreateDirect(
2849 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002850 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002851 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2852 break;
2853 }
2854 }
2855 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002856 case IIK_Default: {
2857 InitializationKind InitKind
2858 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002859 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2860 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002861 break;
2862 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002863
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002864 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002865 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002866 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002867 ParmVarDecl *Param = Constructor->getParamDecl(0);
2868 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002869
Anders Carlssone5ef7402010-04-23 03:10:23 +00002870 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002871 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002872 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002873 Constructor->getLocation(), ParamType,
2874 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002875
Eli Friedman5f2987c2012-02-02 03:46:19 +00002876 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2877
Anders Carlssonc7957502010-04-24 22:02:54 +00002878 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002879 QualType ArgTy =
2880 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2881 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002882
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002883 if (Moving) {
2884 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2885 }
2886
John McCallf871d0c2010-08-07 06:22:56 +00002887 CXXCastPath BasePath;
2888 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002889 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2890 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002891 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002892 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002893
Anders Carlssone5ef7402010-04-23 03:10:23 +00002894 InitializationKind InitKind
2895 = InitializationKind::CreateDirect(Constructor->getLocation(),
2896 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002897 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2898 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002899 break;
2900 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002901 }
John McCall9ae2f072010-08-23 23:25:46 +00002902
Douglas Gregor53c374f2010-12-07 00:41:46 +00002903 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002904 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002905 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002906
Anders Carlssondefefd22010-04-23 02:00:02 +00002907 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002908 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002909 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2910 SourceLocation()),
2911 BaseSpec->isVirtual(),
2912 SourceLocation(),
2913 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002914 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002915 SourceLocation());
2916
Anders Carlssondefefd22010-04-23 02:00:02 +00002917 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002918}
2919
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002920static bool RefersToRValueRef(Expr *MemRef) {
2921 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2922 return Referenced->getType()->isRValueReferenceType();
2923}
2924
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002925static bool
2926BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002927 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002928 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002929 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002930 if (Field->isInvalidDecl())
2931 return true;
2932
Chandler Carruthf186b542010-06-29 23:50:44 +00002933 SourceLocation Loc = Constructor->getLocation();
2934
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002935 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2936 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002937 ParmVarDecl *Param = Constructor->getParamDecl(0);
2938 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002939
2940 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002941 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2942 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002943
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002944 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002945 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002946 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002947 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002948
Eli Friedman5f2987c2012-02-02 03:46:19 +00002949 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2950
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002951 if (Moving) {
2952 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2953 }
2954
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002955 // Build a reference to this field within the parameter.
2956 CXXScopeSpec SS;
2957 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2958 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002959 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2960 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002961 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002962 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002963 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002964 ParamType, Loc,
2965 /*IsArrow=*/false,
2966 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002967 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002968 /*FirstQualifierInScope=*/0,
2969 MemberLookup,
2970 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002971 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002972 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002973
2974 // C++11 [class.copy]p15:
2975 // - if a member m has rvalue reference type T&&, it is direct-initialized
2976 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002977 if (RefersToRValueRef(CtorArg.get())) {
2978 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002979 }
2980
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002981 // When the field we are copying is an array, create index variables for
2982 // each dimension of the array. We use these index variables to subscript
2983 // the source array, and other clients (e.g., CodeGen) will perform the
2984 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002985 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002986 QualType BaseType = Field->getType();
2987 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002988 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002989 while (const ConstantArrayType *Array
2990 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002991 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002992 // Create the iteration variable for this array index.
2993 IdentifierInfo *IterationVarName = 0;
2994 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002995 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002996 llvm::raw_svector_ostream OS(Str);
2997 OS << "__i" << IndexVariables.size();
2998 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2999 }
3000 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003001 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003002 IterationVarName, SizeType,
3003 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003004 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003005 IndexVariables.push_back(IterationVar);
3006
3007 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003008 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003009 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003010 assert(!IterationVarRef.isInvalid() &&
3011 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003012 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3013 assert(!IterationVarRef.isInvalid() &&
3014 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003015
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003016 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003017 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003018 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003019 Loc);
3020 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003021 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003022
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003023 BaseType = Array->getElementType();
3024 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003025
3026 // The array subscript expression is an lvalue, which is wrong for moving.
3027 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003028 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003029
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003030 // Construct the entity that we will be initializing. For an array, this
3031 // will be first element in the array, which may require several levels
3032 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003033 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003034 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003035 if (Indirect)
3036 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3037 else
3038 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003039 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3040 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3041 0,
3042 Entities.back()));
3043
3044 // Direct-initialize to use the copy constructor.
3045 InitializationKind InitKind =
3046 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3047
Sebastian Redl74e611a2011-09-04 18:14:28 +00003048 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003049 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003050
John McCall60d7b3a2010-08-24 06:29:42 +00003051 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003052 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003053 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003054 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003055 if (MemberInit.isInvalid())
3056 return true;
3057
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003058 if (Indirect) {
3059 assert(IndexVariables.size() == 0 &&
3060 "Indirect field improperly initialized");
3061 CXXMemberInit
3062 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3063 Loc, Loc,
3064 MemberInit.takeAs<Expr>(),
3065 Loc);
3066 } else
3067 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3068 Loc, MemberInit.takeAs<Expr>(),
3069 Loc,
3070 IndexVariables.data(),
3071 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003072 return false;
3073 }
3074
Richard Smith07b0fdc2013-03-18 21:12:30 +00003075 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3076 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003077
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003078 QualType FieldBaseElementType =
3079 SemaRef.Context.getBaseElementType(Field->getType());
3080
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003081 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003082 InitializedEntity InitEntity
3083 = Indirect? InitializedEntity::InitializeMember(Indirect)
3084 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003085 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003086 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003087
3088 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3089 ExprResult MemberInit =
3090 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003091
Douglas Gregor53c374f2010-12-07 00:41:46 +00003092 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003093 if (MemberInit.isInvalid())
3094 return true;
3095
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003096 if (Indirect)
3097 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3098 Indirect, Loc,
3099 Loc,
3100 MemberInit.get(),
3101 Loc);
3102 else
3103 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3104 Field, Loc, Loc,
3105 MemberInit.get(),
3106 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003107 return false;
3108 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003109
Sean Hunt1f2f3842011-05-17 00:19:05 +00003110 if (!Field->getParent()->isUnion()) {
3111 if (FieldBaseElementType->isReferenceType()) {
3112 SemaRef.Diag(Constructor->getLocation(),
3113 diag::err_uninitialized_member_in_ctor)
3114 << (int)Constructor->isImplicit()
3115 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3116 << 0 << Field->getDeclName();
3117 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3118 return true;
3119 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003120
Sean Hunt1f2f3842011-05-17 00:19:05 +00003121 if (FieldBaseElementType.isConstQualified()) {
3122 SemaRef.Diag(Constructor->getLocation(),
3123 diag::err_uninitialized_member_in_ctor)
3124 << (int)Constructor->isImplicit()
3125 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3126 << 1 << Field->getDeclName();
3127 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3128 return true;
3129 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003130 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003131
David Blaikie4e4d0842012-03-11 07:00:24 +00003132 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003133 FieldBaseElementType->isObjCRetainableType() &&
3134 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3135 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003136 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003137 // Default-initialize Objective-C pointers to NULL.
3138 CXXMemberInit
3139 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3140 Loc, Loc,
3141 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3142 Loc);
3143 return false;
3144 }
3145
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003146 // Nothing to initialize.
3147 CXXMemberInit = 0;
3148 return false;
3149}
John McCallf1860e52010-05-20 23:23:51 +00003150
3151namespace {
3152struct BaseAndFieldInfo {
3153 Sema &S;
3154 CXXConstructorDecl *Ctor;
3155 bool AnyErrorsInInits;
3156 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003157 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003158 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003159
3160 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3161 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003162 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3163 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003164 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003165 else if (Generated && Ctor->isMoveConstructor())
3166 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003167 else if (Ctor->getInheritedConstructor())
3168 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003169 else
3170 IIK = IIK_Default;
3171 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003172
3173 bool isImplicitCopyOrMove() const {
3174 switch (IIK) {
3175 case IIK_Copy:
3176 case IIK_Move:
3177 return true;
3178
3179 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003180 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003181 return false;
3182 }
David Blaikie30263482012-01-20 21:50:17 +00003183
3184 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003185 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003186
3187 bool addFieldInitializer(CXXCtorInitializer *Init) {
3188 AllToInit.push_back(Init);
3189
3190 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003191 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003192 S.UnusedPrivateFields.remove(Init->getAnyMember());
3193
3194 return false;
3195 }
John McCallf1860e52010-05-20 23:23:51 +00003196};
3197}
3198
Richard Smitha4950662011-09-19 13:34:43 +00003199/// \brief Determine whether the given indirect field declaration is somewhere
3200/// within an anonymous union.
3201static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3202 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3203 CEnd = F->chain_end();
3204 C != CEnd; ++C)
3205 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3206 if (Record->isUnion())
3207 return true;
3208
3209 return false;
3210}
3211
Douglas Gregorddb21472011-11-02 23:04:16 +00003212/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3213/// array type.
3214static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3215 if (T->isIncompleteArrayType())
3216 return true;
3217
3218 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3219 if (!ArrayT->getSize())
3220 return true;
3221
3222 T = ArrayT->getElementType();
3223 }
3224
3225 return false;
3226}
3227
Richard Smith7a614d82011-06-11 17:19:42 +00003228static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003229 FieldDecl *Field,
3230 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003231
Chandler Carruthe861c602010-06-30 02:59:29 +00003232 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003233 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3234 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003235
Richard Smith0b8220a2012-08-07 21:30:42 +00003236 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003237 // has a brace-or-equal-initializer, the entity is initialized as specified
3238 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003239 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003240 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3241 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003242 CXXCtorInitializer *Init;
3243 if (Indirect)
3244 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3245 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003246 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003247 SourceLocation());
3248 else
3249 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3250 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003251 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003252 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003253 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003254 }
3255
Richard Smithc115f632011-09-18 11:14:50 +00003256 // Don't build an implicit initializer for union members if none was
3257 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003258 if (Field->getParent()->isUnion() ||
3259 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003260 return false;
3261
Douglas Gregorddb21472011-11-02 23:04:16 +00003262 // Don't initialize incomplete or zero-length arrays.
3263 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3264 return false;
3265
John McCallf1860e52010-05-20 23:23:51 +00003266 // Don't try to build an implicit initializer if there were semantic
3267 // errors in any of the initializers (and therefore we might be
3268 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003269 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003270 return false;
3271
Sean Huntcbb67482011-01-08 20:30:50 +00003272 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003273 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3274 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003275 return true;
John McCallf1860e52010-05-20 23:23:51 +00003276
Richard Smith0b8220a2012-08-07 21:30:42 +00003277 if (!Init)
3278 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003279
Richard Smith0b8220a2012-08-07 21:30:42 +00003280 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003281}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003282
3283bool
3284Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3285 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003286 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003287 Constructor->setNumCtorInitializers(1);
3288 CXXCtorInitializer **initializer =
3289 new (Context) CXXCtorInitializer*[1];
3290 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3291 Constructor->setCtorInitializers(initializer);
3292
Sean Huntb76af9c2011-05-03 23:05:34 +00003293 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003294 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003295 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3296 }
3297
Sean Huntc1598702011-05-05 00:05:47 +00003298 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003299
Sean Hunt059ce0d2011-05-01 07:04:31 +00003300 return false;
3301}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003302
David Blaikie93c86172013-01-17 05:26:25 +00003303bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3304 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003305 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003306 // Just store the initializers as written, they will be checked during
3307 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003308 if (!Initializers.empty()) {
3309 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003310 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003311 new (Context) CXXCtorInitializer*[Initializers.size()];
3312 memcpy(baseOrMemberInitializers, Initializers.data(),
3313 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003314 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003315 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003316
3317 // Let template instantiation know whether we had errors.
3318 if (AnyErrors)
3319 Constructor->setInvalidDecl();
3320
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003321 return false;
3322 }
3323
John McCallf1860e52010-05-20 23:23:51 +00003324 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003325
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003326 // We need to build the initializer AST according to order of construction
3327 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003328 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003329 if (!ClassDecl)
3330 return true;
3331
Eli Friedman80c30da2009-11-09 19:20:36 +00003332 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003333
David Blaikie93c86172013-01-17 05:26:25 +00003334 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003335 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003336
3337 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003338 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003339 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003340 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003341 }
3342
Anders Carlsson711f34a2010-04-21 19:52:01 +00003343 // Keep track of the direct virtual bases.
3344 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3345 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3346 E = ClassDecl->bases_end(); I != E; ++I) {
3347 if (I->isVirtual())
3348 DirectVBases.insert(I);
3349 }
3350
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003351 // Push virtual bases before others.
3352 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3353 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3354
Sean Huntcbb67482011-01-08 20:30:50 +00003355 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003356 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3357 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003358 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003359 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003360 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003361 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003362 VBase, IsInheritedVirtualBase,
3363 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003364 HadError = true;
3365 continue;
3366 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003367
John McCallf1860e52010-05-20 23:23:51 +00003368 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003369 }
3370 }
Mike Stump1eb44332009-09-09 15:08:12 +00003371
John McCallf1860e52010-05-20 23:23:51 +00003372 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003373 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3374 E = ClassDecl->bases_end(); Base != E; ++Base) {
3375 // Virtuals are in the virtual base list and already constructed.
3376 if (Base->isVirtual())
3377 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003378
Sean Huntcbb67482011-01-08 20:30:50 +00003379 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003380 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3381 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003382 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003383 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003384 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003385 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003386 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003387 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003388 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003389 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003390
John McCallf1860e52010-05-20 23:23:51 +00003391 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003392 }
3393 }
Mike Stump1eb44332009-09-09 15:08:12 +00003394
John McCallf1860e52010-05-20 23:23:51 +00003395 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003396 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3397 MemEnd = ClassDecl->decls_end();
3398 Mem != MemEnd; ++Mem) {
3399 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003400 // C++ [class.bit]p2:
3401 // A declaration for a bit-field that omits the identifier declares an
3402 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3403 // initialized.
3404 if (F->isUnnamedBitfield())
3405 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003406
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003407 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003408 // handle anonymous struct/union fields based on their individual
3409 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003410 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003411 continue;
3412
3413 if (CollectFieldInitializer(*this, Info, F))
3414 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003415 continue;
3416 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003417
3418 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003419 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003420 continue;
3421
3422 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3423 if (F->getType()->isIncompleteArrayType()) {
3424 assert(ClassDecl->hasFlexibleArrayMember() &&
3425 "Incomplete array type is not valid");
3426 continue;
3427 }
3428
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003429 // Initialize each field of an anonymous struct individually.
3430 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3431 HadError = true;
3432
3433 continue;
3434 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003435 }
Mike Stump1eb44332009-09-09 15:08:12 +00003436
David Blaikie93c86172013-01-17 05:26:25 +00003437 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003438 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003439 Constructor->setNumCtorInitializers(NumInitializers);
3440 CXXCtorInitializer **baseOrMemberInitializers =
3441 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003442 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003443 NumInitializers * sizeof(CXXCtorInitializer*));
3444 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003445
John McCallef027fe2010-03-16 21:39:52 +00003446 // Constructors implicitly reference the base and member
3447 // destructors.
3448 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3449 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003450 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003451
3452 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003453}
3454
David Blaikieee000bb2013-01-17 08:49:22 +00003455static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003456 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003457 const RecordDecl *RD = RT->getDecl();
3458 if (RD->isAnonymousStructOrUnion()) {
3459 for (RecordDecl::field_iterator Field = RD->field_begin(),
3460 E = RD->field_end(); Field != E; ++Field)
3461 PopulateKeysForFields(*Field, IdealInits);
3462 return;
3463 }
Eli Friedman6347f422009-07-21 19:28:10 +00003464 }
David Blaikieee000bb2013-01-17 08:49:22 +00003465 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003466}
3467
Anders Carlssonea356fb2010-04-02 05:42:15 +00003468static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003469 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003470}
3471
Anders Carlssonea356fb2010-04-02 05:42:15 +00003472static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003473 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003474 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003475 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003476
David Blaikieee000bb2013-01-17 08:49:22 +00003477 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003478}
3479
David Blaikie93c86172013-01-17 05:26:25 +00003480static void DiagnoseBaseOrMemInitializerOrder(
3481 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3482 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003483 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003484 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003485
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003486 // Don't check initializers order unless the warning is enabled at the
3487 // location of at least one initializer.
3488 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003489 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003490 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003491 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3492 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003493 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003494 ShouldCheckOrder = true;
3495 break;
3496 }
3497 }
3498 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003499 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003500
John McCalld6ca8da2010-04-10 07:37:23 +00003501 // Build the list of bases and members in the order that they'll
3502 // actually be initialized. The explicit initializers should be in
3503 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003504 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Anders Carlsson071d6102010-04-02 03:38:04 +00003506 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3507
John McCalld6ca8da2010-04-10 07:37:23 +00003508 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003509 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003510 ClassDecl->vbases_begin(),
3511 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003512 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003513
John McCalld6ca8da2010-04-10 07:37:23 +00003514 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003515 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003516 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003517 if (Base->isVirtual())
3518 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003519 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003520 }
Mike Stump1eb44332009-09-09 15:08:12 +00003521
John McCalld6ca8da2010-04-10 07:37:23 +00003522 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003523 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003524 E = ClassDecl->field_end(); Field != E; ++Field) {
3525 if (Field->isUnnamedBitfield())
3526 continue;
3527
David Blaikieee000bb2013-01-17 08:49:22 +00003528 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003529 }
3530
John McCalld6ca8da2010-04-10 07:37:23 +00003531 unsigned NumIdealInits = IdealInitKeys.size();
3532 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003533
Sean Huntcbb67482011-01-08 20:30:50 +00003534 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003535 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003536 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003537 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003538
3539 // Scan forward to try to find this initializer in the idealized
3540 // initializers list.
3541 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3542 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003543 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003544
3545 // If we didn't find this initializer, it must be because we
3546 // scanned past it on a previous iteration. That can only
3547 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003548 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003549 Sema::SemaDiagnosticBuilder D =
3550 SemaRef.Diag(PrevInit->getSourceLocation(),
3551 diag::warn_initializer_out_of_order);
3552
Francois Pichet00eb3f92010-12-04 09:14:42 +00003553 if (PrevInit->isAnyMemberInitializer())
3554 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003555 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003556 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003557
Francois Pichet00eb3f92010-12-04 09:14:42 +00003558 if (Init->isAnyMemberInitializer())
3559 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003560 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003561 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003562
3563 // Move back to the initializer's location in the ideal list.
3564 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3565 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003566 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003567
3568 assert(IdealIndex != NumIdealInits &&
3569 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003570 }
John McCalld6ca8da2010-04-10 07:37:23 +00003571
3572 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003573 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003574}
3575
John McCall3c3ccdb2010-04-10 09:28:51 +00003576namespace {
3577bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003578 CXXCtorInitializer *Init,
3579 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003580 if (!PrevInit) {
3581 PrevInit = Init;
3582 return false;
3583 }
3584
Douglas Gregordc392c12013-03-25 23:28:23 +00003585 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003586 S.Diag(Init->getSourceLocation(),
3587 diag::err_multiple_mem_initialization)
3588 << Field->getDeclName()
3589 << Init->getSourceRange();
3590 else {
John McCallf4c73712011-01-19 06:33:43 +00003591 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003592 assert(BaseClass && "neither field nor base");
3593 S.Diag(Init->getSourceLocation(),
3594 diag::err_multiple_base_initialization)
3595 << QualType(BaseClass, 0)
3596 << Init->getSourceRange();
3597 }
3598 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3599 << 0 << PrevInit->getSourceRange();
3600
3601 return true;
3602}
3603
Sean Huntcbb67482011-01-08 20:30:50 +00003604typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003605typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3606
3607bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003608 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003609 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003610 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003611 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003612 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003613
3614 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003615 if (Parent->isUnion()) {
3616 UnionEntry &En = Unions[Parent];
3617 if (En.first && En.first != Child) {
3618 S.Diag(Init->getSourceLocation(),
3619 diag::err_multiple_mem_union_initialization)
3620 << Field->getDeclName()
3621 << Init->getSourceRange();
3622 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3623 << 0 << En.second->getSourceRange();
3624 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003625 }
3626 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003627 En.first = Child;
3628 En.second = Init;
3629 }
David Blaikie6fe29652011-11-17 06:01:57 +00003630 if (!Parent->isAnonymousStructOrUnion())
3631 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003632 }
3633
3634 Child = Parent;
3635 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003636 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003637
3638 return false;
3639}
3640}
3641
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003642/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003643void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003644 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003645 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003646 bool AnyErrors) {
3647 if (!ConstructorDecl)
3648 return;
3649
3650 AdjustDeclIfTemplate(ConstructorDecl);
3651
3652 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003653 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003654
3655 if (!Constructor) {
3656 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3657 return;
3658 }
3659
John McCall3c3ccdb2010-04-10 09:28:51 +00003660 // Mapping for the duplicate initializers check.
3661 // For member initializers, this is keyed with a FieldDecl*.
3662 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003663 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003664
3665 // Mapping for the inconsistent anonymous-union initializers check.
3666 RedundantUnionMap MemberUnions;
3667
Anders Carlssonea356fb2010-04-02 05:42:15 +00003668 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003669 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003670 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003671
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003672 // Set the source order index.
3673 Init->setSourceOrder(i);
3674
Francois Pichet00eb3f92010-12-04 09:14:42 +00003675 if (Init->isAnyMemberInitializer()) {
3676 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003677 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3678 CheckRedundantUnionInit(*this, Init, MemberUnions))
3679 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003680 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003681 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3682 if (CheckRedundantInit(*this, Init, Members[Key]))
3683 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003684 } else {
3685 assert(Init->isDelegatingInitializer());
3686 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003687 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003688 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003689 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003690 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003691 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003692 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003693 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003694 // Return immediately as the initializer is set.
3695 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003696 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003697 }
3698
Anders Carlssonea356fb2010-04-02 05:42:15 +00003699 if (HadError)
3700 return;
3701
David Blaikie93c86172013-01-17 05:26:25 +00003702 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003703
David Blaikie93c86172013-01-17 05:26:25 +00003704 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003705}
3706
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003707void
John McCallef027fe2010-03-16 21:39:52 +00003708Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3709 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003710 // Ignore dependent contexts. Also ignore unions, since their members never
3711 // have destructors implicitly called.
3712 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003713 return;
John McCall58e6f342010-03-16 05:22:47 +00003714
3715 // FIXME: all the access-control diagnostics are positioned on the
3716 // field/base declaration. That's probably good; that said, the
3717 // user might reasonably want to know why the destructor is being
3718 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003719
Anders Carlsson9f853df2009-11-17 04:44:12 +00003720 // Non-static data members.
3721 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3722 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003723 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003724 if (Field->isInvalidDecl())
3725 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003726
3727 // Don't destroy incomplete or zero-length arrays.
3728 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3729 continue;
3730
Anders Carlsson9f853df2009-11-17 04:44:12 +00003731 QualType FieldType = Context.getBaseElementType(Field->getType());
3732
3733 const RecordType* RT = FieldType->getAs<RecordType>();
3734 if (!RT)
3735 continue;
3736
3737 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003738 if (FieldClassDecl->isInvalidDecl())
3739 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003740 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003741 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003742 // The destructor for an implicit anonymous union member is never invoked.
3743 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3744 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003745
Douglas Gregordb89f282010-07-01 22:47:18 +00003746 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003747 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003748 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003749 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003750 << Field->getDeclName()
3751 << FieldType);
3752
Eli Friedman5f2987c2012-02-02 03:46:19 +00003753 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003754 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003755 }
3756
John McCall58e6f342010-03-16 05:22:47 +00003757 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3758
Anders Carlsson9f853df2009-11-17 04:44:12 +00003759 // Bases.
3760 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3761 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003762 // Bases are always records in a well-formed non-dependent class.
3763 const RecordType *RT = Base->getType()->getAs<RecordType>();
3764
3765 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003766 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003767 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003768
John McCall58e6f342010-03-16 05:22:47 +00003769 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003770 // If our base class is invalid, we probably can't get its dtor anyway.
3771 if (BaseClassDecl->isInvalidDecl())
3772 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003773 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003774 continue;
John McCall58e6f342010-03-16 05:22:47 +00003775
Douglas Gregordb89f282010-07-01 22:47:18 +00003776 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003777 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003778
3779 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003780 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003781 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003782 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003783 << Base->getSourceRange(),
3784 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003785
Eli Friedman5f2987c2012-02-02 03:46:19 +00003786 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003787 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003788 }
3789
3790 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003791 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3792 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003793
3794 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003795 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003796
3797 // Ignore direct virtual bases.
3798 if (DirectVirtualBases.count(RT))
3799 continue;
3800
John McCall58e6f342010-03-16 05:22:47 +00003801 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003802 // If our base class is invalid, we probably can't get its dtor anyway.
3803 if (BaseClassDecl->isInvalidDecl())
3804 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003805 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003806 continue;
John McCall58e6f342010-03-16 05:22:47 +00003807
Douglas Gregordb89f282010-07-01 22:47:18 +00003808 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003809 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer585bee42013-06-06 23:43:20 +00003810 if (CheckDestructorAccess(
3811 ClassDecl->getLocation(), Dtor,
3812 PDiag(diag::err_access_dtor_vbase)
3813 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3814 Context.getTypeDeclType(ClassDecl)) ==
3815 AR_accessible) {
3816 CheckDerivedToBaseConversion(
3817 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3818 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3819 SourceRange(), DeclarationName(), 0);
3820 }
John McCall58e6f342010-03-16 05:22:47 +00003821
Eli Friedman5f2987c2012-02-02 03:46:19 +00003822 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003823 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003824 }
3825}
3826
John McCalld226f652010-08-21 09:40:31 +00003827void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003828 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003829 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003830
Mike Stump1eb44332009-09-09 15:08:12 +00003831 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003832 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003833 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003834}
3835
Mike Stump1eb44332009-09-09 15:08:12 +00003836bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003837 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003838 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3839 unsigned DiagID;
3840 AbstractDiagSelID SelID;
3841
3842 public:
3843 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3844 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3845
3846 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003847 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003848 if (SelID == -1)
3849 S.Diag(Loc, DiagID) << T;
3850 else
3851 S.Diag(Loc, DiagID) << SelID << T;
3852 }
3853 } Diagnoser(DiagID, SelID);
3854
3855 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003856}
3857
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003858bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003859 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003860 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003861 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003862
Anders Carlsson11f21a02009-03-23 19:10:31 +00003863 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003864 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003865
Ted Kremenek6217b802009-07-29 21:53:49 +00003866 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003867 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003868 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003869 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003870
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003871 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003872 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003873 }
Mike Stump1eb44332009-09-09 15:08:12 +00003874
Ted Kremenek6217b802009-07-29 21:53:49 +00003875 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003876 if (!RT)
3877 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003878
John McCall86ff3082010-02-04 22:26:26 +00003879 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003880
John McCall94c3b562010-08-18 09:41:07 +00003881 // We can't answer whether something is abstract until it has a
3882 // definition. If it's currently being defined, we'll walk back
3883 // over all the declarations when we have a full definition.
3884 const CXXRecordDecl *Def = RD->getDefinition();
3885 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003886 return false;
3887
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003888 if (!RD->isAbstract())
3889 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003891 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003892 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003893
John McCall94c3b562010-08-18 09:41:07 +00003894 return true;
3895}
3896
3897void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3898 // Check if we've already emitted the list of pure virtual functions
3899 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003900 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003901 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003902
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003903 CXXFinalOverriderMap FinalOverriders;
3904 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003905
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003906 // Keep a set of seen pure methods so we won't diagnose the same method
3907 // more than once.
3908 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3909
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003910 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3911 MEnd = FinalOverriders.end();
3912 M != MEnd;
3913 ++M) {
3914 for (OverridingMethods::iterator SO = M->second.begin(),
3915 SOEnd = M->second.end();
3916 SO != SOEnd; ++SO) {
3917 // C++ [class.abstract]p4:
3918 // A class is abstract if it contains or inherits at least one
3919 // pure virtual function for which the final overrider is pure
3920 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003921
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003922 //
3923 if (SO->second.size() != 1)
3924 continue;
3925
3926 if (!SO->second.front().Method->isPure())
3927 continue;
3928
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003929 if (!SeenPureMethods.insert(SO->second.front().Method))
3930 continue;
3931
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003932 Diag(SO->second.front().Method->getLocation(),
3933 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003934 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003935 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003936 }
3937
3938 if (!PureVirtualClassDiagSet)
3939 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3940 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003941}
3942
Anders Carlsson8211eff2009-03-24 01:19:16 +00003943namespace {
John McCall94c3b562010-08-18 09:41:07 +00003944struct AbstractUsageInfo {
3945 Sema &S;
3946 CXXRecordDecl *Record;
3947 CanQualType AbstractType;
3948 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003949
John McCall94c3b562010-08-18 09:41:07 +00003950 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3951 : S(S), Record(Record),
3952 AbstractType(S.Context.getCanonicalType(
3953 S.Context.getTypeDeclType(Record))),
3954 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003955
John McCall94c3b562010-08-18 09:41:07 +00003956 void DiagnoseAbstractType() {
3957 if (Invalid) return;
3958 S.DiagnoseAbstractType(Record);
3959 Invalid = true;
3960 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003961
John McCall94c3b562010-08-18 09:41:07 +00003962 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3963};
3964
3965struct CheckAbstractUsage {
3966 AbstractUsageInfo &Info;
3967 const NamedDecl *Ctx;
3968
3969 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3970 : Info(Info), Ctx(Ctx) {}
3971
3972 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3973 switch (TL.getTypeLocClass()) {
3974#define ABSTRACT_TYPELOC(CLASS, PARENT)
3975#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003976 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003977#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003978 }
John McCall94c3b562010-08-18 09:41:07 +00003979 }
Mike Stump1eb44332009-09-09 15:08:12 +00003980
John McCall94c3b562010-08-18 09:41:07 +00003981 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3982 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3983 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003984 if (!TL.getArg(I))
3985 continue;
3986
John McCall94c3b562010-08-18 09:41:07 +00003987 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3988 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003989 }
John McCall94c3b562010-08-18 09:41:07 +00003990 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003991
John McCall94c3b562010-08-18 09:41:07 +00003992 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3993 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3994 }
Mike Stump1eb44332009-09-09 15:08:12 +00003995
John McCall94c3b562010-08-18 09:41:07 +00003996 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3997 // Visit the type parameters from a permissive context.
3998 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3999 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4000 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4001 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4002 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4003 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004004 }
John McCall94c3b562010-08-18 09:41:07 +00004005 }
Mike Stump1eb44332009-09-09 15:08:12 +00004006
John McCall94c3b562010-08-18 09:41:07 +00004007 // Visit pointee types from a permissive context.
4008#define CheckPolymorphic(Type) \
4009 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4010 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4011 }
4012 CheckPolymorphic(PointerTypeLoc)
4013 CheckPolymorphic(ReferenceTypeLoc)
4014 CheckPolymorphic(MemberPointerTypeLoc)
4015 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004016 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004017
John McCall94c3b562010-08-18 09:41:07 +00004018 /// Handle all the types we haven't given a more specific
4019 /// implementation for above.
4020 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4021 // Every other kind of type that we haven't called out already
4022 // that has an inner type is either (1) sugar or (2) contains that
4023 // inner type in some way as a subobject.
4024 if (TypeLoc Next = TL.getNextTypeLoc())
4025 return Visit(Next, Sel);
4026
4027 // If there's no inner type and we're in a permissive context,
4028 // don't diagnose.
4029 if (Sel == Sema::AbstractNone) return;
4030
4031 // Check whether the type matches the abstract type.
4032 QualType T = TL.getType();
4033 if (T->isArrayType()) {
4034 Sel = Sema::AbstractArrayType;
4035 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004036 }
John McCall94c3b562010-08-18 09:41:07 +00004037 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4038 if (CT != Info.AbstractType) return;
4039
4040 // It matched; do some magic.
4041 if (Sel == Sema::AbstractArrayType) {
4042 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4043 << T << TL.getSourceRange();
4044 } else {
4045 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4046 << Sel << T << TL.getSourceRange();
4047 }
4048 Info.DiagnoseAbstractType();
4049 }
4050};
4051
4052void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4053 Sema::AbstractDiagSelID Sel) {
4054 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4055}
4056
4057}
4058
4059/// Check for invalid uses of an abstract type in a method declaration.
4060static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4061 CXXMethodDecl *MD) {
4062 // No need to do the check on definitions, which require that
4063 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004064 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004065 return;
4066
4067 // For safety's sake, just ignore it if we don't have type source
4068 // information. This should never happen for non-implicit methods,
4069 // but...
4070 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4071 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4072}
4073
4074/// Check for invalid uses of an abstract type within a class definition.
4075static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4076 CXXRecordDecl *RD) {
4077 for (CXXRecordDecl::decl_iterator
4078 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4079 Decl *D = *I;
4080 if (D->isImplicit()) continue;
4081
4082 // Methods and method templates.
4083 if (isa<CXXMethodDecl>(D)) {
4084 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4085 } else if (isa<FunctionTemplateDecl>(D)) {
4086 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4087 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4088
4089 // Fields and static variables.
4090 } else if (isa<FieldDecl>(D)) {
4091 FieldDecl *FD = cast<FieldDecl>(D);
4092 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4093 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4094 } else if (isa<VarDecl>(D)) {
4095 VarDecl *VD = cast<VarDecl>(D);
4096 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4097 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4098
4099 // Nested classes and class templates.
4100 } else if (isa<CXXRecordDecl>(D)) {
4101 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4102 } else if (isa<ClassTemplateDecl>(D)) {
4103 CheckAbstractClassUsage(Info,
4104 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4105 }
4106 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004107}
4108
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004109/// \brief Perform semantic checks on a class definition that has been
4110/// completing, introducing implicitly-declared members, checking for
4111/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004112void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004113 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004114 return;
4115
John McCall94c3b562010-08-18 09:41:07 +00004116 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4117 AbstractUsageInfo Info(*this, Record);
4118 CheckAbstractClassUsage(Info, Record);
4119 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004120
4121 // If this is not an aggregate type and has no user-declared constructor,
4122 // complain about any non-static data members of reference or const scalar
4123 // type, since they will never get initializers.
4124 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004125 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4126 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004127 bool Complained = false;
4128 for (RecordDecl::field_iterator F = Record->field_begin(),
4129 FEnd = Record->field_end();
4130 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004131 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004132 continue;
4133
Douglas Gregor325e5932010-04-15 00:00:53 +00004134 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004135 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004136 if (!Complained) {
4137 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4138 << Record->getTagKind() << Record;
4139 Complained = true;
4140 }
4141
4142 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4143 << F->getType()->isReferenceType()
4144 << F->getDeclName();
4145 }
4146 }
4147 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004148
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004149 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004150 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004151
4152 if (Record->getIdentifier()) {
4153 // C++ [class.mem]p13:
4154 // If T is the name of a class, then each of the following shall have a
4155 // name different from T:
4156 // - every member of every anonymous union that is a member of class T.
4157 //
4158 // C++ [class.mem]p14:
4159 // In addition, if class T has a user-declared constructor (12.1), every
4160 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004161 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4162 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4163 ++I) {
4164 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004165 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4166 isa<IndirectFieldDecl>(D)) {
4167 Diag(D->getLocation(), diag::err_member_name_of_class)
4168 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004169 break;
4170 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004171 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004172 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004173
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004174 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004175 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004176 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004177 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004178 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4179 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4180 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004181
David Blaikieb6b5b972012-09-21 03:21:07 +00004182 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4183 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4184 DiagnoseAbstractType(Record);
4185 }
4186
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004187 if (!Record->isDependentType()) {
4188 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4189 MEnd = Record->method_end();
4190 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004191 // See if a method overloads virtual methods in a base
4192 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004193 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004194 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004195
4196 // Check whether the explicitly-defaulted special members are valid.
4197 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4198 CheckExplicitlyDefaultedSpecialMember(*M);
4199
4200 // For an explicitly defaulted or deleted special member, we defer
4201 // determining triviality until the class is complete. That time is now!
4202 if (!M->isImplicit() && !M->isUserProvided()) {
4203 CXXSpecialMember CSM = getSpecialMember(*M);
4204 if (CSM != CXXInvalid) {
4205 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4206
4207 // Inform the class that we've finished declaring this member.
4208 Record->finishedDefaultedOrDeletedMember(*M);
4209 }
4210 }
4211 }
4212 }
4213
4214 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4215 // function that is not a constructor declares that member function to be
4216 // const. [...] The class of which that function is a member shall be
4217 // a literal type.
4218 //
4219 // If the class has virtual bases, any constexpr members will already have
4220 // been diagnosed by the checks performed on the member declaration, so
4221 // suppress this (less useful) diagnostic.
4222 //
4223 // We delay this until we know whether an explicitly-defaulted (or deleted)
4224 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004225 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004226 !Record->isLiteral() && !Record->getNumVBases()) {
4227 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4228 MEnd = Record->method_end();
4229 M != MEnd; ++M) {
4230 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4231 switch (Record->getTemplateSpecializationKind()) {
4232 case TSK_ImplicitInstantiation:
4233 case TSK_ExplicitInstantiationDeclaration:
4234 case TSK_ExplicitInstantiationDefinition:
4235 // If a template instantiates to a non-literal type, but its members
4236 // instantiate to constexpr functions, the template is technically
4237 // ill-formed, but we allow it for sanity.
4238 continue;
4239
4240 case TSK_Undeclared:
4241 case TSK_ExplicitSpecialization:
4242 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4243 diag::err_constexpr_method_non_literal);
4244 break;
4245 }
4246
4247 // Only produce one error per class.
4248 break;
4249 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004250 }
4251 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004252
Richard Smith07b0fdc2013-03-18 21:12:30 +00004253 // Declare inheriting constructors. We do this eagerly here because:
4254 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004255 // constructors from different classes.
4256 // - The lazy declaration of the other implicit constructors is so as to not
4257 // waste space and performance on classes that are not meant to be
4258 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004259 // have inheriting constructors.
4260 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004261}
4262
Richard Smith7756afa2012-06-10 05:43:50 +00004263/// Is the special member function which would be selected to perform the
4264/// specified operation on the specified class type a constexpr constructor?
4265static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4266 Sema::CXXSpecialMember CSM,
4267 bool ConstArg) {
4268 Sema::SpecialMemberOverloadResult *SMOR =
4269 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4270 false, false, false, false);
4271 if (!SMOR || !SMOR->getMethod())
4272 // A constructor we wouldn't select can't be "involved in initializing"
4273 // anything.
4274 return true;
4275 return SMOR->getMethod()->isConstexpr();
4276}
4277
4278/// Determine whether the specified special member function would be constexpr
4279/// if it were implicitly defined.
4280static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4281 Sema::CXXSpecialMember CSM,
4282 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004283 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004284 return false;
4285
4286 // C++11 [dcl.constexpr]p4:
4287 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004288 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004289 switch (CSM) {
4290 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004291 // Since default constructor lookup is essentially trivial (and cannot
4292 // involve, for instance, template instantiation), we compute whether a
4293 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4294 //
4295 // This is important for performance; we need to know whether the default
4296 // constructor is constexpr to determine whether the type is a literal type.
4297 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4298
Richard Smith7756afa2012-06-10 05:43:50 +00004299 case Sema::CXXCopyConstructor:
4300 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004301 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004302 break;
4303
4304 case Sema::CXXCopyAssignment:
4305 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004306 if (!S.getLangOpts().CPlusPlus1y)
4307 return false;
4308 // In C++1y, we need to perform overload resolution.
4309 Ctor = false;
4310 break;
4311
Richard Smith7756afa2012-06-10 05:43:50 +00004312 case Sema::CXXDestructor:
4313 case Sema::CXXInvalid:
4314 return false;
4315 }
4316
4317 // -- if the class is a non-empty union, or for each non-empty anonymous
4318 // union member of a non-union class, exactly one non-static data member
4319 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004320 //
4321 // If we squint, this is guaranteed, since exactly one non-static data member
4322 // will be initialized (if the constructor isn't deleted), we just don't know
4323 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004324 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004325 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004326
4327 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004328 if (Ctor && ClassDecl->getNumVBases())
4329 return false;
4330
4331 // C++1y [class.copy]p26:
4332 // -- [the class] is a literal type, and
4333 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004334 return false;
4335
4336 // -- every constructor involved in initializing [...] base class
4337 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004338 // -- the assignment operator selected to copy/move each direct base
4339 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004340 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4341 BEnd = ClassDecl->bases_end();
4342 B != BEnd; ++B) {
4343 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4344 if (!BaseType) continue;
4345
4346 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4347 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4348 return false;
4349 }
4350
4351 // -- every constructor involved in initializing non-static data members
4352 // [...] shall be a constexpr constructor;
4353 // -- every non-static data member and base class sub-object shall be
4354 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004355 // -- for each non-stastic data member of X that is of class type (or array
4356 // thereof), the assignment operator selected to copy/move that member is
4357 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004358 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4359 FEnd = ClassDecl->field_end();
4360 F != FEnd; ++F) {
4361 if (F->isInvalidDecl())
4362 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004363 if (const RecordType *RecordTy =
4364 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004365 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4366 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4367 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004368 }
4369 }
4370
4371 // All OK, it's constexpr!
4372 return true;
4373}
4374
Richard Smithb9d0b762012-07-27 04:22:15 +00004375static Sema::ImplicitExceptionSpecification
4376computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4377 switch (S.getSpecialMember(MD)) {
4378 case Sema::CXXDefaultConstructor:
4379 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4380 case Sema::CXXCopyConstructor:
4381 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4382 case Sema::CXXCopyAssignment:
4383 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4384 case Sema::CXXMoveConstructor:
4385 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4386 case Sema::CXXMoveAssignment:
4387 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4388 case Sema::CXXDestructor:
4389 return S.ComputeDefaultedDtorExceptionSpec(MD);
4390 case Sema::CXXInvalid:
4391 break;
4392 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004393 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4394 "only special members have implicit exception specs");
4395 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004396}
4397
Richard Smithdd25e802012-07-30 23:48:14 +00004398static void
4399updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4400 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4401 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4402 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004403 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4404 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004405}
4406
Richard Smithb9d0b762012-07-27 04:22:15 +00004407void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4408 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4409 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4410 return;
4411
Richard Smithdd25e802012-07-30 23:48:14 +00004412 // Evaluate the exception specification.
4413 ImplicitExceptionSpecification ExceptSpec =
4414 computeImplicitExceptionSpec(*this, Loc, MD);
4415
4416 // Update the type of the special member to use it.
4417 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4418
4419 // A user-provided destructor can be defined outside the class. When that
4420 // happens, be sure to update the exception specification on both
4421 // declarations.
4422 const FunctionProtoType *CanonicalFPT =
4423 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4424 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4425 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4426 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004427}
4428
Richard Smith3003e1d2012-05-15 04:39:51 +00004429void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4430 CXXRecordDecl *RD = MD->getParent();
4431 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004432
Richard Smith3003e1d2012-05-15 04:39:51 +00004433 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4434 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004435
4436 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004437 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004438 bool First = MD == MD->getCanonicalDecl();
4439
4440 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004441
4442 // C++11 [dcl.fct.def.default]p1:
4443 // A function that is explicitly defaulted shall
4444 // -- be a special member function (checked elsewhere),
4445 // -- have the same type (except for ref-qualifiers, and except that a
4446 // copy operation can take a non-const reference) as an implicit
4447 // declaration, and
4448 // -- not have default arguments.
4449 unsigned ExpectedParams = 1;
4450 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4451 ExpectedParams = 0;
4452 if (MD->getNumParams() != ExpectedParams) {
4453 // This also checks for default arguments: a copy or move constructor with a
4454 // default argument is classified as a default constructor, and assignment
4455 // operations and destructors can't have default arguments.
4456 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4457 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004458 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004459 } else if (MD->isVariadic()) {
4460 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4461 << CSM << MD->getSourceRange();
4462 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004463 }
4464
Richard Smith3003e1d2012-05-15 04:39:51 +00004465 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004466
Richard Smith7756afa2012-06-10 05:43:50 +00004467 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004468 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004469 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004470 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004471 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004472
Richard Smith3003e1d2012-05-15 04:39:51 +00004473 QualType ReturnType = Context.VoidTy;
4474 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4475 // Check for return type matching.
4476 ReturnType = Type->getResultType();
4477 QualType ExpectedReturnType =
4478 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4479 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4480 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4481 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4482 HadError = true;
4483 }
4484
4485 // A defaulted special member cannot have cv-qualifiers.
4486 if (Type->getTypeQuals()) {
4487 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004488 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004489 HadError = true;
4490 }
4491 }
4492
4493 // Check for parameter type matching.
4494 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004495 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004496 if (ExpectedParams && ArgType->isReferenceType()) {
4497 // Argument must be reference to possibly-const T.
4498 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004499 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004500
4501 if (ReferentType.isVolatileQualified()) {
4502 Diag(MD->getLocation(),
4503 diag::err_defaulted_special_member_volatile_param) << CSM;
4504 HadError = true;
4505 }
4506
Richard Smith7756afa2012-06-10 05:43:50 +00004507 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004508 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4509 Diag(MD->getLocation(),
4510 diag::err_defaulted_special_member_copy_const_param)
4511 << (CSM == CXXCopyAssignment);
4512 // FIXME: Explain why this special member can't be const.
4513 } else {
4514 Diag(MD->getLocation(),
4515 diag::err_defaulted_special_member_move_const_param)
4516 << (CSM == CXXMoveAssignment);
4517 }
4518 HadError = true;
4519 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004520 } else if (ExpectedParams) {
4521 // A copy assignment operator can take its argument by value, but a
4522 // defaulted one cannot.
4523 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004524 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004525 HadError = true;
4526 }
Sean Huntbe631222011-05-17 20:44:43 +00004527
Richard Smith61802452011-12-22 02:22:31 +00004528 // C++11 [dcl.fct.def.default]p2:
4529 // An explicitly-defaulted function may be declared constexpr only if it
4530 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004531 // Do not apply this rule to members of class templates, since core issue 1358
4532 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004533 // functions which cannot be constexpr (for non-constructors in C++11 and for
4534 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004535 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4536 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004537 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4538 : isa<CXXConstructorDecl>(MD)) &&
4539 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004540 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4541 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004542 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004543 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004544 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004545
Richard Smith61802452011-12-22 02:22:31 +00004546 // and may have an explicit exception-specification only if it is compatible
4547 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004548 if (Type->hasExceptionSpec()) {
4549 // Delay the check if this is the first declaration of the special member,
4550 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004551 if (First) {
4552 // If the exception specification needs to be instantiated, do so now,
4553 // before we clobber it with an EST_Unevaluated specification below.
4554 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4555 InstantiateExceptionSpec(MD->getLocStart(), MD);
4556 Type = MD->getType()->getAs<FunctionProtoType>();
4557 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004558 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004559 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004560 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4561 }
Richard Smith61802452011-12-22 02:22:31 +00004562
4563 // If a function is explicitly defaulted on its first declaration,
4564 if (First) {
4565 // -- it is implicitly considered to be constexpr if the implicit
4566 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004567 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004568
Richard Smith3003e1d2012-05-15 04:39:51 +00004569 // -- it is implicitly considered to have the same exception-specification
4570 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004571 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4572 EPI.ExceptionSpecType = EST_Unevaluated;
4573 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004574 MD->setType(Context.getFunctionType(ReturnType,
4575 ArrayRef<QualType>(&ArgType,
4576 ExpectedParams),
4577 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004578 }
4579
Richard Smith3003e1d2012-05-15 04:39:51 +00004580 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004581 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004582 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004583 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004584 // C++11 [dcl.fct.def.default]p4:
4585 // [For a] user-provided explicitly-defaulted function [...] if such a
4586 // function is implicitly defined as deleted, the program is ill-formed.
4587 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4588 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004589 }
4590 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004591
Richard Smith3003e1d2012-05-15 04:39:51 +00004592 if (HadError)
4593 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004594}
4595
Richard Smith1d28caf2012-12-11 01:14:52 +00004596/// Check whether the exception specification provided for an
4597/// explicitly-defaulted special member matches the exception specification
4598/// that would have been generated for an implicit special member, per
4599/// C++11 [dcl.fct.def.default]p2.
4600void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4601 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4602 // Compute the implicit exception specification.
4603 FunctionProtoType::ExtProtoInfo EPI;
4604 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4605 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004606 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004607
4608 // Ensure that it matches.
4609 CheckEquivalentExceptionSpec(
4610 PDiag(diag::err_incorrect_defaulted_exception_spec)
4611 << getSpecialMember(MD), PDiag(),
4612 ImplicitType, SourceLocation(),
4613 SpecifiedType, MD->getLocation());
4614}
4615
4616void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4617 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4618 I != N; ++I)
4619 CheckExplicitlyDefaultedMemberExceptionSpec(
4620 DelayedDefaultedMemberExceptionSpecs[I].first,
4621 DelayedDefaultedMemberExceptionSpecs[I].second);
4622
4623 DelayedDefaultedMemberExceptionSpecs.clear();
4624}
4625
Richard Smith7d5088a2012-02-18 02:02:13 +00004626namespace {
4627struct SpecialMemberDeletionInfo {
4628 Sema &S;
4629 CXXMethodDecl *MD;
4630 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004631 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004632
4633 // Properties of the special member, computed for convenience.
4634 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4635 SourceLocation Loc;
4636
4637 bool AllFieldsAreConst;
4638
4639 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004640 Sema::CXXSpecialMember CSM, bool Diagnose)
4641 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004642 IsConstructor(false), IsAssignment(false), IsMove(false),
4643 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4644 AllFieldsAreConst(true) {
4645 switch (CSM) {
4646 case Sema::CXXDefaultConstructor:
4647 case Sema::CXXCopyConstructor:
4648 IsConstructor = true;
4649 break;
4650 case Sema::CXXMoveConstructor:
4651 IsConstructor = true;
4652 IsMove = true;
4653 break;
4654 case Sema::CXXCopyAssignment:
4655 IsAssignment = true;
4656 break;
4657 case Sema::CXXMoveAssignment:
4658 IsAssignment = true;
4659 IsMove = true;
4660 break;
4661 case Sema::CXXDestructor:
4662 break;
4663 case Sema::CXXInvalid:
4664 llvm_unreachable("invalid special member kind");
4665 }
4666
4667 if (MD->getNumParams()) {
4668 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4669 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4670 }
4671 }
4672
4673 bool inUnion() const { return MD->getParent()->isUnion(); }
4674
4675 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004676 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4677 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004678 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004679 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4680 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4681 Quals = 0;
4682 return S.LookupSpecialMember(Class, CSM,
4683 ConstArg || (Quals & Qualifiers::Const),
4684 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004685 MD->getRefQualifier() == RQ_RValue,
4686 TQ & Qualifiers::Const,
4687 TQ & Qualifiers::Volatile);
4688 }
4689
Richard Smith6c4c36c2012-03-30 20:53:28 +00004690 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004691
Richard Smith6c4c36c2012-03-30 20:53:28 +00004692 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004693 bool shouldDeleteForField(FieldDecl *FD);
4694 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004695
Richard Smith517bb842012-07-18 03:51:16 +00004696 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4697 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004698 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4699 Sema::SpecialMemberOverloadResult *SMOR,
4700 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004701
4702 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004703};
4704}
4705
John McCall12d8d802012-04-09 20:53:23 +00004706/// Is the given special member inaccessible when used on the given
4707/// sub-object.
4708bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4709 CXXMethodDecl *target) {
4710 /// If we're operating on a base class, the object type is the
4711 /// type of this special member.
4712 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004713 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004714 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4715 objectTy = S.Context.getTypeDeclType(MD->getParent());
4716 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4717
4718 // If we're operating on a field, the object type is the type of the field.
4719 } else {
4720 objectTy = S.Context.getTypeDeclType(target->getParent());
4721 }
4722
4723 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4724}
4725
Richard Smith6c4c36c2012-03-30 20:53:28 +00004726/// Check whether we should delete a special member due to the implicit
4727/// definition containing a call to a special member of a subobject.
4728bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4729 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4730 bool IsDtorCallInCtor) {
4731 CXXMethodDecl *Decl = SMOR->getMethod();
4732 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4733
4734 int DiagKind = -1;
4735
4736 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4737 DiagKind = !Decl ? 0 : 1;
4738 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4739 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004740 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004741 DiagKind = 3;
4742 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4743 !Decl->isTrivial()) {
4744 // A member of a union must have a trivial corresponding special member.
4745 // As a weird special case, a destructor call from a union's constructor
4746 // must be accessible and non-deleted, but need not be trivial. Such a
4747 // destructor is never actually called, but is semantically checked as
4748 // if it were.
4749 DiagKind = 4;
4750 }
4751
4752 if (DiagKind == -1)
4753 return false;
4754
4755 if (Diagnose) {
4756 if (Field) {
4757 S.Diag(Field->getLocation(),
4758 diag::note_deleted_special_member_class_subobject)
4759 << CSM << MD->getParent() << /*IsField*/true
4760 << Field << DiagKind << IsDtorCallInCtor;
4761 } else {
4762 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4763 S.Diag(Base->getLocStart(),
4764 diag::note_deleted_special_member_class_subobject)
4765 << CSM << MD->getParent() << /*IsField*/false
4766 << Base->getType() << DiagKind << IsDtorCallInCtor;
4767 }
4768
4769 if (DiagKind == 1)
4770 S.NoteDeletedFunction(Decl);
4771 // FIXME: Explain inaccessibility if DiagKind == 3.
4772 }
4773
4774 return true;
4775}
4776
Richard Smith9a561d52012-02-26 09:11:52 +00004777/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004778/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004779bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004780 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004781 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004782
4783 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004784 // -- any direct or virtual base class, or non-static data member with no
4785 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004786 // either M has no default constructor or overload resolution as applied
4787 // to M's default constructor results in an ambiguity or in a function
4788 // that is deleted or inaccessible
4789 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4790 // -- a direct or virtual base class B that cannot be copied/moved because
4791 // overload resolution, as applied to B's corresponding special member,
4792 // results in an ambiguity or a function that is deleted or inaccessible
4793 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004794 // C++11 [class.dtor]p5:
4795 // -- any direct or virtual base class [...] has a type with a destructor
4796 // that is deleted or inaccessible
4797 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004798 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004799 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004800 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004801
Richard Smith6c4c36c2012-03-30 20:53:28 +00004802 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4803 // -- any direct or virtual base class or non-static data member has a
4804 // type with a destructor that is deleted or inaccessible
4805 if (IsConstructor) {
4806 Sema::SpecialMemberOverloadResult *SMOR =
4807 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4808 false, false, false, false, false);
4809 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4810 return true;
4811 }
4812
Richard Smith9a561d52012-02-26 09:11:52 +00004813 return false;
4814}
4815
4816/// Check whether we should delete a special member function due to the class
4817/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004818bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004819 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004820 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004821}
4822
4823/// Check whether we should delete a special member function due to the class
4824/// having a particular non-static data member.
4825bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4826 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4827 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4828
4829 if (CSM == Sema::CXXDefaultConstructor) {
4830 // For a default constructor, all references must be initialized in-class
4831 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004832 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4833 if (Diagnose)
4834 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4835 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004836 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004837 }
Richard Smith79363f52012-02-27 06:07:25 +00004838 // C++11 [class.ctor]p5: any non-variant non-static data member of
4839 // const-qualified type (or array thereof) with no
4840 // brace-or-equal-initializer does not have a user-provided default
4841 // constructor.
4842 if (!inUnion() && FieldType.isConstQualified() &&
4843 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004844 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4845 if (Diagnose)
4846 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004847 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004848 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004849 }
4850
4851 if (inUnion() && !FieldType.isConstQualified())
4852 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004853 } else if (CSM == Sema::CXXCopyConstructor) {
4854 // For a copy constructor, data members must not be of rvalue reference
4855 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004856 if (FieldType->isRValueReferenceType()) {
4857 if (Diagnose)
4858 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4859 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004860 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004861 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004862 } else if (IsAssignment) {
4863 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004864 if (FieldType->isReferenceType()) {
4865 if (Diagnose)
4866 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4867 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004868 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004869 }
4870 if (!FieldRecord && FieldType.isConstQualified()) {
4871 // C++11 [class.copy]p23:
4872 // -- a non-static data member of const non-class type (or array thereof)
4873 if (Diagnose)
4874 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004875 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004876 return true;
4877 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004878 }
4879
4880 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004881 // Some additional restrictions exist on the variant members.
4882 if (!inUnion() && FieldRecord->isUnion() &&
4883 FieldRecord->isAnonymousStructOrUnion()) {
4884 bool AllVariantFieldsAreConst = true;
4885
Richard Smithdf8dc862012-03-29 19:00:10 +00004886 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004887 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4888 UE = FieldRecord->field_end();
4889 UI != UE; ++UI) {
4890 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004891
4892 if (!UnionFieldType.isConstQualified())
4893 AllVariantFieldsAreConst = false;
4894
Richard Smith9a561d52012-02-26 09:11:52 +00004895 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4896 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004897 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4898 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004899 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004900 }
4901
4902 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004903 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004904 FieldRecord->field_begin() != FieldRecord->field_end()) {
4905 if (Diagnose)
4906 S.Diag(FieldRecord->getLocation(),
4907 diag::note_deleted_default_ctor_all_const)
4908 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004909 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004910 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004911
Richard Smithdf8dc862012-03-29 19:00:10 +00004912 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004913 // This is technically non-conformant, but sanity demands it.
4914 return false;
4915 }
4916
Richard Smith517bb842012-07-18 03:51:16 +00004917 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4918 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004919 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004920 }
4921
4922 return false;
4923}
4924
4925/// C++11 [class.ctor] p5:
4926/// A defaulted default constructor for a class X is defined as deleted if
4927/// X is a union and all of its variant members are of const-qualified type.
4928bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004929 // This is a silly definition, because it gives an empty union a deleted
4930 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004931 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4932 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4933 if (Diagnose)
4934 S.Diag(MD->getParent()->getLocation(),
4935 diag::note_deleted_default_ctor_all_const)
4936 << MD->getParent() << /*not anonymous union*/0;
4937 return true;
4938 }
4939 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004940}
4941
4942/// Determine whether a defaulted special member function should be defined as
4943/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4944/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004945bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4946 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004947 if (MD->isInvalidDecl())
4948 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004949 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004950 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004951 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004952 return false;
4953
Richard Smith7d5088a2012-02-18 02:02:13 +00004954 // C++11 [expr.lambda.prim]p19:
4955 // The closure type associated with a lambda-expression has a
4956 // deleted (8.4.3) default constructor and a deleted copy
4957 // assignment operator.
4958 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004959 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4960 if (Diagnose)
4961 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004962 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004963 }
4964
Richard Smith5bdaac52012-04-02 20:59:25 +00004965 // For an anonymous struct or union, the copy and assignment special members
4966 // will never be used, so skip the check. For an anonymous union declared at
4967 // namespace scope, the constructor and destructor are used.
4968 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4969 RD->isAnonymousStructOrUnion())
4970 return false;
4971
Richard Smith6c4c36c2012-03-30 20:53:28 +00004972 // C++11 [class.copy]p7, p18:
4973 // If the class definition declares a move constructor or move assignment
4974 // operator, an implicitly declared copy constructor or copy assignment
4975 // operator is defined as deleted.
4976 if (MD->isImplicit() &&
4977 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4978 CXXMethodDecl *UserDeclaredMove = 0;
4979
4980 // In Microsoft mode, a user-declared move only causes the deletion of the
4981 // corresponding copy operation, not both copy operations.
4982 if (RD->hasUserDeclaredMoveConstructor() &&
4983 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4984 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004985
4986 // Find any user-declared move constructor.
4987 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4988 E = RD->ctor_end(); I != E; ++I) {
4989 if (I->isMoveConstructor()) {
4990 UserDeclaredMove = *I;
4991 break;
4992 }
4993 }
Richard Smith1c931be2012-04-02 18:40:40 +00004994 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004995 } else if (RD->hasUserDeclaredMoveAssignment() &&
4996 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4997 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004998
4999 // Find any user-declared move assignment operator.
5000 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5001 E = RD->method_end(); I != E; ++I) {
5002 if (I->isMoveAssignmentOperator()) {
5003 UserDeclaredMove = *I;
5004 break;
5005 }
5006 }
Richard Smith1c931be2012-04-02 18:40:40 +00005007 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005008 }
5009
5010 if (UserDeclaredMove) {
5011 Diag(UserDeclaredMove->getLocation(),
5012 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005013 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005014 << UserDeclaredMove->isMoveAssignmentOperator();
5015 return true;
5016 }
5017 }
Sean Hunte16da072011-10-10 06:18:57 +00005018
Richard Smith5bdaac52012-04-02 20:59:25 +00005019 // Do access control from the special member function
5020 ContextRAII MethodContext(*this, MD);
5021
Richard Smith9a561d52012-02-26 09:11:52 +00005022 // C++11 [class.dtor]p5:
5023 // -- for a virtual destructor, lookup of the non-array deallocation function
5024 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005025 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005026 FunctionDecl *OperatorDelete = 0;
5027 DeclarationName Name =
5028 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5029 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005030 OperatorDelete, false)) {
5031 if (Diagnose)
5032 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005033 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005034 }
Richard Smith9a561d52012-02-26 09:11:52 +00005035 }
5036
Richard Smith6c4c36c2012-03-30 20:53:28 +00005037 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005038
Sean Huntcdee3fe2011-05-11 22:34:38 +00005039 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005040 BE = RD->bases_end(); BI != BE; ++BI)
5041 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005042 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005043 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005044
5045 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005046 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00005047 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005048 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005049
5050 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005051 FE = RD->field_end(); FI != FE; ++FI)
5052 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005053 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005054 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005055
Richard Smith7d5088a2012-02-18 02:02:13 +00005056 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005057 return true;
5058
5059 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005060}
5061
Richard Smithac713512012-12-08 02:53:02 +00005062/// Perform lookup for a special member of the specified kind, and determine
5063/// whether it is trivial. If the triviality can be determined without the
5064/// lookup, skip it. This is intended for use when determining whether a
5065/// special member of a containing object is trivial, and thus does not ever
5066/// perform overload resolution for default constructors.
5067///
5068/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5069/// member that was most likely to be intended to be trivial, if any.
5070static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5071 Sema::CXXSpecialMember CSM, unsigned Quals,
5072 CXXMethodDecl **Selected) {
5073 if (Selected)
5074 *Selected = 0;
5075
5076 switch (CSM) {
5077 case Sema::CXXInvalid:
5078 llvm_unreachable("not a special member");
5079
5080 case Sema::CXXDefaultConstructor:
5081 // C++11 [class.ctor]p5:
5082 // A default constructor is trivial if:
5083 // - all the [direct subobjects] have trivial default constructors
5084 //
5085 // Note, no overload resolution is performed in this case.
5086 if (RD->hasTrivialDefaultConstructor())
5087 return true;
5088
5089 if (Selected) {
5090 // If there's a default constructor which could have been trivial, dig it
5091 // out. Otherwise, if there's any user-provided default constructor, point
5092 // to that as an example of why there's not a trivial one.
5093 CXXConstructorDecl *DefCtor = 0;
5094 if (RD->needsImplicitDefaultConstructor())
5095 S.DeclareImplicitDefaultConstructor(RD);
5096 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5097 CE = RD->ctor_end(); CI != CE; ++CI) {
5098 if (!CI->isDefaultConstructor())
5099 continue;
5100 DefCtor = *CI;
5101 if (!DefCtor->isUserProvided())
5102 break;
5103 }
5104
5105 *Selected = DefCtor;
5106 }
5107
5108 return false;
5109
5110 case Sema::CXXDestructor:
5111 // C++11 [class.dtor]p5:
5112 // A destructor is trivial if:
5113 // - all the direct [subobjects] have trivial destructors
5114 if (RD->hasTrivialDestructor())
5115 return true;
5116
5117 if (Selected) {
5118 if (RD->needsImplicitDestructor())
5119 S.DeclareImplicitDestructor(RD);
5120 *Selected = RD->getDestructor();
5121 }
5122
5123 return false;
5124
5125 case Sema::CXXCopyConstructor:
5126 // C++11 [class.copy]p12:
5127 // A copy constructor is trivial if:
5128 // - the constructor selected to copy each direct [subobject] is trivial
5129 if (RD->hasTrivialCopyConstructor()) {
5130 if (Quals == Qualifiers::Const)
5131 // We must either select the trivial copy constructor or reach an
5132 // ambiguity; no need to actually perform overload resolution.
5133 return true;
5134 } else if (!Selected) {
5135 return false;
5136 }
5137 // In C++98, we are not supposed to perform overload resolution here, but we
5138 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5139 // cases like B as having a non-trivial copy constructor:
5140 // struct A { template<typename T> A(T&); };
5141 // struct B { mutable A a; };
5142 goto NeedOverloadResolution;
5143
5144 case Sema::CXXCopyAssignment:
5145 // C++11 [class.copy]p25:
5146 // A copy assignment operator is trivial if:
5147 // - the assignment operator selected to copy each direct [subobject] is
5148 // trivial
5149 if (RD->hasTrivialCopyAssignment()) {
5150 if (Quals == Qualifiers::Const)
5151 return true;
5152 } else if (!Selected) {
5153 return false;
5154 }
5155 // In C++98, we are not supposed to perform overload resolution here, but we
5156 // treat that as a language defect.
5157 goto NeedOverloadResolution;
5158
5159 case Sema::CXXMoveConstructor:
5160 case Sema::CXXMoveAssignment:
5161 NeedOverloadResolution:
5162 Sema::SpecialMemberOverloadResult *SMOR =
5163 S.LookupSpecialMember(RD, CSM,
5164 Quals & Qualifiers::Const,
5165 Quals & Qualifiers::Volatile,
5166 /*RValueThis*/false, /*ConstThis*/false,
5167 /*VolatileThis*/false);
5168
5169 // The standard doesn't describe how to behave if the lookup is ambiguous.
5170 // We treat it as not making the member non-trivial, just like the standard
5171 // mandates for the default constructor. This should rarely matter, because
5172 // the member will also be deleted.
5173 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5174 return true;
5175
5176 if (!SMOR->getMethod()) {
5177 assert(SMOR->getKind() ==
5178 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5179 return false;
5180 }
5181
5182 // We deliberately don't check if we found a deleted special member. We're
5183 // not supposed to!
5184 if (Selected)
5185 *Selected = SMOR->getMethod();
5186 return SMOR->getMethod()->isTrivial();
5187 }
5188
5189 llvm_unreachable("unknown special method kind");
5190}
5191
Benjamin Kramera574c892013-02-15 12:30:38 +00005192static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005193 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5194 CI != CE; ++CI)
5195 if (!CI->isImplicit())
5196 return *CI;
5197
5198 // Look for constructor templates.
5199 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5200 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5201 if (CXXConstructorDecl *CD =
5202 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5203 return CD;
5204 }
5205
5206 return 0;
5207}
5208
5209/// The kind of subobject we are checking for triviality. The values of this
5210/// enumeration are used in diagnostics.
5211enum TrivialSubobjectKind {
5212 /// The subobject is a base class.
5213 TSK_BaseClass,
5214 /// The subobject is a non-static data member.
5215 TSK_Field,
5216 /// The object is actually the complete object.
5217 TSK_CompleteObject
5218};
5219
5220/// Check whether the special member selected for a given type would be trivial.
5221static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5222 QualType SubType,
5223 Sema::CXXSpecialMember CSM,
5224 TrivialSubobjectKind Kind,
5225 bool Diagnose) {
5226 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5227 if (!SubRD)
5228 return true;
5229
5230 CXXMethodDecl *Selected;
5231 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5232 Diagnose ? &Selected : 0))
5233 return true;
5234
5235 if (Diagnose) {
5236 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5237 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5238 << Kind << SubType.getUnqualifiedType();
5239 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5240 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5241 } else if (!Selected)
5242 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5243 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5244 else if (Selected->isUserProvided()) {
5245 if (Kind == TSK_CompleteObject)
5246 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5247 << Kind << SubType.getUnqualifiedType() << CSM;
5248 else {
5249 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5250 << Kind << SubType.getUnqualifiedType() << CSM;
5251 S.Diag(Selected->getLocation(), diag::note_declared_at);
5252 }
5253 } else {
5254 if (Kind != TSK_CompleteObject)
5255 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5256 << Kind << SubType.getUnqualifiedType() << CSM;
5257
5258 // Explain why the defaulted or deleted special member isn't trivial.
5259 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5260 }
5261 }
5262
5263 return false;
5264}
5265
5266/// Check whether the members of a class type allow a special member to be
5267/// trivial.
5268static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5269 Sema::CXXSpecialMember CSM,
5270 bool ConstArg, bool Diagnose) {
5271 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5272 FE = RD->field_end(); FI != FE; ++FI) {
5273 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5274 continue;
5275
5276 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5277
5278 // Pretend anonymous struct or union members are members of this class.
5279 if (FI->isAnonymousStructOrUnion()) {
5280 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5281 CSM, ConstArg, Diagnose))
5282 return false;
5283 continue;
5284 }
5285
5286 // C++11 [class.ctor]p5:
5287 // A default constructor is trivial if [...]
5288 // -- no non-static data member of its class has a
5289 // brace-or-equal-initializer
5290 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5291 if (Diagnose)
5292 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5293 return false;
5294 }
5295
5296 // Objective C ARC 4.3.5:
5297 // [...] nontrivally ownership-qualified types are [...] not trivially
5298 // default constructible, copy constructible, move constructible, copy
5299 // assignable, move assignable, or destructible [...]
5300 if (S.getLangOpts().ObjCAutoRefCount &&
5301 FieldType.hasNonTrivialObjCLifetime()) {
5302 if (Diagnose)
5303 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5304 << RD << FieldType.getObjCLifetime();
5305 return false;
5306 }
5307
5308 if (ConstArg && !FI->isMutable())
5309 FieldType.addConst();
5310 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5311 TSK_Field, Diagnose))
5312 return false;
5313 }
5314
5315 return true;
5316}
5317
5318/// Diagnose why the specified class does not have a trivial special member of
5319/// the given kind.
5320void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5321 QualType Ty = Context.getRecordType(RD);
5322 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5323 Ty.addConst();
5324
5325 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5326 TSK_CompleteObject, /*Diagnose*/true);
5327}
5328
5329/// Determine whether a defaulted or deleted special member function is trivial,
5330/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5331/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5332bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5333 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005334 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5335
5336 CXXRecordDecl *RD = MD->getParent();
5337
5338 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005339
5340 // C++11 [class.copy]p12, p25:
5341 // A [special member] is trivial if its declared parameter type is the same
5342 // as if it had been implicitly declared [...]
5343 switch (CSM) {
5344 case CXXDefaultConstructor:
5345 case CXXDestructor:
5346 // Trivial default constructors and destructors cannot have parameters.
5347 break;
5348
5349 case CXXCopyConstructor:
5350 case CXXCopyAssignment: {
5351 // Trivial copy operations always have const, non-volatile parameter types.
5352 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005353 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005354 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5355 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5356 if (Diagnose)
5357 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5358 << Param0->getSourceRange() << Param0->getType()
5359 << Context.getLValueReferenceType(
5360 Context.getRecordType(RD).withConst());
5361 return false;
5362 }
5363 break;
5364 }
5365
5366 case CXXMoveConstructor:
5367 case CXXMoveAssignment: {
5368 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005369 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005370 const RValueReferenceType *RT =
5371 Param0->getType()->getAs<RValueReferenceType>();
5372 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5373 if (Diagnose)
5374 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5375 << Param0->getSourceRange() << Param0->getType()
5376 << Context.getRValueReferenceType(Context.getRecordType(RD));
5377 return false;
5378 }
5379 break;
5380 }
5381
5382 case CXXInvalid:
5383 llvm_unreachable("not a special member");
5384 }
5385
5386 // FIXME: We require that the parameter-declaration-clause is equivalent to
5387 // that of an implicit declaration, not just that the declared parameter type
5388 // matches, in order to prevent absuridities like a function simultaneously
5389 // being a trivial copy constructor and a non-trivial default constructor.
5390 // This issue has not yet been assigned a core issue number.
5391 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5392 if (Diagnose)
5393 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5394 diag::note_nontrivial_default_arg)
5395 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5396 return false;
5397 }
5398 if (MD->isVariadic()) {
5399 if (Diagnose)
5400 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5401 return false;
5402 }
5403
5404 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5405 // A copy/move [constructor or assignment operator] is trivial if
5406 // -- the [member] selected to copy/move each direct base class subobject
5407 // is trivial
5408 //
5409 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5410 // A [default constructor or destructor] is trivial if
5411 // -- all the direct base classes have trivial [default constructors or
5412 // destructors]
5413 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5414 BE = RD->bases_end(); BI != BE; ++BI)
5415 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5416 ConstArg ? BI->getType().withConst()
5417 : BI->getType(),
5418 CSM, TSK_BaseClass, Diagnose))
5419 return false;
5420
5421 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5422 // A copy/move [constructor or assignment operator] for a class X is
5423 // trivial if
5424 // -- for each non-static data member of X that is of class type (or array
5425 // thereof), the constructor selected to copy/move that member is
5426 // trivial
5427 //
5428 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5429 // A [default constructor or destructor] is trivial if
5430 // -- for all of the non-static data members of its class that are of class
5431 // type (or array thereof), each such class has a trivial [default
5432 // constructor or destructor]
5433 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5434 return false;
5435
5436 // C++11 [class.dtor]p5:
5437 // A destructor is trivial if [...]
5438 // -- the destructor is not virtual
5439 if (CSM == CXXDestructor && MD->isVirtual()) {
5440 if (Diagnose)
5441 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5442 return false;
5443 }
5444
5445 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5446 // A [special member] for class X is trivial if [...]
5447 // -- class X has no virtual functions and no virtual base classes
5448 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5449 if (!Diagnose)
5450 return false;
5451
5452 if (RD->getNumVBases()) {
5453 // Check for virtual bases. We already know that the corresponding
5454 // member in all bases is trivial, so vbases must all be direct.
5455 CXXBaseSpecifier &BS = *RD->vbases_begin();
5456 assert(BS.isVirtual());
5457 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5458 return false;
5459 }
5460
5461 // Must have a virtual method.
5462 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5463 ME = RD->method_end(); MI != ME; ++MI) {
5464 if (MI->isVirtual()) {
5465 SourceLocation MLoc = MI->getLocStart();
5466 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5467 return false;
5468 }
5469 }
5470
5471 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5472 }
5473
5474 // Looks like it's trivial!
5475 return true;
5476}
5477
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005478/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005479namespace {
5480 struct FindHiddenVirtualMethodData {
5481 Sema *S;
5482 CXXMethodDecl *Method;
5483 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005484 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005485 };
5486}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005487
David Blaikie5f750682012-10-19 00:53:08 +00005488/// \brief Check whether any most overriden method from MD in Methods
5489static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5490 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5491 if (MD->size_overridden_methods() == 0)
5492 return Methods.count(MD->getCanonicalDecl());
5493 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5494 E = MD->end_overridden_methods();
5495 I != E; ++I)
5496 if (CheckMostOverridenMethods(*I, Methods))
5497 return true;
5498 return false;
5499}
5500
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005501/// \brief Member lookup function that determines whether a given C++
5502/// method overloads virtual methods in a base class without overriding any,
5503/// to be used with CXXRecordDecl::lookupInBases().
5504static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5505 CXXBasePath &Path,
5506 void *UserData) {
5507 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5508
5509 FindHiddenVirtualMethodData &Data
5510 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5511
5512 DeclarationName Name = Data.Method->getDeclName();
5513 assert(Name.getNameKind() == DeclarationName::Identifier);
5514
5515 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005516 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005517 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005518 !Path.Decls.empty();
5519 Path.Decls = Path.Decls.slice(1)) {
5520 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005521 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005522 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005523 foundSameNameMethod = true;
5524 // Interested only in hidden virtual methods.
5525 if (!MD->isVirtual())
5526 continue;
5527 // If the method we are checking overrides a method from its base
5528 // don't warn about the other overloaded methods.
5529 if (!Data.S->IsOverload(Data.Method, MD, false))
5530 return true;
5531 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005532 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005533 overloadedMethods.push_back(MD);
5534 }
5535 }
5536
5537 if (foundSameNameMethod)
5538 Data.OverloadedMethods.append(overloadedMethods.begin(),
5539 overloadedMethods.end());
5540 return foundSameNameMethod;
5541}
5542
David Blaikie5f750682012-10-19 00:53:08 +00005543/// \brief Add the most overriden methods from MD to Methods
5544static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5545 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5546 if (MD->size_overridden_methods() == 0)
5547 Methods.insert(MD->getCanonicalDecl());
5548 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5549 E = MD->end_overridden_methods();
5550 I != E; ++I)
5551 AddMostOverridenMethods(*I, Methods);
5552}
5553
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005554/// \brief See if a method overloads virtual methods in a base class without
5555/// overriding any.
5556void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5557 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005558 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005559 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005560 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005561 return;
5562
5563 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5564 /*bool RecordPaths=*/false,
5565 /*bool DetectVirtual=*/false);
5566 FindHiddenVirtualMethodData Data;
5567 Data.Method = MD;
5568 Data.S = this;
5569
5570 // Keep the base methods that were overriden or introduced in the subclass
5571 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005572 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5573 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5574 NamedDecl *ND = *I;
5575 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005576 ND = shad->getTargetDecl();
5577 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5578 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005579 }
5580
5581 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5582 !Data.OverloadedMethods.empty()) {
5583 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5584 << MD << (Data.OverloadedMethods.size() > 1);
5585
5586 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5587 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005588 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005589 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005590 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5591 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005592 }
5593 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005594}
5595
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005596void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005597 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005598 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005599 SourceLocation RBrac,
5600 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005601 if (!TagDecl)
5602 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005603
Douglas Gregor42af25f2009-05-11 19:58:34 +00005604 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005605
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005606 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5607 if (l->getKind() != AttributeList::AT_Visibility)
5608 continue;
5609 l->setInvalid();
5610 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5611 l->getName();
5612 }
5613
David Blaikie77b6de02011-09-22 02:58:26 +00005614 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005615 // strict aliasing violation!
5616 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005617 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005618
Douglas Gregor23c94db2010-07-02 17:43:08 +00005619 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005620 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005621}
5622
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005623/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5624/// special functions, such as the default constructor, copy
5625/// constructor, or destructor, to the given C++ class (C++
5626/// [special]p1). This routine can only be executed just before the
5627/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005628void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005629 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005630 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005631
Richard Smithbc2a35d2012-12-08 08:32:28 +00005632 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005633 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005634
Richard Smithbc2a35d2012-12-08 08:32:28 +00005635 // If the properties or semantics of the copy constructor couldn't be
5636 // determined while the class was being declared, force a declaration
5637 // of it now.
5638 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5639 DeclareImplicitCopyConstructor(ClassDecl);
5640 }
5641
Richard Smith80ad52f2013-01-02 11:42:31 +00005642 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005643 ++ASTContext::NumImplicitMoveConstructors;
5644
Richard Smithbc2a35d2012-12-08 08:32:28 +00005645 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5646 DeclareImplicitMoveConstructor(ClassDecl);
5647 }
5648
Douglas Gregora376d102010-07-02 21:50:04 +00005649 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5650 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005651
5652 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005653 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005654 // it shows up in the right place in the vtable and that we diagnose
5655 // problems with the implicit exception specification.
5656 if (ClassDecl->isDynamicClass() ||
5657 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005658 DeclareImplicitCopyAssignment(ClassDecl);
5659 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005660
Richard Smith80ad52f2013-01-02 11:42:31 +00005661 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005662 ++ASTContext::NumImplicitMoveAssignmentOperators;
5663
5664 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005665 if (ClassDecl->isDynamicClass() ||
5666 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005667 DeclareImplicitMoveAssignment(ClassDecl);
5668 }
5669
Douglas Gregor4923aa22010-07-02 20:37:36 +00005670 if (!ClassDecl->hasUserDeclaredDestructor()) {
5671 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005672
5673 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005674 // have to declare the destructor immediately. This ensures that, e.g., it
5675 // shows up in the right place in the vtable and that we diagnose problems
5676 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005677 if (ClassDecl->isDynamicClass() ||
5678 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005679 DeclareImplicitDestructor(ClassDecl);
5680 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005681}
5682
Francois Pichet8387e2a2011-04-22 22:18:13 +00005683void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5684 if (!D)
5685 return;
5686
5687 int NumParamList = D->getNumTemplateParameterLists();
5688 for (int i = 0; i < NumParamList; i++) {
5689 TemplateParameterList* Params = D->getTemplateParameterList(i);
5690 for (TemplateParameterList::iterator Param = Params->begin(),
5691 ParamEnd = Params->end();
5692 Param != ParamEnd; ++Param) {
5693 NamedDecl *Named = cast<NamedDecl>(*Param);
5694 if (Named->getDeclName()) {
5695 S->AddDecl(Named);
5696 IdResolver.AddDecl(Named);
5697 }
5698 }
5699 }
5700}
5701
John McCalld226f652010-08-21 09:40:31 +00005702void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005703 if (!D)
5704 return;
5705
5706 TemplateParameterList *Params = 0;
5707 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5708 Params = Template->getTemplateParameters();
5709 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5710 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5711 Params = PartialSpec->getTemplateParameters();
5712 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005713 return;
5714
Douglas Gregor6569d682009-05-27 23:11:45 +00005715 for (TemplateParameterList::iterator Param = Params->begin(),
5716 ParamEnd = Params->end();
5717 Param != ParamEnd; ++Param) {
5718 NamedDecl *Named = cast<NamedDecl>(*Param);
5719 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005720 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005721 IdResolver.AddDecl(Named);
5722 }
5723 }
5724}
5725
John McCalld226f652010-08-21 09:40:31 +00005726void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005727 if (!RecordD) return;
5728 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005729 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005730 PushDeclContext(S, Record);
5731}
5732
John McCalld226f652010-08-21 09:40:31 +00005733void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005734 if (!RecordD) return;
5735 PopDeclContext();
5736}
5737
Douglas Gregor72b505b2008-12-16 21:30:33 +00005738/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5739/// parsing a top-level (non-nested) C++ class, and we are now
5740/// parsing those parts of the given Method declaration that could
5741/// not be parsed earlier (C++ [class.mem]p2), such as default
5742/// arguments. This action should enter the scope of the given
5743/// Method declaration as if we had just parsed the qualified method
5744/// name. However, it should not bring the parameters into scope;
5745/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005746void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005747}
5748
5749/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5750/// C++ method declaration. We're (re-)introducing the given
5751/// function parameter into scope for use in parsing later parts of
5752/// the method declaration. For example, we could see an
5753/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005754void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005755 if (!ParamD)
5756 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005757
John McCalld226f652010-08-21 09:40:31 +00005758 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005759
5760 // If this parameter has an unparsed default argument, clear it out
5761 // to make way for the parsed default argument.
5762 if (Param->hasUnparsedDefaultArg())
5763 Param->setDefaultArg(0);
5764
John McCalld226f652010-08-21 09:40:31 +00005765 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005766 if (Param->getDeclName())
5767 IdResolver.AddDecl(Param);
5768}
5769
5770/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5771/// processing the delayed method declaration for Method. The method
5772/// declaration is now considered finished. There may be a separate
5773/// ActOnStartOfFunctionDef action later (not necessarily
5774/// immediately!) for this method, if it was also defined inside the
5775/// class body.
John McCalld226f652010-08-21 09:40:31 +00005776void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005777 if (!MethodD)
5778 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005779
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005780 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005781
John McCalld226f652010-08-21 09:40:31 +00005782 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005783
5784 // Now that we have our default arguments, check the constructor
5785 // again. It could produce additional diagnostics or affect whether
5786 // the class has implicitly-declared destructors, among other
5787 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005788 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5789 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005790
5791 // Check the default arguments, which we may have added.
5792 if (!Method->isInvalidDecl())
5793 CheckCXXDefaultArguments(Method);
5794}
5795
Douglas Gregor42a552f2008-11-05 20:51:48 +00005796/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005797/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005798/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005799/// emit diagnostics and set the invalid bit to true. In any case, the type
5800/// will be updated to reflect a well-formed type for the constructor and
5801/// returned.
5802QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005803 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005804 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005805
5806 // C++ [class.ctor]p3:
5807 // A constructor shall not be virtual (10.3) or static (9.4). A
5808 // constructor can be invoked for a const, volatile or const
5809 // volatile object. A constructor shall not be declared const,
5810 // volatile, or const volatile (9.3.2).
5811 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005812 if (!D.isInvalidType())
5813 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5814 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5815 << SourceRange(D.getIdentifierLoc());
5816 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005817 }
John McCalld931b082010-08-26 03:08:43 +00005818 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005819 if (!D.isInvalidType())
5820 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5821 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5822 << SourceRange(D.getIdentifierLoc());
5823 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005824 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005825 }
Mike Stump1eb44332009-09-09 15:08:12 +00005826
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005827 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005828 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005829 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005830 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5831 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005832 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005833 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5834 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005835 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005836 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5837 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005838 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005839 }
Mike Stump1eb44332009-09-09 15:08:12 +00005840
Douglas Gregorc938c162011-01-26 05:01:58 +00005841 // C++0x [class.ctor]p4:
5842 // A constructor shall not be declared with a ref-qualifier.
5843 if (FTI.hasRefQualifier()) {
5844 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5845 << FTI.RefQualifierIsLValueRef
5846 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5847 D.setInvalidType();
5848 }
5849
Douglas Gregor42a552f2008-11-05 20:51:48 +00005850 // Rebuild the function type "R" without any type qualifiers (in
5851 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005852 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005853 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005854 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5855 return R;
5856
5857 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5858 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005859 EPI.RefQualifier = RQ_None;
5860
Richard Smith07b0fdc2013-03-18 21:12:30 +00005861 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005862}
5863
Douglas Gregor72b505b2008-12-16 21:30:33 +00005864/// CheckConstructor - Checks a fully-formed constructor for
5865/// well-formedness, issuing any diagnostics required. Returns true if
5866/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005867void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005868 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005869 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5870 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005871 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005872
5873 // C++ [class.copy]p3:
5874 // A declaration of a constructor for a class X is ill-formed if
5875 // its first parameter is of type (optionally cv-qualified) X and
5876 // either there are no other parameters or else all other
5877 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005878 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005879 ((Constructor->getNumParams() == 1) ||
5880 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005881 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5882 Constructor->getTemplateSpecializationKind()
5883 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005884 QualType ParamType = Constructor->getParamDecl(0)->getType();
5885 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5886 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005887 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005888 const char *ConstRef
5889 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5890 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005891 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005892 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005893
5894 // FIXME: Rather that making the constructor invalid, we should endeavor
5895 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005896 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005897 }
5898 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005899}
5900
John McCall15442822010-08-04 01:04:25 +00005901/// CheckDestructor - Checks a fully-formed destructor definition for
5902/// well-formedness, issuing any diagnostics required. Returns true
5903/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005904bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005905 CXXRecordDecl *RD = Destructor->getParent();
5906
Peter Collingbournef51cfb82013-05-20 14:12:25 +00005907 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005908 SourceLocation Loc;
5909
5910 if (!Destructor->isImplicit())
5911 Loc = Destructor->getLocation();
5912 else
5913 Loc = RD->getLocation();
5914
5915 // If we have a virtual destructor, look up the deallocation function
5916 FunctionDecl *OperatorDelete = 0;
5917 DeclarationName Name =
5918 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005919 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005920 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005921
Eli Friedman5f2987c2012-02-02 03:46:19 +00005922 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005923
5924 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005925 }
Anders Carlsson37909802009-11-30 21:24:50 +00005926
5927 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005928}
5929
Mike Stump1eb44332009-09-09 15:08:12 +00005930static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005931FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5932 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5933 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005934 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005935}
5936
Douglas Gregor42a552f2008-11-05 20:51:48 +00005937/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5938/// the well-formednes of the destructor declarator @p D with type @p
5939/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005940/// emit diagnostics and set the declarator to invalid. Even if this happens,
5941/// will be updated to reflect a well-formed type for the destructor and
5942/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005943QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005944 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005945 // C++ [class.dtor]p1:
5946 // [...] A typedef-name that names a class is a class-name
5947 // (7.1.3); however, a typedef-name that names a class shall not
5948 // be used as the identifier in the declarator for a destructor
5949 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005950 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005951 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005952 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005953 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005954 else if (const TemplateSpecializationType *TST =
5955 DeclaratorType->getAs<TemplateSpecializationType>())
5956 if (TST->isTypeAlias())
5957 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5958 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005959
5960 // C++ [class.dtor]p2:
5961 // A destructor is used to destroy objects of its class type. A
5962 // destructor takes no parameters, and no return type can be
5963 // specified for it (not even void). The address of a destructor
5964 // shall not be taken. A destructor shall not be static. A
5965 // destructor can be invoked for a const, volatile or const
5966 // volatile object. A destructor shall not be declared const,
5967 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005968 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005969 if (!D.isInvalidType())
5970 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5971 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005972 << SourceRange(D.getIdentifierLoc())
5973 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5974
John McCalld931b082010-08-26 03:08:43 +00005975 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005976 }
Chris Lattner65401802009-04-25 08:28:21 +00005977 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005978 // Destructors don't have return types, but the parser will
5979 // happily parse something like:
5980 //
5981 // class X {
5982 // float ~X();
5983 // };
5984 //
5985 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005986 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5987 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5988 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005989 }
Mike Stump1eb44332009-09-09 15:08:12 +00005990
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005991 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005992 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005993 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005994 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5995 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005996 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005997 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5998 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005999 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006000 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6001 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006002 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006003 }
6004
Douglas Gregorc938c162011-01-26 05:01:58 +00006005 // C++0x [class.dtor]p2:
6006 // A destructor shall not be declared with a ref-qualifier.
6007 if (FTI.hasRefQualifier()) {
6008 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6009 << FTI.RefQualifierIsLValueRef
6010 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6011 D.setInvalidType();
6012 }
6013
Douglas Gregor42a552f2008-11-05 20:51:48 +00006014 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006015 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006016 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6017
6018 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006019 FTI.freeArgs();
6020 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006021 }
6022
Mike Stump1eb44332009-09-09 15:08:12 +00006023 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006024 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006025 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006026 D.setInvalidType();
6027 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006028
6029 // Rebuild the function type "R" without any type qualifiers or
6030 // parameters (in case any of the errors above fired) and with
6031 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006032 // types.
John McCalle23cf432010-12-14 08:05:40 +00006033 if (!D.isInvalidType())
6034 return R;
6035
Douglas Gregord92ec472010-07-01 05:10:53 +00006036 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006037 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6038 EPI.Variadic = false;
6039 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006040 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006041 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006042}
6043
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006044/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6045/// well-formednes of the conversion function declarator @p D with
6046/// type @p R. If there are any errors in the declarator, this routine
6047/// will emit diagnostics and return true. Otherwise, it will return
6048/// false. Either way, the type @p R will be updated to reflect a
6049/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006050void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006051 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006052 // C++ [class.conv.fct]p1:
6053 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006054 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006055 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006056 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006057 if (!D.isInvalidType())
6058 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6059 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6060 << SourceRange(D.getIdentifierLoc());
6061 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006062 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006063 }
John McCalla3f81372010-04-13 00:04:31 +00006064
6065 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6066
Chris Lattner6e475012009-04-25 08:35:12 +00006067 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006068 // Conversion functions don't have return types, but the parser will
6069 // happily parse something like:
6070 //
6071 // class X {
6072 // float operator bool();
6073 // };
6074 //
6075 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006076 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6077 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6078 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006079 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006080 }
6081
John McCalla3f81372010-04-13 00:04:31 +00006082 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6083
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006084 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006085 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006086 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6087
6088 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006089 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006090 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006091 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006092 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006093 D.setInvalidType();
6094 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006095
John McCalla3f81372010-04-13 00:04:31 +00006096 // Diagnose "&operator bool()" and other such nonsense. This
6097 // is actually a gcc extension which we don't support.
6098 if (Proto->getResultType() != ConvType) {
6099 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6100 << Proto->getResultType();
6101 D.setInvalidType();
6102 ConvType = Proto->getResultType();
6103 }
6104
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006105 // C++ [class.conv.fct]p4:
6106 // The conversion-type-id shall not represent a function type nor
6107 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006108 if (ConvType->isArrayType()) {
6109 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6110 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006111 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006112 } else if (ConvType->isFunctionType()) {
6113 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6114 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006115 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006116 }
6117
6118 // Rebuild the function type "R" without any parameters (in case any
6119 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006120 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006121 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006122 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006123
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006124 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006125 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006126 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006127 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006128 diag::warn_cxx98_compat_explicit_conversion_functions :
6129 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006130 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006131}
6132
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006133/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6134/// the declaration of the given C++ conversion function. This routine
6135/// is responsible for recording the conversion function in the C++
6136/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006137Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006138 assert(Conversion && "Expected to receive a conversion function declaration");
6139
Douglas Gregor9d350972008-12-12 08:25:50 +00006140 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006141
6142 // Make sure we aren't redeclaring the conversion function.
6143 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006144
6145 // C++ [class.conv.fct]p1:
6146 // [...] A conversion function is never used to convert a
6147 // (possibly cv-qualified) object to the (possibly cv-qualified)
6148 // same object type (or a reference to it), to a (possibly
6149 // cv-qualified) base class of that type (or a reference to it),
6150 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006151 // FIXME: Suppress this warning if the conversion function ends up being a
6152 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006153 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006154 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006155 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006156 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006157 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6158 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006159 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006160 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006161 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6162 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006163 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006164 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006165 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006166 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006167 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006168 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006169 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006170 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006171 }
6172
Douglas Gregore80622f2010-09-29 04:25:11 +00006173 if (FunctionTemplateDecl *ConversionTemplate
6174 = Conversion->getDescribedFunctionTemplate())
6175 return ConversionTemplate;
6176
John McCalld226f652010-08-21 09:40:31 +00006177 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006178}
6179
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006180//===----------------------------------------------------------------------===//
6181// Namespace Handling
6182//===----------------------------------------------------------------------===//
6183
Richard Smithd1a55a62012-10-04 22:13:39 +00006184/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6185/// reopened.
6186static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6187 SourceLocation Loc,
6188 IdentifierInfo *II, bool *IsInline,
6189 NamespaceDecl *PrevNS) {
6190 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006191
Richard Smithc969e6a2012-10-05 01:46:25 +00006192 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6193 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6194 // inline namespaces, with the intention of bringing names into namespace std.
6195 //
6196 // We support this just well enough to get that case working; this is not
6197 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006198 if (*IsInline && II && II->getName().startswith("__atomic") &&
6199 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006200 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006201 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6202 NS = NS->getPreviousDecl())
6203 NS->setInline(*IsInline);
6204 // Patch up the lookup table for the containing namespace. This isn't really
6205 // correct, but it's good enough for this particular case.
6206 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6207 E = PrevNS->decls_end(); I != E; ++I)
6208 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6209 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6210 return;
6211 }
6212
6213 if (PrevNS->isInline())
6214 // The user probably just forgot the 'inline', so suggest that it
6215 // be added back.
6216 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6217 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6218 else
6219 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6220 << IsInline;
6221
6222 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6223 *IsInline = PrevNS->isInline();
6224}
John McCallea318642010-08-26 09:15:37 +00006225
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006226/// ActOnStartNamespaceDef - This is called at the start of a namespace
6227/// definition.
John McCalld226f652010-08-21 09:40:31 +00006228Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006229 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006230 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006231 SourceLocation IdentLoc,
6232 IdentifierInfo *II,
6233 SourceLocation LBrace,
6234 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006235 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6236 // For anonymous namespace, take the location of the left brace.
6237 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006238 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006239 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006240 bool IsStd = false;
6241 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006242 Scope *DeclRegionScope = NamespcScope->getParent();
6243
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006244 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006245 if (II) {
6246 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006247 // The identifier in an original-namespace-definition shall not
6248 // have been previously defined in the declarative region in
6249 // which the original-namespace-definition appears. The
6250 // identifier in an original-namespace-definition is the name of
6251 // the namespace. Subsequently in that declarative region, it is
6252 // treated as an original-namespace-name.
6253 //
6254 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006255 // look through using directives, just look for any ordinary names.
6256
6257 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006258 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6259 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006260 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006261 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6262 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6263 ++I) {
6264 if ((*I)->getIdentifierNamespace() & IDNS) {
6265 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006266 break;
6267 }
6268 }
6269
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006270 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6271
6272 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006273 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006274 if (IsInline != PrevNS->isInline())
6275 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6276 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006277 } else if (PrevDecl) {
6278 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006279 Diag(Loc, diag::err_redefinition_different_kind)
6280 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006281 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006282 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006283 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006284 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006285 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006286 // This is the first "real" definition of the namespace "std", so update
6287 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006288 PrevNS = getStdNamespace();
6289 IsStd = true;
6290 AddToKnown = !IsInline;
6291 } else {
6292 // We've seen this namespace for the first time.
6293 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006294 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006295 } else {
John McCall9aeed322009-10-01 00:25:31 +00006296 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006297
6298 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006299 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006300 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006301 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006302 } else {
6303 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006304 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006305 }
6306
Richard Smithd1a55a62012-10-04 22:13:39 +00006307 if (PrevNS && IsInline != PrevNS->isInline())
6308 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6309 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006310 }
6311
6312 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6313 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006314 if (IsInvalid)
6315 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006316
6317 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006318
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006319 // FIXME: Should we be merging attributes?
6320 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006321 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006322
6323 if (IsStd)
6324 StdNamespace = Namespc;
6325 if (AddToKnown)
6326 KnownNamespaces[Namespc] = false;
6327
6328 if (II) {
6329 PushOnScopeChains(Namespc, DeclRegionScope);
6330 } else {
6331 // Link the anonymous namespace into its parent.
6332 DeclContext *Parent = CurContext->getRedeclContext();
6333 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6334 TU->setAnonymousNamespace(Namespc);
6335 } else {
6336 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006337 }
John McCall9aeed322009-10-01 00:25:31 +00006338
Douglas Gregora4181472010-03-24 00:46:35 +00006339 CurContext->addDecl(Namespc);
6340
John McCall9aeed322009-10-01 00:25:31 +00006341 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6342 // behaves as if it were replaced by
6343 // namespace unique { /* empty body */ }
6344 // using namespace unique;
6345 // namespace unique { namespace-body }
6346 // where all occurrences of 'unique' in a translation unit are
6347 // replaced by the same identifier and this identifier differs
6348 // from all other identifiers in the entire program.
6349
6350 // We just create the namespace with an empty name and then add an
6351 // implicit using declaration, just like the standard suggests.
6352 //
6353 // CodeGen enforces the "universally unique" aspect by giving all
6354 // declarations semantically contained within an anonymous
6355 // namespace internal linkage.
6356
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006357 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006358 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006359 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006360 /* 'using' */ LBrace,
6361 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006362 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006363 /* identifier */ SourceLocation(),
6364 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006365 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006366 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006367 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006368 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006369 }
6370
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006371 ActOnDocumentableDecl(Namespc);
6372
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006373 // Although we could have an invalid decl (i.e. the namespace name is a
6374 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006375 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6376 // for the namespace has the declarations that showed up in that particular
6377 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006378 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006379 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006380}
6381
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006382/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6383/// is a namespace alias, returns the namespace it points to.
6384static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6385 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6386 return AD->getNamespace();
6387 return dyn_cast_or_null<NamespaceDecl>(D);
6388}
6389
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006390/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6391/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006392void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006393 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6394 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006395 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006396 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006397 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006398 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006399}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006400
John McCall384aff82010-08-25 07:42:41 +00006401CXXRecordDecl *Sema::getStdBadAlloc() const {
6402 return cast_or_null<CXXRecordDecl>(
6403 StdBadAlloc.get(Context.getExternalSource()));
6404}
6405
6406NamespaceDecl *Sema::getStdNamespace() const {
6407 return cast_or_null<NamespaceDecl>(
6408 StdNamespace.get(Context.getExternalSource()));
6409}
6410
Douglas Gregor66992202010-06-29 17:53:46 +00006411/// \brief Retrieve the special "std" namespace, which may require us to
6412/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006413NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006414 if (!StdNamespace) {
6415 // The "std" namespace has not yet been defined, so build one implicitly.
6416 StdNamespace = NamespaceDecl::Create(Context,
6417 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006418 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006419 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006420 &PP.getIdentifierTable().get("std"),
6421 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006422 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006423 }
6424
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006425 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006426}
6427
Sebastian Redl395e04d2012-01-17 22:49:33 +00006428bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006429 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006430 "Looking for std::initializer_list outside of C++.");
6431
6432 // We're looking for implicit instantiations of
6433 // template <typename E> class std::initializer_list.
6434
6435 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6436 return false;
6437
Sebastian Redl84760e32012-01-17 22:49:58 +00006438 ClassTemplateDecl *Template = 0;
6439 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006440
Sebastian Redl84760e32012-01-17 22:49:58 +00006441 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006442
Sebastian Redl84760e32012-01-17 22:49:58 +00006443 ClassTemplateSpecializationDecl *Specialization =
6444 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6445 if (!Specialization)
6446 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006447
Sebastian Redl84760e32012-01-17 22:49:58 +00006448 Template = Specialization->getSpecializedTemplate();
6449 Arguments = Specialization->getTemplateArgs().data();
6450 } else if (const TemplateSpecializationType *TST =
6451 Ty->getAs<TemplateSpecializationType>()) {
6452 Template = dyn_cast_or_null<ClassTemplateDecl>(
6453 TST->getTemplateName().getAsTemplateDecl());
6454 Arguments = TST->getArgs();
6455 }
6456 if (!Template)
6457 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006458
6459 if (!StdInitializerList) {
6460 // Haven't recognized std::initializer_list yet, maybe this is it.
6461 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6462 if (TemplateClass->getIdentifier() !=
6463 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006464 !getStdNamespace()->InEnclosingNamespaceSetOf(
6465 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006466 return false;
6467 // This is a template called std::initializer_list, but is it the right
6468 // template?
6469 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006470 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006471 return false;
6472 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6473 return false;
6474
6475 // It's the right template.
6476 StdInitializerList = Template;
6477 }
6478
6479 if (Template != StdInitializerList)
6480 return false;
6481
6482 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006483 if (Element)
6484 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006485 return true;
6486}
6487
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006488static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6489 NamespaceDecl *Std = S.getStdNamespace();
6490 if (!Std) {
6491 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6492 return 0;
6493 }
6494
6495 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6496 Loc, Sema::LookupOrdinaryName);
6497 if (!S.LookupQualifiedName(Result, Std)) {
6498 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6499 return 0;
6500 }
6501 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6502 if (!Template) {
6503 Result.suppressDiagnostics();
6504 // We found something weird. Complain about the first thing we found.
6505 NamedDecl *Found = *Result.begin();
6506 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6507 return 0;
6508 }
6509
6510 // We found some template called std::initializer_list. Now verify that it's
6511 // correct.
6512 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006513 if (Params->getMinRequiredArguments() != 1 ||
6514 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006515 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6516 return 0;
6517 }
6518
6519 return Template;
6520}
6521
6522QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6523 if (!StdInitializerList) {
6524 StdInitializerList = LookupStdInitializerList(*this, Loc);
6525 if (!StdInitializerList)
6526 return QualType();
6527 }
6528
6529 TemplateArgumentListInfo Args(Loc, Loc);
6530 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6531 Context.getTrivialTypeSourceInfo(Element,
6532 Loc)));
6533 return Context.getCanonicalType(
6534 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6535}
6536
Sebastian Redl98d36062012-01-17 22:50:14 +00006537bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6538 // C++ [dcl.init.list]p2:
6539 // A constructor is an initializer-list constructor if its first parameter
6540 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6541 // std::initializer_list<E> for some type E, and either there are no other
6542 // parameters or else all other parameters have default arguments.
6543 if (Ctor->getNumParams() < 1 ||
6544 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6545 return false;
6546
6547 QualType ArgType = Ctor->getParamDecl(0)->getType();
6548 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6549 ArgType = RT->getPointeeType().getUnqualifiedType();
6550
6551 return isStdInitializerList(ArgType, 0);
6552}
6553
Douglas Gregor9172aa62011-03-26 22:25:30 +00006554/// \brief Determine whether a using statement is in a context where it will be
6555/// apply in all contexts.
6556static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6557 switch (CurContext->getDeclKind()) {
6558 case Decl::TranslationUnit:
6559 return true;
6560 case Decl::LinkageSpec:
6561 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6562 default:
6563 return false;
6564 }
6565}
6566
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006567namespace {
6568
6569// Callback to only accept typo corrections that are namespaces.
6570class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6571 public:
6572 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6573 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6574 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6575 }
6576 return false;
6577 }
6578};
6579
6580}
6581
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006582static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6583 CXXScopeSpec &SS,
6584 SourceLocation IdentLoc,
6585 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006586 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006587 R.clear();
6588 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006589 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006590 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006591 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6592 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006593 if (DeclContext *DC = S.computeDeclContext(SS, false))
6594 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6595 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006596 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6597 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006598 else
6599 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6600 << Ident << CorrectedQuotedStr
6601 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006602
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006603 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6604 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006605
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006606 R.addDecl(Corrected.getCorrectionDecl());
6607 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006608 }
6609 return false;
6610}
6611
John McCalld226f652010-08-21 09:40:31 +00006612Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006613 SourceLocation UsingLoc,
6614 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006615 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006616 SourceLocation IdentLoc,
6617 IdentifierInfo *NamespcName,
6618 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006619 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6620 assert(NamespcName && "Invalid NamespcName.");
6621 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006622
6623 // This can only happen along a recovery path.
6624 while (S->getFlags() & Scope::TemplateParamScope)
6625 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006626 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006627
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006628 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006629 NestedNameSpecifier *Qualifier = 0;
6630 if (SS.isSet())
6631 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6632
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006633 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006634 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6635 LookupParsedName(R, S, &SS);
6636 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006637 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006638
Douglas Gregor66992202010-06-29 17:53:46 +00006639 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006640 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006641 // Allow "using namespace std;" or "using namespace ::std;" even if
6642 // "std" hasn't been defined yet, for GCC compatibility.
6643 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6644 NamespcName->isStr("std")) {
6645 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006646 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006647 R.resolveKind();
6648 }
6649 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006650 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006651 }
6652
John McCallf36e02d2009-10-09 21:13:30 +00006653 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006654 NamedDecl *Named = R.getFoundDecl();
6655 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6656 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006657 // C++ [namespace.udir]p1:
6658 // A using-directive specifies that the names in the nominated
6659 // namespace can be used in the scope in which the
6660 // using-directive appears after the using-directive. During
6661 // unqualified name lookup (3.4.1), the names appear as if they
6662 // were declared in the nearest enclosing namespace which
6663 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006664 // namespace. [Note: in this context, "contains" means "contains
6665 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006666
6667 // Find enclosing context containing both using-directive and
6668 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006669 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006670 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6671 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6672 CommonAncestor = CommonAncestor->getParent();
6673
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006674 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006675 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006676 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006677
Douglas Gregor9172aa62011-03-26 22:25:30 +00006678 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006679 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006680 Diag(IdentLoc, diag::warn_using_directive_in_header);
6681 }
6682
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006683 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006684 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006685 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006686 }
6687
Richard Smith6b3d3e52013-02-20 19:22:51 +00006688 if (UDir)
6689 ProcessDeclAttributeList(S, UDir, AttrList);
6690
John McCalld226f652010-08-21 09:40:31 +00006691 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006692}
6693
6694void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006695 // If the scope has an associated entity and the using directive is at
6696 // namespace or translation unit scope, add the UsingDirectiveDecl into
6697 // its lookup structure so qualified name lookup can find it.
6698 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6699 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006700 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006701 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006702 // Otherwise, it is at block sope. The using-directives will affect lookup
6703 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006704 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006705}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006706
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006707
John McCalld226f652010-08-21 09:40:31 +00006708Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006709 AccessSpecifier AS,
6710 bool HasUsingKeyword,
6711 SourceLocation UsingLoc,
6712 CXXScopeSpec &SS,
6713 UnqualifiedId &Name,
6714 AttributeList *AttrList,
6715 bool IsTypeName,
6716 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006717 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006718
Douglas Gregor12c118a2009-11-04 16:30:06 +00006719 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006720 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006721 case UnqualifiedId::IK_Identifier:
6722 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006723 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006724 case UnqualifiedId::IK_ConversionFunctionId:
6725 break;
6726
6727 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006728 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006729 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006730 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006731 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006732 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006733 diag::err_using_decl_constructor)
6734 << SS.getRange();
6735
Richard Smith80ad52f2013-01-02 11:42:31 +00006736 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006737
John McCalld226f652010-08-21 09:40:31 +00006738 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006739
6740 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006741 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006742 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006743 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006744
6745 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006746 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006747 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006748 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006749 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006750
6751 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6752 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006753 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006754 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006755
Richard Smith07b0fdc2013-03-18 21:12:30 +00006756 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006757 // TODO: store that the declaration was written without 'using' and
6758 // talk about access decls instead of using decls in the
6759 // diagnostics.
6760 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006761 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006762
6763 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006764 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006765 }
6766
Douglas Gregor56c04582010-12-16 00:46:58 +00006767 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6768 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6769 return 0;
6770
John McCall9488ea12009-11-17 05:59:44 +00006771 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006772 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006773 /* IsInstantiation */ false,
6774 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006775 if (UD)
6776 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006777
John McCalld226f652010-08-21 09:40:31 +00006778 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006779}
6780
Douglas Gregor09acc982010-07-07 23:08:52 +00006781/// \brief Determine whether a using declaration considers the given
6782/// declarations as "equivalent", e.g., if they are redeclarations of
6783/// the same entity or are both typedefs of the same type.
6784static bool
6785IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6786 bool &SuppressRedeclaration) {
6787 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6788 SuppressRedeclaration = false;
6789 return true;
6790 }
6791
Richard Smith162e1c12011-04-15 14:24:37 +00006792 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6793 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006794 SuppressRedeclaration = true;
6795 return Context.hasSameType(TD1->getUnderlyingType(),
6796 TD2->getUnderlyingType());
6797 }
6798
6799 return false;
6800}
6801
6802
John McCall9f54ad42009-12-10 09:41:52 +00006803/// Determines whether to create a using shadow decl for a particular
6804/// decl, given the set of decls existing prior to this using lookup.
6805bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6806 const LookupResult &Previous) {
6807 // Diagnose finding a decl which is not from a base class of the
6808 // current class. We do this now because there are cases where this
6809 // function will silently decide not to build a shadow decl, which
6810 // will pre-empt further diagnostics.
6811 //
6812 // We don't need to do this in C++0x because we do the check once on
6813 // the qualifier.
6814 //
6815 // FIXME: diagnose the following if we care enough:
6816 // struct A { int foo; };
6817 // struct B : A { using A::foo; };
6818 // template <class T> struct C : A {};
6819 // template <class T> struct D : C<T> { using B::foo; } // <---
6820 // This is invalid (during instantiation) in C++03 because B::foo
6821 // resolves to the using decl in B, which is not a base class of D<T>.
6822 // We can't diagnose it immediately because C<T> is an unknown
6823 // specialization. The UsingShadowDecl in D<T> then points directly
6824 // to A::foo, which will look well-formed when we instantiate.
6825 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006826 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006827 DeclContext *OrigDC = Orig->getDeclContext();
6828
6829 // Handle enums and anonymous structs.
6830 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6831 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6832 while (OrigRec->isAnonymousStructOrUnion())
6833 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6834
6835 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6836 if (OrigDC == CurContext) {
6837 Diag(Using->getLocation(),
6838 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006839 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006840 Diag(Orig->getLocation(), diag::note_using_decl_target);
6841 return true;
6842 }
6843
Douglas Gregordc355712011-02-25 00:36:19 +00006844 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006845 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006846 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006847 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006848 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006849 Diag(Orig->getLocation(), diag::note_using_decl_target);
6850 return true;
6851 }
6852 }
6853
6854 if (Previous.empty()) return false;
6855
6856 NamedDecl *Target = Orig;
6857 if (isa<UsingShadowDecl>(Target))
6858 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6859
John McCalld7533ec2009-12-11 02:33:26 +00006860 // If the target happens to be one of the previous declarations, we
6861 // don't have a conflict.
6862 //
6863 // FIXME: but we might be increasing its access, in which case we
6864 // should redeclare it.
6865 NamedDecl *NonTag = 0, *Tag = 0;
6866 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6867 I != E; ++I) {
6868 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006869 bool Result;
6870 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6871 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006872
6873 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6874 }
6875
John McCall9f54ad42009-12-10 09:41:52 +00006876 if (Target->isFunctionOrFunctionTemplate()) {
6877 FunctionDecl *FD;
6878 if (isa<FunctionTemplateDecl>(Target))
6879 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6880 else
6881 FD = cast<FunctionDecl>(Target);
6882
6883 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006884 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006885 case Ovl_Overload:
6886 return false;
6887
6888 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006889 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006890 break;
6891
6892 // We found a decl with the exact signature.
6893 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006894 // If we're in a record, we want to hide the target, so we
6895 // return true (without a diagnostic) to tell the caller not to
6896 // build a shadow decl.
6897 if (CurContext->isRecord())
6898 return true;
6899
6900 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006901 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006902 break;
6903 }
6904
6905 Diag(Target->getLocation(), diag::note_using_decl_target);
6906 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6907 return true;
6908 }
6909
6910 // Target is not a function.
6911
John McCall9f54ad42009-12-10 09:41:52 +00006912 if (isa<TagDecl>(Target)) {
6913 // No conflict between a tag and a non-tag.
6914 if (!Tag) return false;
6915
John McCall41ce66f2009-12-10 19:51:03 +00006916 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006917 Diag(Target->getLocation(), diag::note_using_decl_target);
6918 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6919 return true;
6920 }
6921
6922 // No conflict between a tag and a non-tag.
6923 if (!NonTag) return false;
6924
John McCall41ce66f2009-12-10 19:51:03 +00006925 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006926 Diag(Target->getLocation(), diag::note_using_decl_target);
6927 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6928 return true;
6929}
6930
John McCall9488ea12009-11-17 05:59:44 +00006931/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006932UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006933 UsingDecl *UD,
6934 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006935
6936 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006937 NamedDecl *Target = Orig;
6938 if (isa<UsingShadowDecl>(Target)) {
6939 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6940 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006941 }
6942
6943 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006944 = UsingShadowDecl::Create(Context, CurContext,
6945 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006946 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006947
6948 Shadow->setAccess(UD->getAccess());
6949 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6950 Shadow->setInvalidDecl();
6951
John McCall9488ea12009-11-17 05:59:44 +00006952 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006953 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006954 else
John McCall604e7f12009-12-08 07:46:18 +00006955 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006956
John McCall604e7f12009-12-08 07:46:18 +00006957
John McCall9f54ad42009-12-10 09:41:52 +00006958 return Shadow;
6959}
John McCall604e7f12009-12-08 07:46:18 +00006960
John McCall9f54ad42009-12-10 09:41:52 +00006961/// Hides a using shadow declaration. This is required by the current
6962/// using-decl implementation when a resolvable using declaration in a
6963/// class is followed by a declaration which would hide or override
6964/// one or more of the using decl's targets; for example:
6965///
6966/// struct Base { void foo(int); };
6967/// struct Derived : Base {
6968/// using Base::foo;
6969/// void foo(int);
6970/// };
6971///
6972/// The governing language is C++03 [namespace.udecl]p12:
6973///
6974/// When a using-declaration brings names from a base class into a
6975/// derived class scope, member functions in the derived class
6976/// override and/or hide member functions with the same name and
6977/// parameter types in a base class (rather than conflicting).
6978///
6979/// There are two ways to implement this:
6980/// (1) optimistically create shadow decls when they're not hidden
6981/// by existing declarations, or
6982/// (2) don't create any shadow decls (or at least don't make them
6983/// visible) until we've fully parsed/instantiated the class.
6984/// The problem with (1) is that we might have to retroactively remove
6985/// a shadow decl, which requires several O(n) operations because the
6986/// decl structures are (very reasonably) not designed for removal.
6987/// (2) avoids this but is very fiddly and phase-dependent.
6988void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006989 if (Shadow->getDeclName().getNameKind() ==
6990 DeclarationName::CXXConversionFunctionName)
6991 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6992
John McCall9f54ad42009-12-10 09:41:52 +00006993 // Remove it from the DeclContext...
6994 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006995
John McCall9f54ad42009-12-10 09:41:52 +00006996 // ...and the scope, if applicable...
6997 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006998 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006999 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007000 }
7001
John McCall9f54ad42009-12-10 09:41:52 +00007002 // ...and the using decl.
7003 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7004
7005 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007006 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007007}
7008
John McCall7ba107a2009-11-18 02:36:19 +00007009/// Builds a using declaration.
7010///
7011/// \param IsInstantiation - Whether this call arises from an
7012/// instantiation of an unresolved using declaration. We treat
7013/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007014NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7015 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007016 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007017 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007018 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007019 bool IsInstantiation,
7020 bool IsTypeName,
7021 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007022 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007023 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007024 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007025
Anders Carlsson550b14b2009-08-28 05:49:21 +00007026 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007027
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007028 if (SS.isEmpty()) {
7029 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007030 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007031 }
Mike Stump1eb44332009-09-09 15:08:12 +00007032
John McCall9f54ad42009-12-10 09:41:52 +00007033 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007034 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007035 ForRedeclaration);
7036 Previous.setHideTags(false);
7037 if (S) {
7038 LookupName(Previous, S);
7039
7040 // It is really dumb that we have to do this.
7041 LookupResult::Filter F = Previous.makeFilter();
7042 while (F.hasNext()) {
7043 NamedDecl *D = F.next();
7044 if (!isDeclInScope(D, CurContext, S))
7045 F.erase();
7046 }
7047 F.done();
7048 } else {
7049 assert(IsInstantiation && "no scope in non-instantiation");
7050 assert(CurContext->isRecord() && "scope not record in instantiation");
7051 LookupQualifiedName(Previous, CurContext);
7052 }
7053
John McCall9f54ad42009-12-10 09:41:52 +00007054 // Check for invalid redeclarations.
7055 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7056 return 0;
7057
7058 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007059 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7060 return 0;
7061
John McCallaf8e6ed2009-11-12 03:15:40 +00007062 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007063 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007064 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007065 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00007066 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00007067 // FIXME: not all declaration name kinds are legal here
7068 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7069 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007070 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007071 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007072 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007073 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7074 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007075 }
John McCalled976492009-12-04 22:46:56 +00007076 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007077 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7078 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007079 }
John McCalled976492009-12-04 22:46:56 +00007080 D->setAccess(AS);
7081 CurContext->addDecl(D);
7082
7083 if (!LookupContext) return D;
7084 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007085
John McCall77bb1aa2010-05-01 00:40:08 +00007086 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007087 UD->setInvalidDecl();
7088 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007089 }
7090
Richard Smithc5a89a12012-04-02 01:30:27 +00007091 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007092 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007093 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007094 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007095 return UD;
7096 }
7097
7098 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007099
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007100 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007101
John McCall604e7f12009-12-08 07:46:18 +00007102 // Unlike most lookups, we don't always want to hide tag
7103 // declarations: tag names are visible through the using declaration
7104 // even if hidden by ordinary names, *except* in a dependent context
7105 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007106 if (!IsInstantiation)
7107 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007108
John McCallb9abd8722012-04-07 03:04:20 +00007109 // For the purposes of this lookup, we have a base object type
7110 // equal to that of the current context.
7111 if (CurContext->isRecord()) {
7112 R.setBaseObjectType(
7113 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7114 }
7115
John McCalla24dc2e2009-11-17 02:14:36 +00007116 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007117
John McCallf36e02d2009-10-09 21:13:30 +00007118 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00007119 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007120 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007121 UD->setInvalidDecl();
7122 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007123 }
7124
John McCalled976492009-12-04 22:46:56 +00007125 if (R.isAmbiguous()) {
7126 UD->setInvalidDecl();
7127 return UD;
7128 }
Mike Stump1eb44332009-09-09 15:08:12 +00007129
John McCall7ba107a2009-11-18 02:36:19 +00007130 if (IsTypeName) {
7131 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007132 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007133 Diag(IdentLoc, diag::err_using_typename_non_type);
7134 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7135 Diag((*I)->getUnderlyingDecl()->getLocation(),
7136 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007137 UD->setInvalidDecl();
7138 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007139 }
7140 } else {
7141 // If we asked for a non-typename and we got a type, error out,
7142 // but only if this is an instantiation of an unresolved using
7143 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007144 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007145 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7146 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007147 UD->setInvalidDecl();
7148 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007149 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007150 }
7151
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007152 // C++0x N2914 [namespace.udecl]p6:
7153 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007154 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007155 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7156 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007157 UD->setInvalidDecl();
7158 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007159 }
Mike Stump1eb44332009-09-09 15:08:12 +00007160
John McCall9f54ad42009-12-10 09:41:52 +00007161 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7162 if (!CheckUsingShadowDecl(UD, *I, Previous))
7163 BuildUsingShadowDecl(S, UD, *I);
7164 }
John McCall9488ea12009-11-17 05:59:44 +00007165
7166 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007167}
7168
Sebastian Redlf677ea32011-02-05 19:23:19 +00007169/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007170bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7171 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007172
Douglas Gregordc355712011-02-25 00:36:19 +00007173 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007174 assert(SourceType &&
7175 "Using decl naming constructor doesn't have type in scope spec.");
7176 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7177
7178 // Check whether the named type is a direct base class.
7179 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7180 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7181 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7182 BaseIt != BaseE; ++BaseIt) {
7183 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7184 if (CanonicalSourceType == BaseType)
7185 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007186 if (BaseIt->getType()->isDependentType())
7187 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007188 }
7189
7190 if (BaseIt == BaseE) {
7191 // Did not find SourceType in the bases.
7192 Diag(UD->getUsingLocation(),
7193 diag::err_using_decl_constructor_not_in_direct_base)
7194 << UD->getNameInfo().getSourceRange()
7195 << QualType(SourceType, 0) << TargetClass;
7196 return true;
7197 }
7198
Richard Smithc5a89a12012-04-02 01:30:27 +00007199 if (!CurContext->isDependentContext())
7200 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007201
7202 return false;
7203}
7204
John McCall9f54ad42009-12-10 09:41:52 +00007205/// Checks that the given using declaration is not an invalid
7206/// redeclaration. Note that this is checking only for the using decl
7207/// itself, not for any ill-formedness among the UsingShadowDecls.
7208bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7209 bool isTypeName,
7210 const CXXScopeSpec &SS,
7211 SourceLocation NameLoc,
7212 const LookupResult &Prev) {
7213 // C++03 [namespace.udecl]p8:
7214 // C++0x [namespace.udecl]p10:
7215 // A using-declaration is a declaration and can therefore be used
7216 // repeatedly where (and only where) multiple declarations are
7217 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007218 //
John McCall8a726212010-11-29 18:01:58 +00007219 // That's in non-member contexts.
7220 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007221 return false;
7222
7223 NestedNameSpecifier *Qual
7224 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7225
7226 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7227 NamedDecl *D = *I;
7228
7229 bool DTypename;
7230 NestedNameSpecifier *DQual;
7231 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7232 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007233 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007234 } else if (UnresolvedUsingValueDecl *UD
7235 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7236 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007237 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007238 } else if (UnresolvedUsingTypenameDecl *UD
7239 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7240 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007241 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007242 } else continue;
7243
7244 // using decls differ if one says 'typename' and the other doesn't.
7245 // FIXME: non-dependent using decls?
7246 if (isTypeName != DTypename) continue;
7247
7248 // using decls differ if they name different scopes (but note that
7249 // template instantiation can cause this check to trigger when it
7250 // didn't before instantiation).
7251 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7252 Context.getCanonicalNestedNameSpecifier(DQual))
7253 continue;
7254
7255 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007256 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007257 return true;
7258 }
7259
7260 return false;
7261}
7262
John McCall604e7f12009-12-08 07:46:18 +00007263
John McCalled976492009-12-04 22:46:56 +00007264/// Checks that the given nested-name qualifier used in a using decl
7265/// in the current context is appropriately related to the current
7266/// scope. If an error is found, diagnoses it and returns true.
7267bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7268 const CXXScopeSpec &SS,
7269 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007270 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007271
John McCall604e7f12009-12-08 07:46:18 +00007272 if (!CurContext->isRecord()) {
7273 // C++03 [namespace.udecl]p3:
7274 // C++0x [namespace.udecl]p8:
7275 // A using-declaration for a class member shall be a member-declaration.
7276
7277 // If we weren't able to compute a valid scope, it must be a
7278 // dependent class scope.
7279 if (!NamedContext || NamedContext->isRecord()) {
7280 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7281 << SS.getRange();
7282 return true;
7283 }
7284
7285 // Otherwise, everything is known to be fine.
7286 return false;
7287 }
7288
7289 // The current scope is a record.
7290
7291 // If the named context is dependent, we can't decide much.
7292 if (!NamedContext) {
7293 // FIXME: in C++0x, we can diagnose if we can prove that the
7294 // nested-name-specifier does not refer to a base class, which is
7295 // still possible in some cases.
7296
7297 // Otherwise we have to conservatively report that things might be
7298 // okay.
7299 return false;
7300 }
7301
7302 if (!NamedContext->isRecord()) {
7303 // Ideally this would point at the last name in the specifier,
7304 // but we don't have that level of source info.
7305 Diag(SS.getRange().getBegin(),
7306 diag::err_using_decl_nested_name_specifier_is_not_class)
7307 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7308 return true;
7309 }
7310
Douglas Gregor6fb07292010-12-21 07:41:49 +00007311 if (!NamedContext->isDependentContext() &&
7312 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7313 return true;
7314
Richard Smith80ad52f2013-01-02 11:42:31 +00007315 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007316 // C++0x [namespace.udecl]p3:
7317 // In a using-declaration used as a member-declaration, the
7318 // nested-name-specifier shall name a base class of the class
7319 // being defined.
7320
7321 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7322 cast<CXXRecordDecl>(NamedContext))) {
7323 if (CurContext == NamedContext) {
7324 Diag(NameLoc,
7325 diag::err_using_decl_nested_name_specifier_is_current_class)
7326 << SS.getRange();
7327 return true;
7328 }
7329
7330 Diag(SS.getRange().getBegin(),
7331 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7332 << (NestedNameSpecifier*) SS.getScopeRep()
7333 << cast<CXXRecordDecl>(CurContext)
7334 << SS.getRange();
7335 return true;
7336 }
7337
7338 return false;
7339 }
7340
7341 // C++03 [namespace.udecl]p4:
7342 // A using-declaration used as a member-declaration shall refer
7343 // to a member of a base class of the class being defined [etc.].
7344
7345 // Salient point: SS doesn't have to name a base class as long as
7346 // lookup only finds members from base classes. Therefore we can
7347 // diagnose here only if we can prove that that can't happen,
7348 // i.e. if the class hierarchies provably don't intersect.
7349
7350 // TODO: it would be nice if "definitely valid" results were cached
7351 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7352 // need to be repeated.
7353
7354 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007355 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007356
7357 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7358 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7359 Data->Bases.insert(Base);
7360 return true;
7361 }
7362
7363 bool hasDependentBases(const CXXRecordDecl *Class) {
7364 return !Class->forallBases(collect, this);
7365 }
7366
7367 /// Returns true if the base is dependent or is one of the
7368 /// accumulated base classes.
7369 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7370 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7371 return !Data->Bases.count(Base);
7372 }
7373
7374 bool mightShareBases(const CXXRecordDecl *Class) {
7375 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7376 }
7377 };
7378
7379 UserData Data;
7380
7381 // Returns false if we find a dependent base.
7382 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7383 return false;
7384
7385 // Returns false if the class has a dependent base or if it or one
7386 // of its bases is present in the base set of the current context.
7387 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7388 return false;
7389
7390 Diag(SS.getRange().getBegin(),
7391 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7392 << (NestedNameSpecifier*) SS.getScopeRep()
7393 << cast<CXXRecordDecl>(CurContext)
7394 << SS.getRange();
7395
7396 return true;
John McCalled976492009-12-04 22:46:56 +00007397}
7398
Richard Smith162e1c12011-04-15 14:24:37 +00007399Decl *Sema::ActOnAliasDeclaration(Scope *S,
7400 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007401 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007402 SourceLocation UsingLoc,
7403 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007404 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007405 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007406 // Skip up to the relevant declaration scope.
7407 while (S->getFlags() & Scope::TemplateParamScope)
7408 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007409 assert((S->getFlags() & Scope::DeclScope) &&
7410 "got alias-declaration outside of declaration scope");
7411
7412 if (Type.isInvalid())
7413 return 0;
7414
7415 bool Invalid = false;
7416 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7417 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007418 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007419
7420 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7421 return 0;
7422
7423 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007424 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007425 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007426 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7427 TInfo->getTypeLoc().getBeginLoc());
7428 }
Richard Smith162e1c12011-04-15 14:24:37 +00007429
7430 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7431 LookupName(Previous, S);
7432
7433 // Warn about shadowing the name of a template parameter.
7434 if (Previous.isSingleResult() &&
7435 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007436 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007437 Previous.clear();
7438 }
7439
7440 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7441 "name in alias declaration must be an identifier");
7442 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7443 Name.StartLocation,
7444 Name.Identifier, TInfo);
7445
7446 NewTD->setAccess(AS);
7447
7448 if (Invalid)
7449 NewTD->setInvalidDecl();
7450
Richard Smith6b3d3e52013-02-20 19:22:51 +00007451 ProcessDeclAttributeList(S, NewTD, AttrList);
7452
Richard Smith3e4c6c42011-05-05 21:57:07 +00007453 CheckTypedefForVariablyModifiedType(S, NewTD);
7454 Invalid |= NewTD->isInvalidDecl();
7455
Richard Smith162e1c12011-04-15 14:24:37 +00007456 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007457
7458 NamedDecl *NewND;
7459 if (TemplateParamLists.size()) {
7460 TypeAliasTemplateDecl *OldDecl = 0;
7461 TemplateParameterList *OldTemplateParams = 0;
7462
7463 if (TemplateParamLists.size() != 1) {
7464 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007465 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7466 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007467 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007468 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007469
7470 // Only consider previous declarations in the same scope.
7471 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7472 /*ExplicitInstantiationOrSpecialization*/false);
7473 if (!Previous.empty()) {
7474 Redeclaration = true;
7475
7476 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7477 if (!OldDecl && !Invalid) {
7478 Diag(UsingLoc, diag::err_redefinition_different_kind)
7479 << Name.Identifier;
7480
7481 NamedDecl *OldD = Previous.getRepresentativeDecl();
7482 if (OldD->getLocation().isValid())
7483 Diag(OldD->getLocation(), diag::note_previous_definition);
7484
7485 Invalid = true;
7486 }
7487
7488 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7489 if (TemplateParameterListsAreEqual(TemplateParams,
7490 OldDecl->getTemplateParameters(),
7491 /*Complain=*/true,
7492 TPL_TemplateMatch))
7493 OldTemplateParams = OldDecl->getTemplateParameters();
7494 else
7495 Invalid = true;
7496
7497 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7498 if (!Invalid &&
7499 !Context.hasSameType(OldTD->getUnderlyingType(),
7500 NewTD->getUnderlyingType())) {
7501 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7502 // but we can't reasonably accept it.
7503 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7504 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7505 if (OldTD->getLocation().isValid())
7506 Diag(OldTD->getLocation(), diag::note_previous_definition);
7507 Invalid = true;
7508 }
7509 }
7510 }
7511
7512 // Merge any previous default template arguments into our parameters,
7513 // and check the parameter list.
7514 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7515 TPC_TypeAliasTemplate))
7516 return 0;
7517
7518 TypeAliasTemplateDecl *NewDecl =
7519 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7520 Name.Identifier, TemplateParams,
7521 NewTD);
7522
7523 NewDecl->setAccess(AS);
7524
7525 if (Invalid)
7526 NewDecl->setInvalidDecl();
7527 else if (OldDecl)
7528 NewDecl->setPreviousDeclaration(OldDecl);
7529
7530 NewND = NewDecl;
7531 } else {
7532 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7533 NewND = NewTD;
7534 }
Richard Smith162e1c12011-04-15 14:24:37 +00007535
7536 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007537 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007538
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007539 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007540 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007541}
7542
John McCalld226f652010-08-21 09:40:31 +00007543Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007544 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007545 SourceLocation AliasLoc,
7546 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007547 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007548 SourceLocation IdentLoc,
7549 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007550
Anders Carlsson81c85c42009-03-28 23:53:49 +00007551 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007552 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7553 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007554
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007555 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007556 NamedDecl *PrevDecl
7557 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7558 ForRedeclaration);
7559 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7560 PrevDecl = 0;
7561
7562 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007563 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007564 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007565 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007566 // FIXME: At some point, we'll want to create the (redundant)
7567 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007568 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007569 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007570 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007571 }
Mike Stump1eb44332009-09-09 15:08:12 +00007572
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007573 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7574 diag::err_redefinition_different_kind;
7575 Diag(AliasLoc, DiagID) << Alias;
7576 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007577 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007578 }
7579
John McCalla24dc2e2009-11-17 02:14:36 +00007580 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007581 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007582
John McCallf36e02d2009-10-09 21:13:30 +00007583 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007584 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007585 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007586 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007587 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007588 }
Mike Stump1eb44332009-09-09 15:08:12 +00007589
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007590 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007591 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007592 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007593 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007594
John McCall3dbd3d52010-02-16 06:53:13 +00007595 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007596 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007597}
7598
Sean Hunt001cad92011-05-10 00:49:42 +00007599Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007600Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7601 CXXMethodDecl *MD) {
7602 CXXRecordDecl *ClassDecl = MD->getParent();
7603
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007604 // C++ [except.spec]p14:
7605 // An implicitly declared special member function (Clause 12) shall have an
7606 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007607 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007608 if (ClassDecl->isInvalidDecl())
7609 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007610
Sebastian Redl60618fa2011-03-12 11:50:43 +00007611 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007612 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7613 BEnd = ClassDecl->bases_end();
7614 B != BEnd; ++B) {
7615 if (B->isVirtual()) // Handled below.
7616 continue;
7617
Douglas Gregor18274032010-07-03 00:47:00 +00007618 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7619 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007620 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7621 // If this is a deleted function, add it anyway. This might be conformant
7622 // with the standard. This might not. I'm not sure. It might not matter.
7623 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007624 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007625 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007626 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007627
7628 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007629 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7630 BEnd = ClassDecl->vbases_end();
7631 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007632 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7633 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007634 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7635 // If this is a deleted function, add it anyway. This might be conformant
7636 // with the standard. This might not. I'm not sure. It might not matter.
7637 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007638 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007639 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007640 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007641
7642 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007643 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7644 FEnd = ClassDecl->field_end();
7645 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007646 if (F->hasInClassInitializer()) {
7647 if (Expr *E = F->getInClassInitializer())
7648 ExceptSpec.CalledExpr(E);
7649 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007650 // DR1351:
7651 // If the brace-or-equal-initializer of a non-static data member
7652 // invokes a defaulted default constructor of its class or of an
7653 // enclosing class in a potentially evaluated subexpression, the
7654 // program is ill-formed.
7655 //
7656 // This resolution is unworkable: the exception specification of the
7657 // default constructor can be needed in an unevaluated context, in
7658 // particular, in the operand of a noexcept-expression, and we can be
7659 // unable to compute an exception specification for an enclosed class.
7660 //
7661 // We do not allow an in-class initializer to require the evaluation
7662 // of the exception specification for any in-class initializer whose
7663 // definition is not lexically complete.
7664 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007665 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007666 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007667 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7668 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7669 // If this is a deleted function, add it anyway. This might be conformant
7670 // with the standard. This might not. I'm not sure. It might not matter.
7671 // In particular, the problem is that this function never gets called. It
7672 // might just be ill-formed because this function attempts to refer to
7673 // a deleted function here.
7674 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007675 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007676 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007677 }
John McCalle23cf432010-12-14 08:05:40 +00007678
Sean Hunt001cad92011-05-10 00:49:42 +00007679 return ExceptSpec;
7680}
7681
Richard Smith07b0fdc2013-03-18 21:12:30 +00007682Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007683Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7684 CXXRecordDecl *ClassDecl = CD->getParent();
7685
7686 // C++ [except.spec]p14:
7687 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007688 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007689 if (ClassDecl->isInvalidDecl())
7690 return ExceptSpec;
7691
7692 // Inherited constructor.
7693 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7694 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7695 // FIXME: Copying or moving the parameters could add extra exceptions to the
7696 // set, as could the default arguments for the inherited constructor. This
7697 // will be addressed when we implement the resolution of core issue 1351.
7698 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7699
7700 // Direct base-class constructors.
7701 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7702 BEnd = ClassDecl->bases_end();
7703 B != BEnd; ++B) {
7704 if (B->isVirtual()) // Handled below.
7705 continue;
7706
7707 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7708 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7709 if (BaseClassDecl == InheritedDecl)
7710 continue;
7711 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7712 if (Constructor)
7713 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7714 }
7715 }
7716
7717 // Virtual base-class constructors.
7718 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7719 BEnd = ClassDecl->vbases_end();
7720 B != BEnd; ++B) {
7721 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7722 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7723 if (BaseClassDecl == InheritedDecl)
7724 continue;
7725 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7726 if (Constructor)
7727 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7728 }
7729 }
7730
7731 // Field constructors.
7732 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7733 FEnd = ClassDecl->field_end();
7734 F != FEnd; ++F) {
7735 if (F->hasInClassInitializer()) {
7736 if (Expr *E = F->getInClassInitializer())
7737 ExceptSpec.CalledExpr(E);
7738 else if (!F->isInvalidDecl())
7739 Diag(CD->getLocation(),
7740 diag::err_in_class_initializer_references_def_ctor) << CD;
7741 } else if (const RecordType *RecordTy
7742 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7743 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7744 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7745 if (Constructor)
7746 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7747 }
7748 }
7749
Richard Smith07b0fdc2013-03-18 21:12:30 +00007750 return ExceptSpec;
7751}
7752
Richard Smithafb49182012-11-29 01:34:07 +00007753namespace {
7754/// RAII object to register a special member as being currently declared.
7755struct DeclaringSpecialMember {
7756 Sema &S;
7757 Sema::SpecialMemberDecl D;
7758 bool WasAlreadyBeingDeclared;
7759
7760 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7761 : S(S), D(RD, CSM) {
7762 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7763 if (WasAlreadyBeingDeclared)
7764 // This almost never happens, but if it does, ensure that our cache
7765 // doesn't contain a stale result.
7766 S.SpecialMemberCache.clear();
7767
7768 // FIXME: Register a note to be produced if we encounter an error while
7769 // declaring the special member.
7770 }
7771 ~DeclaringSpecialMember() {
7772 if (!WasAlreadyBeingDeclared)
7773 S.SpecialMembersBeingDeclared.erase(D);
7774 }
7775
7776 /// \brief Are we already trying to declare this special member?
7777 bool isAlreadyBeingDeclared() const {
7778 return WasAlreadyBeingDeclared;
7779 }
7780};
7781}
7782
Sean Hunt001cad92011-05-10 00:49:42 +00007783CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7784 CXXRecordDecl *ClassDecl) {
7785 // C++ [class.ctor]p5:
7786 // A default constructor for a class X is a constructor of class X
7787 // that can be called without an argument. If there is no
7788 // user-declared constructor for class X, a default constructor is
7789 // implicitly declared. An implicitly-declared default constructor
7790 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007791 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007792 "Should not build implicit default constructor!");
7793
Richard Smithafb49182012-11-29 01:34:07 +00007794 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7795 if (DSM.isAlreadyBeingDeclared())
7796 return 0;
7797
Richard Smith7756afa2012-06-10 05:43:50 +00007798 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7799 CXXDefaultConstructor,
7800 false);
7801
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007802 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007803 CanQualType ClassType
7804 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007805 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007806 DeclarationName Name
7807 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007808 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007809 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007810 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007811 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007812 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007813 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007814 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007815 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007816
7817 // Build an exception specification pointing back at this constructor.
7818 FunctionProtoType::ExtProtoInfo EPI;
7819 EPI.ExceptionSpecType = EST_Unevaluated;
7820 EPI.ExceptionSpecDecl = DefaultCon;
Dmitri Gribenko55431692013-05-05 00:41:58 +00007821 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007822
Richard Smithbc2a35d2012-12-08 08:32:28 +00007823 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7824 // constructors is easy to compute.
7825 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7826
7827 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007828 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007829
Douglas Gregor18274032010-07-03 00:47:00 +00007830 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007831 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007832
Douglas Gregor23c94db2010-07-02 17:43:08 +00007833 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007834 PushOnScopeChains(DefaultCon, S, false);
7835 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007836
Douglas Gregor32df23e2010-07-01 22:02:46 +00007837 return DefaultCon;
7838}
7839
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007840void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7841 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007842 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007843 !Constructor->doesThisDeclarationHaveABody() &&
7844 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007845 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007846
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007847 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007848 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007849
Eli Friedman9a14db32012-10-18 20:14:08 +00007850 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007851 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007852 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007853 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007854 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007855 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007856 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007857 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007858 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007859
7860 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007861 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007862
7863 Constructor->setUsed();
7864 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007865
7866 if (ASTMutationListener *L = getASTMutationListener()) {
7867 L->CompletedImplicitDefinition(Constructor);
7868 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007869}
7870
Richard Smith7a614d82011-06-11 17:19:42 +00007871void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007872 // Check that any explicitly-defaulted methods have exception specifications
7873 // compatible with their implicit exception specifications.
7874 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007875}
7876
Richard Smith4841ca52013-04-10 05:48:59 +00007877namespace {
7878/// Information on inheriting constructors to declare.
7879class InheritingConstructorInfo {
7880public:
7881 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7882 : SemaRef(SemaRef), Derived(Derived) {
7883 // Mark the constructors that we already have in the derived class.
7884 //
7885 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7886 // unless there is a user-declared constructor with the same signature in
7887 // the class where the using-declaration appears.
7888 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7889 }
7890
7891 void inheritAll(CXXRecordDecl *RD) {
7892 visitAll(RD, &InheritingConstructorInfo::inherit);
7893 }
7894
7895private:
7896 /// Information about an inheriting constructor.
7897 struct InheritingConstructor {
7898 InheritingConstructor()
7899 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7900
7901 /// If \c true, a constructor with this signature is already declared
7902 /// in the derived class.
7903 bool DeclaredInDerived;
7904
7905 /// The constructor which is inherited.
7906 const CXXConstructorDecl *BaseCtor;
7907
7908 /// The derived constructor we declared.
7909 CXXConstructorDecl *DerivedCtor;
7910 };
7911
7912 /// Inheriting constructors with a given canonical type. There can be at
7913 /// most one such non-template constructor, and any number of templated
7914 /// constructors.
7915 struct InheritingConstructorsForType {
7916 InheritingConstructor NonTemplate;
7917 llvm::SmallVector<
7918 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7919
7920 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7921 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7922 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7923 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7924 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7925 false, S.TPL_TemplateMatch))
7926 return Templates[I].second;
7927 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7928 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007929 }
Richard Smith4841ca52013-04-10 05:48:59 +00007930
7931 return NonTemplate;
7932 }
7933 };
7934
7935 /// Get or create the inheriting constructor record for a constructor.
7936 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7937 QualType CtorType) {
7938 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7939 .getEntry(SemaRef, Ctor);
7940 }
7941
7942 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7943
7944 /// Process all constructors for a class.
7945 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7946 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7947 CtorE = RD->ctor_end();
7948 CtorIt != CtorE; ++CtorIt)
7949 (this->*Callback)(*CtorIt);
7950 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7951 I(RD->decls_begin()), E(RD->decls_end());
7952 I != E; ++I) {
7953 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7954 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7955 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007956 }
7957 }
Richard Smith4841ca52013-04-10 05:48:59 +00007958
7959 /// Note that a constructor (or constructor template) was declared in Derived.
7960 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7961 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7962 }
7963
7964 /// Inherit a single constructor.
7965 void inherit(const CXXConstructorDecl *Ctor) {
7966 const FunctionProtoType *CtorType =
7967 Ctor->getType()->castAs<FunctionProtoType>();
7968 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7969 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7970
7971 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7972
7973 // Core issue (no number yet): the ellipsis is always discarded.
7974 if (EPI.Variadic) {
7975 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7976 SemaRef.Diag(Ctor->getLocation(),
7977 diag::note_using_decl_constructor_ellipsis);
7978 EPI.Variadic = false;
7979 }
7980
7981 // Declare a constructor for each number of parameters.
7982 //
7983 // C++11 [class.inhctor]p1:
7984 // The candidate set of inherited constructors from the class X named in
7985 // the using-declaration consists of [... modulo defects ...] for each
7986 // constructor or constructor template of X, the set of constructors or
7987 // constructor templates that results from omitting any ellipsis parameter
7988 // specification and successively omitting parameters with a default
7989 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00007990 unsigned MinParams = minParamsToInherit(Ctor);
7991 unsigned Params = Ctor->getNumParams();
7992 if (Params >= MinParams) {
7993 do
7994 declareCtor(UsingLoc, Ctor,
7995 SemaRef.Context.getFunctionType(
7996 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7997 while (Params > MinParams &&
7998 Ctor->getParamDecl(--Params)->hasDefaultArg());
7999 }
Richard Smith4841ca52013-04-10 05:48:59 +00008000 }
8001
8002 /// Find the using-declaration which specified that we should inherit the
8003 /// constructors of \p Base.
8004 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8005 // No fancy lookup required; just look for the base constructor name
8006 // directly within the derived class.
8007 ASTContext &Context = SemaRef.Context;
8008 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8009 Context.getCanonicalType(Context.getRecordType(Base)));
8010 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8011 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8012 }
8013
8014 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8015 // C++11 [class.inhctor]p3:
8016 // [F]or each constructor template in the candidate set of inherited
8017 // constructors, a constructor template is implicitly declared
8018 if (Ctor->getDescribedFunctionTemplate())
8019 return 0;
8020
8021 // For each non-template constructor in the candidate set of inherited
8022 // constructors other than a constructor having no parameters or a
8023 // copy/move constructor having a single parameter, a constructor is
8024 // implicitly declared [...]
8025 if (Ctor->getNumParams() == 0)
8026 return 1;
8027 if (Ctor->isCopyOrMoveConstructor())
8028 return 2;
8029
8030 // Per discussion on core reflector, never inherit a constructor which
8031 // would become a default, copy, or move constructor of Derived either.
8032 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8033 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8034 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8035 }
8036
8037 /// Declare a single inheriting constructor, inheriting the specified
8038 /// constructor, with the given type.
8039 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8040 QualType DerivedType) {
8041 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8042
8043 // C++11 [class.inhctor]p3:
8044 // ... a constructor is implicitly declared with the same constructor
8045 // characteristics unless there is a user-declared constructor with
8046 // the same signature in the class where the using-declaration appears
8047 if (Entry.DeclaredInDerived)
8048 return;
8049
8050 // C++11 [class.inhctor]p7:
8051 // If two using-declarations declare inheriting constructors with the
8052 // same signature, the program is ill-formed
8053 if (Entry.DerivedCtor) {
8054 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8055 // Only diagnose this once per constructor.
8056 if (Entry.DerivedCtor->isInvalidDecl())
8057 return;
8058 Entry.DerivedCtor->setInvalidDecl();
8059
8060 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8061 SemaRef.Diag(BaseCtor->getLocation(),
8062 diag::note_using_decl_constructor_conflict_current_ctor);
8063 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8064 diag::note_using_decl_constructor_conflict_previous_ctor);
8065 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8066 diag::note_using_decl_constructor_conflict_previous_using);
8067 } else {
8068 // Core issue (no number): if the same inheriting constructor is
8069 // produced by multiple base class constructors from the same base
8070 // class, the inheriting constructor is defined as deleted.
8071 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8072 }
8073
8074 return;
8075 }
8076
8077 ASTContext &Context = SemaRef.Context;
8078 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8079 Context.getCanonicalType(Context.getRecordType(Derived)));
8080 DeclarationNameInfo NameInfo(Name, UsingLoc);
8081
8082 TemplateParameterList *TemplateParams = 0;
8083 if (const FunctionTemplateDecl *FTD =
8084 BaseCtor->getDescribedFunctionTemplate()) {
8085 TemplateParams = FTD->getTemplateParameters();
8086 // We're reusing template parameters from a different DeclContext. This
8087 // is questionable at best, but works out because the template depth in
8088 // both places is guaranteed to be 0.
8089 // FIXME: Rebuild the template parameters in the new context, and
8090 // transform the function type to refer to them.
8091 }
8092
8093 // Build type source info pointing at the using-declaration. This is
8094 // required by template instantiation.
8095 TypeSourceInfo *TInfo =
8096 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8097 FunctionProtoTypeLoc ProtoLoc =
8098 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8099
8100 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8101 Context, Derived, UsingLoc, NameInfo, DerivedType,
8102 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8103 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8104
8105 // Build an unevaluated exception specification for this constructor.
8106 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8107 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8108 EPI.ExceptionSpecType = EST_Unevaluated;
8109 EPI.ExceptionSpecDecl = DerivedCtor;
8110 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8111 FPT->getArgTypes(), EPI));
8112
8113 // Build the parameter declarations.
8114 SmallVector<ParmVarDecl *, 16> ParamDecls;
8115 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8116 TypeSourceInfo *TInfo =
8117 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8118 ParmVarDecl *PD = ParmVarDecl::Create(
8119 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8120 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8121 PD->setScopeInfo(0, I);
8122 PD->setImplicit();
8123 ParamDecls.push_back(PD);
8124 ProtoLoc.setArg(I, PD);
8125 }
8126
8127 // Set up the new constructor.
8128 DerivedCtor->setAccess(BaseCtor->getAccess());
8129 DerivedCtor->setParams(ParamDecls);
8130 DerivedCtor->setInheritedConstructor(BaseCtor);
8131 if (BaseCtor->isDeleted())
8132 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8133
8134 // If this is a constructor template, build the template declaration.
8135 if (TemplateParams) {
8136 FunctionTemplateDecl *DerivedTemplate =
8137 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8138 TemplateParams, DerivedCtor);
8139 DerivedTemplate->setAccess(BaseCtor->getAccess());
8140 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8141 Derived->addDecl(DerivedTemplate);
8142 } else {
8143 Derived->addDecl(DerivedCtor);
8144 }
8145
8146 Entry.BaseCtor = BaseCtor;
8147 Entry.DerivedCtor = DerivedCtor;
8148 }
8149
8150 Sema &SemaRef;
8151 CXXRecordDecl *Derived;
8152 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8153 MapType Map;
8154};
8155}
8156
8157void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8158 // Defer declaring the inheriting constructors until the class is
8159 // instantiated.
8160 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008161 return;
8162
Richard Smith4841ca52013-04-10 05:48:59 +00008163 // Find base classes from which we might inherit constructors.
8164 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8165 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8166 BaseE = ClassDecl->bases_end();
8167 BaseIt != BaseE; ++BaseIt)
8168 if (BaseIt->getInheritConstructors())
8169 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008170
Richard Smith4841ca52013-04-10 05:48:59 +00008171 // Go no further if we're not inheriting any constructors.
8172 if (InheritedBases.empty())
8173 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008174
Richard Smith4841ca52013-04-10 05:48:59 +00008175 // Declare the inherited constructors.
8176 InheritingConstructorInfo ICI(*this, ClassDecl);
8177 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8178 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008179}
8180
Richard Smith07b0fdc2013-03-18 21:12:30 +00008181void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8182 CXXConstructorDecl *Constructor) {
8183 CXXRecordDecl *ClassDecl = Constructor->getParent();
8184 assert(Constructor->getInheritedConstructor() &&
8185 !Constructor->doesThisDeclarationHaveABody() &&
8186 !Constructor->isDeleted());
8187
8188 SynthesizedFunctionScope Scope(*this, Constructor);
8189 DiagnosticErrorTrap Trap(Diags);
8190 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8191 Trap.hasErrorOccurred()) {
8192 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8193 << Context.getTagDeclType(ClassDecl);
8194 Constructor->setInvalidDecl();
8195 return;
8196 }
8197
8198 SourceLocation Loc = Constructor->getLocation();
8199 Constructor->setBody(new (Context) CompoundStmt(Loc));
8200
8201 Constructor->setUsed();
8202 MarkVTableUsed(CurrentLocation, ClassDecl);
8203
8204 if (ASTMutationListener *L = getASTMutationListener()) {
8205 L->CompletedImplicitDefinition(Constructor);
8206 }
8207}
8208
8209
Sean Huntcb45a0f2011-05-12 22:46:25 +00008210Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008211Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8212 CXXRecordDecl *ClassDecl = MD->getParent();
8213
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008214 // C++ [except.spec]p14:
8215 // An implicitly declared special member function (Clause 12) shall have
8216 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008217 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008218 if (ClassDecl->isInvalidDecl())
8219 return ExceptSpec;
8220
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008221 // Direct base-class destructors.
8222 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8223 BEnd = ClassDecl->bases_end();
8224 B != BEnd; ++B) {
8225 if (B->isVirtual()) // Handled below.
8226 continue;
8227
8228 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008229 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008230 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008231 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008232
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008233 // Virtual base-class destructors.
8234 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8235 BEnd = ClassDecl->vbases_end();
8236 B != BEnd; ++B) {
8237 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008238 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008239 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008240 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008241
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008242 // Field destructors.
8243 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8244 FEnd = ClassDecl->field_end();
8245 F != FEnd; ++F) {
8246 if (const RecordType *RecordTy
8247 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008248 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008249 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008250 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008251
Sean Huntcb45a0f2011-05-12 22:46:25 +00008252 return ExceptSpec;
8253}
8254
8255CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8256 // C++ [class.dtor]p2:
8257 // If a class has no user-declared destructor, a destructor is
8258 // declared implicitly. An implicitly-declared destructor is an
8259 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008260 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008261
Richard Smithafb49182012-11-29 01:34:07 +00008262 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8263 if (DSM.isAlreadyBeingDeclared())
8264 return 0;
8265
Douglas Gregor4923aa22010-07-02 20:37:36 +00008266 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008267 CanQualType ClassType
8268 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008269 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008270 DeclarationName Name
8271 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008272 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008273 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008274 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8275 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008276 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008277 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008278 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008279 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008280
8281 // Build an exception specification pointing back at this destructor.
8282 FunctionProtoType::ExtProtoInfo EPI;
8283 EPI.ExceptionSpecType = EST_Unevaluated;
8284 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008285 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008286
Richard Smithbc2a35d2012-12-08 08:32:28 +00008287 AddOverriddenMethods(ClassDecl, Destructor);
8288
8289 // We don't need to use SpecialMemberIsTrivial here; triviality for
8290 // destructors is easy to compute.
8291 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8292
8293 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008294 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008295
Douglas Gregor4923aa22010-07-02 20:37:36 +00008296 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008297 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008298
Douglas Gregor4923aa22010-07-02 20:37:36 +00008299 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008300 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008301 PushOnScopeChains(Destructor, S, false);
8302 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008303
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008304 return Destructor;
8305}
8306
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008307void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008308 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008309 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008310 !Destructor->doesThisDeclarationHaveABody() &&
8311 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008312 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008313 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008314 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008315
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008316 if (Destructor->isInvalidDecl())
8317 return;
8318
Eli Friedman9a14db32012-10-18 20:14:08 +00008319 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008320
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008321 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008322 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8323 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008324
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008325 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008326 Diag(CurrentLocation, diag::note_member_synthesized_at)
8327 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8328
8329 Destructor->setInvalidDecl();
8330 return;
8331 }
8332
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008333 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008334 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008335 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008336 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008337 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008338
8339 if (ASTMutationListener *L = getASTMutationListener()) {
8340 L->CompletedImplicitDefinition(Destructor);
8341 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008342}
8343
Richard Smitha4156b82012-04-21 18:42:51 +00008344/// \brief Perform any semantic analysis which needs to be delayed until all
8345/// pending class member declarations have been parsed.
8346void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008347 // If the context is an invalid C++ class, just suppress these checks.
8348 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8349 if (Record->isInvalidDecl()) {
8350 DelayedDestructorExceptionSpecChecks.clear();
8351 return;
8352 }
8353 }
8354
Richard Smitha4156b82012-04-21 18:42:51 +00008355 // Perform any deferred checking of exception specifications for virtual
8356 // destructors.
8357 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8358 i != e; ++i) {
8359 const CXXDestructorDecl *Dtor =
8360 DelayedDestructorExceptionSpecChecks[i].first;
8361 assert(!Dtor->getParent()->isDependentType() &&
8362 "Should not ever add destructors of templates into the list.");
8363 CheckOverridingFunctionExceptionSpec(Dtor,
8364 DelayedDestructorExceptionSpecChecks[i].second);
8365 }
8366 DelayedDestructorExceptionSpecChecks.clear();
8367}
8368
Richard Smithb9d0b762012-07-27 04:22:15 +00008369void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8370 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008371 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008372 "adjusting dtor exception specs was introduced in c++11");
8373
Sebastian Redl0ee33912011-05-19 05:13:44 +00008374 // C++11 [class.dtor]p3:
8375 // A declaration of a destructor that does not have an exception-
8376 // specification is implicitly considered to have the same exception-
8377 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008378 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008379 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008380 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008381 return;
8382
Chandler Carruth3f224b22011-09-20 04:55:26 +00008383 // Replace the destructor's type, building off the existing one. Fortunately,
8384 // the only thing of interest in the destructor type is its extended info.
8385 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008386 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8387 EPI.ExceptionSpecType = EST_Unevaluated;
8388 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008389 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008390
Sebastian Redl0ee33912011-05-19 05:13:44 +00008391 // FIXME: If the destructor has a body that could throw, and the newly created
8392 // spec doesn't allow exceptions, we should emit a warning, because this
8393 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008394 // However, we don't have a body or an exception specification yet, so it
8395 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008396}
8397
Richard Smith8c889532012-11-14 00:50:40 +00008398/// When generating a defaulted copy or move assignment operator, if a field
8399/// should be copied with __builtin_memcpy rather than via explicit assignments,
8400/// do so. This optimization only applies for arrays of scalars, and for arrays
8401/// of class type where the selected copy/move-assignment operator is trivial.
8402static StmtResult
8403buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8404 Expr *To, Expr *From) {
8405 // Compute the size of the memory buffer to be copied.
8406 QualType SizeType = S.Context.getSizeType();
8407 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8408 S.Context.getTypeSizeInChars(T).getQuantity());
8409
8410 // Take the address of the field references for "from" and "to". We
8411 // directly construct UnaryOperators here because semantic analysis
8412 // does not permit us to take the address of an xvalue.
8413 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8414 S.Context.getPointerType(From->getType()),
8415 VK_RValue, OK_Ordinary, Loc);
8416 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8417 S.Context.getPointerType(To->getType()),
8418 VK_RValue, OK_Ordinary, Loc);
8419
8420 const Type *E = T->getBaseElementTypeUnsafe();
8421 bool NeedsCollectableMemCpy =
8422 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8423
8424 // Create a reference to the __builtin_objc_memmove_collectable function
8425 StringRef MemCpyName = NeedsCollectableMemCpy ?
8426 "__builtin_objc_memmove_collectable" :
8427 "__builtin_memcpy";
8428 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8429 Sema::LookupOrdinaryName);
8430 S.LookupName(R, S.TUScope, true);
8431
8432 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8433 if (!MemCpy)
8434 // Something went horribly wrong earlier, and we will have complained
8435 // about it.
8436 return StmtError();
8437
8438 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8439 VK_RValue, Loc, 0);
8440 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8441
8442 Expr *CallArgs[] = {
8443 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8444 };
8445 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8446 Loc, CallArgs, Loc);
8447
8448 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8449 return S.Owned(Call.takeAs<Stmt>());
8450}
8451
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008452/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008453/// \c To.
8454///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008455/// This routine is used to copy/move the members of a class with an
8456/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008457/// copied are arrays, this routine builds for loops to copy them.
8458///
8459/// \param S The Sema object used for type-checking.
8460///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008461/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008462///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008463/// \param T The type of the expressions being copied/moved. Both expressions
8464/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008465///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008466/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008467///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008468/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008469///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008470/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008471/// Otherwise, it's a non-static member subobject.
8472///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008473/// \param Copying Whether we're copying or moving.
8474///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008475/// \param Depth Internal parameter recording the depth of the recursion.
8476///
Richard Smith8c889532012-11-14 00:50:40 +00008477/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8478/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008479static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008480buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8481 Expr *To, Expr *From,
8482 bool CopyingBaseSubobject, bool Copying,
8483 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008484 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008485 // Each subobject is assigned in the manner appropriate to its type:
8486 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008487 // - if the subobject is of class type, as if by a call to operator= with
8488 // the subobject as the object expression and the corresponding
8489 // subobject of x as a single function argument (as if by explicit
8490 // qualification; that is, ignoring any possible virtual overriding
8491 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008492 //
8493 // C++03 [class.copy]p13:
8494 // - if the subobject is of class type, the copy assignment operator for
8495 // the class is used (as if by explicit qualification; that is,
8496 // ignoring any possible virtual overriding functions in more derived
8497 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008498 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8499 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008500
Douglas Gregor06a9f362010-05-01 20:49:11 +00008501 // Look for operator=.
8502 DeclarationName Name
8503 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8504 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8505 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008506
Richard Smith044c8aa2012-11-13 00:54:12 +00008507 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8508 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008509 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008510 LookupResult::Filter F = OpLookup.makeFilter();
8511 while (F.hasNext()) {
8512 NamedDecl *D = F.next();
8513 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8514 if (Method->isCopyAssignmentOperator() ||
8515 (!Copying && Method->isMoveAssignmentOperator()))
8516 continue;
8517
8518 F.erase();
8519 }
8520 F.done();
John McCallb0207482010-03-16 06:11:48 +00008521 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008522
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008523 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008524 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008525 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008526 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008527 // ambiguities), we need to cast "this" to that subobject type; to
8528 // ensure that we don't go through the virtual call mechanism, we need
8529 // to qualify the operator= name with the base class (see below). However,
8530 // this means that if the base class has a protected copy assignment
8531 // operator, the protected member access check will fail. So, we
8532 // rewrite "protected" access to "public" access in this case, since we
8533 // know by construction that we're calling from a derived class.
8534 if (CopyingBaseSubobject) {
8535 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8536 L != LEnd; ++L) {
8537 if (L.getAccess() == AS_protected)
8538 L.setAccess(AS_public);
8539 }
8540 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008541
Douglas Gregor06a9f362010-05-01 20:49:11 +00008542 // Create the nested-name-specifier that will be used to qualify the
8543 // reference to operator=; this is required to suppress the virtual
8544 // call mechanism.
8545 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008546 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008547 SS.MakeTrivial(S.Context,
8548 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008549 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008550 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008551
Douglas Gregor06a9f362010-05-01 20:49:11 +00008552 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008553 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008554 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008555 /*TemplateKWLoc=*/SourceLocation(),
8556 /*FirstQualifierInScope=*/0,
8557 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008558 /*TemplateArgs=*/0,
8559 /*SuppressQualifierCheck=*/true);
8560 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008561 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008562
Douglas Gregor06a9f362010-05-01 20:49:11 +00008563 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008564
Richard Smith044c8aa2012-11-13 00:54:12 +00008565 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008566 OpEqualRef.takeAs<Expr>(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00008567 Loc, From, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008568 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008569 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008570
Richard Smith8c889532012-11-14 00:50:40 +00008571 // If we built a call to a trivial 'operator=' while copying an array,
8572 // bail out. We'll replace the whole shebang with a memcpy.
8573 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8574 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8575 return StmtResult((Stmt*)0);
8576
Richard Smith044c8aa2012-11-13 00:54:12 +00008577 // Convert to an expression-statement, and clean up any produced
8578 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008579 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008580 }
John McCallb0207482010-03-16 06:11:48 +00008581
Richard Smith044c8aa2012-11-13 00:54:12 +00008582 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008583 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008584 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008585 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008586 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008587 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008588 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008589 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008590 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008591
8592 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008593 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008594
Douglas Gregor06a9f362010-05-01 20:49:11 +00008595 // Construct a loop over the array bounds, e.g.,
8596 //
8597 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8598 //
8599 // that will copy each of the array elements.
8600 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008601
Douglas Gregor06a9f362010-05-01 20:49:11 +00008602 // Create the iteration variable.
8603 IdentifierInfo *IterationVarName = 0;
8604 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008605 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008606 llvm::raw_svector_ostream OS(Str);
8607 OS << "__i" << Depth;
8608 IterationVarName = &S.Context.Idents.get(OS.str());
8609 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008610 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008611 IterationVarName, SizeType,
8612 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008613 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008614
Douglas Gregor06a9f362010-05-01 20:49:11 +00008615 // Initialize the iteration variable to zero.
8616 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008617 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008618
8619 // Create a reference to the iteration variable; we'll use this several
8620 // times throughout.
8621 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008622 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008623 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008624 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8625 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8626
Douglas Gregor06a9f362010-05-01 20:49:11 +00008627 // Create the DeclStmt that holds the iteration variable.
8628 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008629
Douglas Gregor06a9f362010-05-01 20:49:11 +00008630 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008631 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008632 IterationVarRefRVal,
8633 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008634 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008635 IterationVarRefRVal,
8636 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008637 if (!Copying) // Cast to rvalue
8638 From = CastForMoving(S, From);
8639
8640 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008641 StmtResult Copy =
8642 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8643 To, From, CopyingBaseSubobject,
8644 Copying, Depth + 1);
8645 // Bail out if copying fails or if we determined that we should use memcpy.
8646 if (Copy.isInvalid() || !Copy.get())
8647 return Copy;
8648
8649 // Create the comparison against the array bound.
8650 llvm::APInt Upper
8651 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8652 Expr *Comparison
8653 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8654 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8655 BO_NE, S.Context.BoolTy,
8656 VK_RValue, OK_Ordinary, Loc, false);
8657
8658 // Create the pre-increment of the iteration variable.
8659 Expr *Increment
8660 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8661 VK_LValue, OK_Ordinary, Loc);
8662
Douglas Gregor06a9f362010-05-01 20:49:11 +00008663 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008664 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008665 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008666 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008667 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008668}
8669
Richard Smith8c889532012-11-14 00:50:40 +00008670static StmtResult
8671buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8672 Expr *To, Expr *From,
8673 bool CopyingBaseSubobject, bool Copying) {
8674 // Maybe we should use a memcpy?
8675 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8676 T.isTriviallyCopyableType(S.Context))
8677 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8678
8679 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8680 CopyingBaseSubobject,
8681 Copying, 0));
8682
8683 // If we ended up picking a trivial assignment operator for an array of a
8684 // non-trivially-copyable class type, just emit a memcpy.
8685 if (!Result.isInvalid() && !Result.get())
8686 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8687
8688 return Result;
8689}
8690
Richard Smithb9d0b762012-07-27 04:22:15 +00008691Sema::ImplicitExceptionSpecification
8692Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8693 CXXRecordDecl *ClassDecl = MD->getParent();
8694
8695 ImplicitExceptionSpecification ExceptSpec(*this);
8696 if (ClassDecl->isInvalidDecl())
8697 return ExceptSpec;
8698
8699 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8700 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8701 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8702
Douglas Gregorb87786f2010-07-01 17:48:08 +00008703 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008704 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008705 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008706
8707 // It is unspecified whether or not an implicit copy assignment operator
8708 // attempts to deduplicate calls to assignment operators of virtual bases are
8709 // made. As such, this exception specification is effectively unspecified.
8710 // Based on a similar decision made for constness in C++0x, we're erring on
8711 // the side of assuming such calls to be made regardless of whether they
8712 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008713 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8714 BaseEnd = ClassDecl->bases_end();
8715 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008716 if (Base->isVirtual())
8717 continue;
8718
Douglas Gregora376d102010-07-02 21:50:04 +00008719 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008720 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008721 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8722 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008723 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008724 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008725
8726 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8727 BaseEnd = ClassDecl->vbases_end();
8728 Base != BaseEnd; ++Base) {
8729 CXXRecordDecl *BaseClassDecl
8730 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8731 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8732 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008733 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008734 }
8735
Douglas Gregorb87786f2010-07-01 17:48:08 +00008736 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8737 FieldEnd = ClassDecl->field_end();
8738 Field != FieldEnd;
8739 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008740 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008741 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8742 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008743 LookupCopyingAssignment(FieldClassDecl,
8744 ArgQuals | FieldType.getCVRQualifiers(),
8745 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008746 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008747 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008748 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008749
Richard Smithb9d0b762012-07-27 04:22:15 +00008750 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008751}
8752
8753CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8754 // Note: The following rules are largely analoguous to the copy
8755 // constructor rules. Note that virtual bases are not taken into account
8756 // for determining the argument type of the operator. Note also that
8757 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008758 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008759
Richard Smithafb49182012-11-29 01:34:07 +00008760 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8761 if (DSM.isAlreadyBeingDeclared())
8762 return 0;
8763
Sean Hunt30de05c2011-05-14 05:23:20 +00008764 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8765 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00008766 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8767 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00008768 ArgType = ArgType.withConst();
8769 ArgType = Context.getLValueReferenceType(ArgType);
8770
Richard Smitha8942d72013-05-07 03:19:20 +00008771 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8772 CXXCopyAssignment,
8773 Const);
8774
Douglas Gregord3c35902010-07-01 16:36:15 +00008775 // An implicitly-declared copy assignment operator is an inline public
8776 // member of its class.
8777 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008778 SourceLocation ClassLoc = ClassDecl->getLocation();
8779 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00008780 CXXMethodDecl *CopyAssignment =
8781 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8782 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8783 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008784 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008785 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008786 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008787
8788 // Build an exception specification pointing back at this member.
8789 FunctionProtoType::ExtProtoInfo EPI;
8790 EPI.ExceptionSpecType = EST_Unevaluated;
8791 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008792 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008793
Douglas Gregord3c35902010-07-01 16:36:15 +00008794 // Add the parameter to the operator.
8795 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008796 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008797 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008798 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008799 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008800
Richard Smithbc2a35d2012-12-08 08:32:28 +00008801 AddOverriddenMethods(ClassDecl, CopyAssignment);
8802
8803 CopyAssignment->setTrivial(
8804 ClassDecl->needsOverloadResolutionForCopyAssignment()
8805 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8806 : ClassDecl->hasTrivialCopyAssignment());
8807
Richard Smitha8942d72013-05-07 03:19:20 +00008808 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00008809 // .... If the class definition does not explicitly declare a copy
8810 // assignment operator, there is no user-declared move constructor, and
8811 // there is no user-declared move assignment operator, a copy assignment
8812 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008813 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008814 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008815
Richard Smithbc2a35d2012-12-08 08:32:28 +00008816 // Note that we have added this copy-assignment operator.
8817 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8818
8819 if (Scope *S = getScopeForContext(ClassDecl))
8820 PushOnScopeChains(CopyAssignment, S, false);
8821 ClassDecl->addDecl(CopyAssignment);
8822
Douglas Gregord3c35902010-07-01 16:36:15 +00008823 return CopyAssignment;
8824}
8825
Douglas Gregor06a9f362010-05-01 20:49:11 +00008826void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8827 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008828 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008829 CopyAssignOperator->isOverloadedOperator() &&
8830 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008831 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8832 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008833 "DefineImplicitCopyAssignment called for wrong function");
8834
8835 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8836
8837 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8838 CopyAssignOperator->setInvalidDecl();
8839 return;
8840 }
8841
8842 CopyAssignOperator->setUsed();
8843
Eli Friedman9a14db32012-10-18 20:14:08 +00008844 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008845 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008846
8847 // C++0x [class.copy]p30:
8848 // The implicitly-defined or explicitly-defaulted copy assignment operator
8849 // for a non-union class X performs memberwise copy assignment of its
8850 // subobjects. The direct base classes of X are assigned first, in the
8851 // order of their declaration in the base-specifier-list, and then the
8852 // immediate non-static data members of X are assigned, in the order in
8853 // which they were declared in the class definition.
8854
8855 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008856 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008857
8858 // The parameter for the "other" object, which we are copying from.
8859 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8860 Qualifiers OtherQuals = Other->getType().getQualifiers();
8861 QualType OtherRefType = Other->getType();
8862 if (const LValueReferenceType *OtherRef
8863 = OtherRefType->getAs<LValueReferenceType>()) {
8864 OtherRefType = OtherRef->getPointeeType();
8865 OtherQuals = OtherRefType.getQualifiers();
8866 }
8867
8868 // Our location for everything implicitly-generated.
8869 SourceLocation Loc = CopyAssignOperator->getLocation();
8870
8871 // Construct a reference to the "other" object. We'll be using this
8872 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008873 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008874 assert(OtherRef && "Reference to parameter cannot fail!");
8875
8876 // Construct the "this" pointer. We'll be using this throughout the generated
8877 // ASTs.
8878 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8879 assert(This && "Reference to this cannot fail!");
8880
8881 // Assign base classes.
8882 bool Invalid = false;
8883 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8884 E = ClassDecl->bases_end(); Base != E; ++Base) {
8885 // Form the assignment:
8886 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8887 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008888 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008889 Invalid = true;
8890 continue;
8891 }
8892
John McCallf871d0c2010-08-07 06:22:56 +00008893 CXXCastPath BasePath;
8894 BasePath.push_back(Base);
8895
Douglas Gregor06a9f362010-05-01 20:49:11 +00008896 // Construct the "from" expression, which is an implicit cast to the
8897 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008898 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008899 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8900 CK_UncheckedDerivedToBase,
8901 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008902
8903 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008904 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008905
8906 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008907 To = ImpCastExprToType(To.take(),
8908 Context.getCVRQualifiedType(BaseType,
8909 CopyAssignOperator->getTypeQualifiers()),
8910 CK_UncheckedDerivedToBase,
8911 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008912
8913 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008914 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008915 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008916 /*CopyingBaseSubobject=*/true,
8917 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008918 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008919 Diag(CurrentLocation, diag::note_member_synthesized_at)
8920 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8921 CopyAssignOperator->setInvalidDecl();
8922 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008923 }
8924
8925 // Success! Record the copy.
8926 Statements.push_back(Copy.takeAs<Expr>());
8927 }
8928
Douglas Gregor06a9f362010-05-01 20:49:11 +00008929 // Assign non-static members.
8930 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8931 FieldEnd = ClassDecl->field_end();
8932 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008933 if (Field->isUnnamedBitfield())
8934 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00008935
8936 if (Field->isInvalidDecl()) {
8937 Invalid = true;
8938 continue;
8939 }
8940
Douglas Gregor06a9f362010-05-01 20:49:11 +00008941 // Check for members of reference type; we can't copy those.
8942 if (Field->getType()->isReferenceType()) {
8943 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8944 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8945 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008946 Diag(CurrentLocation, diag::note_member_synthesized_at)
8947 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008948 Invalid = true;
8949 continue;
8950 }
8951
8952 // Check for members of const-qualified, non-class type.
8953 QualType BaseType = Context.getBaseElementType(Field->getType());
8954 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8955 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8956 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8957 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008958 Diag(CurrentLocation, diag::note_member_synthesized_at)
8959 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008960 Invalid = true;
8961 continue;
8962 }
John McCallb77115d2011-06-17 00:18:42 +00008963
8964 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008965 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8966 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008967
8968 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008969 if (FieldType->isIncompleteArrayType()) {
8970 assert(ClassDecl->hasFlexibleArrayMember() &&
8971 "Incomplete array type is not valid");
8972 continue;
8973 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008974
8975 // Build references to the field in the object we're copying from and to.
8976 CXXScopeSpec SS; // Intentionally empty
8977 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8978 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008979 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008980 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008981 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008982 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008983 SS, SourceLocation(), 0,
8984 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008985 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008986 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008987 SS, SourceLocation(), 0,
8988 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008989 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8990 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008991
Douglas Gregor06a9f362010-05-01 20:49:11 +00008992 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008993 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008994 To.get(), From.get(),
8995 /*CopyingBaseSubobject=*/false,
8996 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008997 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008998 Diag(CurrentLocation, diag::note_member_synthesized_at)
8999 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9000 CopyAssignOperator->setInvalidDecl();
9001 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009002 }
9003
9004 // Success! Record the copy.
9005 Statements.push_back(Copy.takeAs<Stmt>());
9006 }
9007
9008 if (!Invalid) {
9009 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00009010 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009011
John McCall60d7b3a2010-08-24 06:29:42 +00009012 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009013 if (Return.isInvalid())
9014 Invalid = true;
9015 else {
9016 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009017
9018 if (Trap.hasErrorOccurred()) {
9019 Diag(CurrentLocation, diag::note_member_synthesized_at)
9020 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9021 Invalid = true;
9022 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009023 }
9024 }
9025
9026 if (Invalid) {
9027 CopyAssignOperator->setInvalidDecl();
9028 return;
9029 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009030
9031 StmtResult Body;
9032 {
9033 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009034 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009035 /*isStmtExpr=*/false);
9036 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9037 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009038 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009039
9040 if (ASTMutationListener *L = getASTMutationListener()) {
9041 L->CompletedImplicitDefinition(CopyAssignOperator);
9042 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009043}
9044
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009045Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009046Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9047 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009048
Richard Smithb9d0b762012-07-27 04:22:15 +00009049 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009050 if (ClassDecl->isInvalidDecl())
9051 return ExceptSpec;
9052
9053 // C++0x [except.spec]p14:
9054 // An implicitly declared special member function (Clause 12) shall have an
9055 // exception-specification. [...]
9056
9057 // It is unspecified whether or not an implicit move assignment operator
9058 // attempts to deduplicate calls to assignment operators of virtual bases are
9059 // made. As such, this exception specification is effectively unspecified.
9060 // Based on a similar decision made for constness in C++0x, we're erring on
9061 // the side of assuming such calls to be made regardless of whether they
9062 // actually happen.
9063 // Note that a move constructor is not implicitly declared when there are
9064 // virtual bases, but it can still be user-declared and explicitly defaulted.
9065 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9066 BaseEnd = ClassDecl->bases_end();
9067 Base != BaseEnd; ++Base) {
9068 if (Base->isVirtual())
9069 continue;
9070
9071 CXXRecordDecl *BaseClassDecl
9072 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9073 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009074 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009075 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009076 }
9077
9078 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9079 BaseEnd = ClassDecl->vbases_end();
9080 Base != BaseEnd; ++Base) {
9081 CXXRecordDecl *BaseClassDecl
9082 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9083 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009084 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009085 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009086 }
9087
9088 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9089 FieldEnd = ClassDecl->field_end();
9090 Field != FieldEnd;
9091 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009092 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009093 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009094 if (CXXMethodDecl *MoveAssign =
9095 LookupMovingAssignment(FieldClassDecl,
9096 FieldType.getCVRQualifiers(),
9097 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009098 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009099 }
9100 }
9101
9102 return ExceptSpec;
9103}
9104
Richard Smith1c931be2012-04-02 18:40:40 +00009105/// Determine whether the class type has any direct or indirect virtual base
9106/// classes which have a non-trivial move assignment operator.
9107static bool
9108hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9109 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9110 BaseEnd = ClassDecl->vbases_end();
9111 Base != BaseEnd; ++Base) {
9112 CXXRecordDecl *BaseClass =
9113 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9114
9115 // Try to declare the move assignment. If it would be deleted, then the
9116 // class does not have a non-trivial move assignment.
9117 if (BaseClass->needsImplicitMoveAssignment())
9118 S.DeclareImplicitMoveAssignment(BaseClass);
9119
Richard Smith426391c2012-11-16 00:53:38 +00009120 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009121 return true;
9122 }
9123
9124 return false;
9125}
9126
9127/// Determine whether the given type either has a move constructor or is
9128/// trivially copyable.
9129static bool
9130hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9131 Type = S.Context.getBaseElementType(Type);
9132
9133 // FIXME: Technically, non-trivially-copyable non-class types, such as
9134 // reference types, are supposed to return false here, but that appears
9135 // to be a standard defect.
9136 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009137 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009138 return true;
9139
9140 if (Type.isTriviallyCopyableType(S.Context))
9141 return true;
9142
9143 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009144 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9145 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009146 if (ClassDecl->needsImplicitMoveConstructor())
9147 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009148 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009149 }
9150
Richard Smithe5411b72012-12-01 02:35:44 +00009151 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9152 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009153 if (ClassDecl->needsImplicitMoveAssignment())
9154 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009155 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009156}
9157
9158/// Determine whether all non-static data members and direct or virtual bases
9159/// of class \p ClassDecl have either a move operation, or are trivially
9160/// copyable.
9161static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9162 bool IsConstructor) {
9163 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9164 BaseEnd = ClassDecl->bases_end();
9165 Base != BaseEnd; ++Base) {
9166 if (Base->isVirtual())
9167 continue;
9168
9169 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9170 return false;
9171 }
9172
9173 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9174 BaseEnd = ClassDecl->vbases_end();
9175 Base != BaseEnd; ++Base) {
9176 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9177 return false;
9178 }
9179
9180 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9181 FieldEnd = ClassDecl->field_end();
9182 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009183 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009184 return false;
9185 }
9186
9187 return true;
9188}
9189
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009190CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009191 // C++11 [class.copy]p20:
9192 // If the definition of a class X does not explicitly declare a move
9193 // assignment operator, one will be implicitly declared as defaulted
9194 // if and only if:
9195 //
9196 // - [first 4 bullets]
9197 assert(ClassDecl->needsImplicitMoveAssignment());
9198
Richard Smithafb49182012-11-29 01:34:07 +00009199 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9200 if (DSM.isAlreadyBeingDeclared())
9201 return 0;
9202
Richard Smith1c931be2012-04-02 18:40:40 +00009203 // [Checked after we build the declaration]
9204 // - the move assignment operator would not be implicitly defined as
9205 // deleted,
9206
9207 // [DR1402]:
9208 // - X has no direct or indirect virtual base class with a non-trivial
9209 // move assignment operator, and
9210 // - each of X's non-static data members and direct or virtual base classes
9211 // has a type that either has a move assignment operator or is trivially
9212 // copyable.
9213 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9214 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9215 ClassDecl->setFailedImplicitMoveAssignment();
9216 return 0;
9217 }
9218
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009219 // Note: The following rules are largely analoguous to the move
9220 // constructor rules.
9221
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009222 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9223 QualType RetType = Context.getLValueReferenceType(ArgType);
9224 ArgType = Context.getRValueReferenceType(ArgType);
9225
Richard Smitha8942d72013-05-07 03:19:20 +00009226 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9227 CXXMoveAssignment,
9228 false);
9229
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009230 // An implicitly-declared move assignment operator is an inline public
9231 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009232 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9233 SourceLocation ClassLoc = ClassDecl->getLocation();
9234 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009235 CXXMethodDecl *MoveAssignment =
9236 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9237 /*TInfo=*/0, /*StorageClass=*/SC_None,
9238 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009239 MoveAssignment->setAccess(AS_public);
9240 MoveAssignment->setDefaulted();
9241 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009242
Richard Smithb9d0b762012-07-27 04:22:15 +00009243 // Build an exception specification pointing back at this member.
9244 FunctionProtoType::ExtProtoInfo EPI;
9245 EPI.ExceptionSpecType = EST_Unevaluated;
9246 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009247 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009248
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009249 // Add the parameter to the operator.
9250 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9251 ClassLoc, ClassLoc, /*Id=*/0,
9252 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009253 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009254 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009255
Richard Smithbc2a35d2012-12-08 08:32:28 +00009256 AddOverriddenMethods(ClassDecl, MoveAssignment);
9257
9258 MoveAssignment->setTrivial(
9259 ClassDecl->needsOverloadResolutionForMoveAssignment()
9260 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9261 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009262
9263 // C++0x [class.copy]p9:
9264 // If the definition of a class X does not explicitly declare a move
9265 // assignment operator, one will be implicitly declared as defaulted if and
9266 // only if:
9267 // [...]
9268 // - the move assignment operator would not be implicitly defined as
9269 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009270 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009271 // Cache this result so that we don't try to generate this over and over
9272 // on every lookup, leaking memory and wasting time.
9273 ClassDecl->setFailedImplicitMoveAssignment();
9274 return 0;
9275 }
9276
Richard Smithbc2a35d2012-12-08 08:32:28 +00009277 // Note that we have added this copy-assignment operator.
9278 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9279
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009280 if (Scope *S = getScopeForContext(ClassDecl))
9281 PushOnScopeChains(MoveAssignment, S, false);
9282 ClassDecl->addDecl(MoveAssignment);
9283
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009284 return MoveAssignment;
9285}
9286
9287void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9288 CXXMethodDecl *MoveAssignOperator) {
9289 assert((MoveAssignOperator->isDefaulted() &&
9290 MoveAssignOperator->isOverloadedOperator() &&
9291 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009292 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9293 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009294 "DefineImplicitMoveAssignment called for wrong function");
9295
9296 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9297
9298 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9299 MoveAssignOperator->setInvalidDecl();
9300 return;
9301 }
9302
9303 MoveAssignOperator->setUsed();
9304
Eli Friedman9a14db32012-10-18 20:14:08 +00009305 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009306 DiagnosticErrorTrap Trap(Diags);
9307
9308 // C++0x [class.copy]p28:
9309 // The implicitly-defined or move assignment operator for a non-union class
9310 // X performs memberwise move assignment of its subobjects. The direct base
9311 // classes of X are assigned first, in the order of their declaration in the
9312 // base-specifier-list, and then the immediate non-static data members of X
9313 // are assigned, in the order in which they were declared in the class
9314 // definition.
9315
9316 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009317 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009318
9319 // The parameter for the "other" object, which we are move from.
9320 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9321 QualType OtherRefType = Other->getType()->
9322 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009323 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009324 "Bad argument type of defaulted move assignment");
9325
9326 // Our location for everything implicitly-generated.
9327 SourceLocation Loc = MoveAssignOperator->getLocation();
9328
9329 // Construct a reference to the "other" object. We'll be using this
9330 // throughout the generated ASTs.
9331 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9332 assert(OtherRef && "Reference to parameter cannot fail!");
9333 // Cast to rvalue.
9334 OtherRef = CastForMoving(*this, OtherRef);
9335
9336 // Construct the "this" pointer. We'll be using this throughout the generated
9337 // ASTs.
9338 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9339 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009340
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009341 // Assign base classes.
9342 bool Invalid = false;
9343 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9344 E = ClassDecl->bases_end(); Base != E; ++Base) {
9345 // Form the assignment:
9346 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9347 QualType BaseType = Base->getType().getUnqualifiedType();
9348 if (!BaseType->isRecordType()) {
9349 Invalid = true;
9350 continue;
9351 }
9352
9353 CXXCastPath BasePath;
9354 BasePath.push_back(Base);
9355
9356 // Construct the "from" expression, which is an implicit cast to the
9357 // appropriately-qualified base type.
9358 Expr *From = OtherRef;
9359 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009360 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009361
9362 // Dereference "this".
9363 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9364
9365 // Implicitly cast "this" to the appropriately-qualified base type.
9366 To = ImpCastExprToType(To.take(),
9367 Context.getCVRQualifiedType(BaseType,
9368 MoveAssignOperator->getTypeQualifiers()),
9369 CK_UncheckedDerivedToBase,
9370 VK_LValue, &BasePath);
9371
9372 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009373 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009374 To.get(), From,
9375 /*CopyingBaseSubobject=*/true,
9376 /*Copying=*/false);
9377 if (Move.isInvalid()) {
9378 Diag(CurrentLocation, diag::note_member_synthesized_at)
9379 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9380 MoveAssignOperator->setInvalidDecl();
9381 return;
9382 }
9383
9384 // Success! Record the move.
9385 Statements.push_back(Move.takeAs<Expr>());
9386 }
9387
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009388 // Assign non-static members.
9389 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9390 FieldEnd = ClassDecl->field_end();
9391 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009392 if (Field->isUnnamedBitfield())
9393 continue;
9394
Eli Friedman8150da32013-06-07 01:48:56 +00009395 if (Field->isInvalidDecl()) {
9396 Invalid = true;
9397 continue;
9398 }
9399
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009400 // Check for members of reference type; we can't move those.
9401 if (Field->getType()->isReferenceType()) {
9402 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9403 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9404 Diag(Field->getLocation(), diag::note_declared_at);
9405 Diag(CurrentLocation, diag::note_member_synthesized_at)
9406 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9407 Invalid = true;
9408 continue;
9409 }
9410
9411 // Check for members of const-qualified, non-class type.
9412 QualType BaseType = Context.getBaseElementType(Field->getType());
9413 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9414 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9415 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9416 Diag(Field->getLocation(), diag::note_declared_at);
9417 Diag(CurrentLocation, diag::note_member_synthesized_at)
9418 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9419 Invalid = true;
9420 continue;
9421 }
9422
9423 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009424 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9425 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009426
9427 QualType FieldType = Field->getType().getNonReferenceType();
9428 if (FieldType->isIncompleteArrayType()) {
9429 assert(ClassDecl->hasFlexibleArrayMember() &&
9430 "Incomplete array type is not valid");
9431 continue;
9432 }
9433
9434 // Build references to the field in the object we're copying from and to.
9435 CXXScopeSpec SS; // Intentionally empty
9436 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9437 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009438 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009439 MemberLookup.resolveKind();
9440 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9441 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009442 SS, SourceLocation(), 0,
9443 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009444 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9445 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009446 SS, SourceLocation(), 0,
9447 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009448 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9449 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9450
9451 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9452 "Member reference with rvalue base must be rvalue except for reference "
9453 "members, which aren't allowed for move assignment.");
9454
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009455 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009456 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009457 To.get(), From.get(),
9458 /*CopyingBaseSubobject=*/false,
9459 /*Copying=*/false);
9460 if (Move.isInvalid()) {
9461 Diag(CurrentLocation, diag::note_member_synthesized_at)
9462 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9463 MoveAssignOperator->setInvalidDecl();
9464 return;
9465 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009466
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009467 // Success! Record the copy.
9468 Statements.push_back(Move.takeAs<Stmt>());
9469 }
9470
9471 if (!Invalid) {
9472 // Add a "return *this;"
9473 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9474
9475 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9476 if (Return.isInvalid())
9477 Invalid = true;
9478 else {
9479 Statements.push_back(Return.takeAs<Stmt>());
9480
9481 if (Trap.hasErrorOccurred()) {
9482 Diag(CurrentLocation, diag::note_member_synthesized_at)
9483 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9484 Invalid = true;
9485 }
9486 }
9487 }
9488
9489 if (Invalid) {
9490 MoveAssignOperator->setInvalidDecl();
9491 return;
9492 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009493
9494 StmtResult Body;
9495 {
9496 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009497 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009498 /*isStmtExpr=*/false);
9499 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9500 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009501 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9502
9503 if (ASTMutationListener *L = getASTMutationListener()) {
9504 L->CompletedImplicitDefinition(MoveAssignOperator);
9505 }
9506}
9507
Richard Smithb9d0b762012-07-27 04:22:15 +00009508Sema::ImplicitExceptionSpecification
9509Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9510 CXXRecordDecl *ClassDecl = MD->getParent();
9511
9512 ImplicitExceptionSpecification ExceptSpec(*this);
9513 if (ClassDecl->isInvalidDecl())
9514 return ExceptSpec;
9515
9516 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9517 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9518 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9519
Douglas Gregor0d405db2010-07-01 20:59:04 +00009520 // C++ [except.spec]p14:
9521 // An implicitly declared special member function (Clause 12) shall have an
9522 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009523 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9524 BaseEnd = ClassDecl->bases_end();
9525 Base != BaseEnd;
9526 ++Base) {
9527 // Virtual bases are handled below.
9528 if (Base->isVirtual())
9529 continue;
9530
Douglas Gregor22584312010-07-02 23:41:54 +00009531 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009532 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009533 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009534 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009535 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009536 }
9537 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9538 BaseEnd = ClassDecl->vbases_end();
9539 Base != BaseEnd;
9540 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009541 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009542 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009543 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009544 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009545 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009546 }
9547 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9548 FieldEnd = ClassDecl->field_end();
9549 Field != FieldEnd;
9550 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009551 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009552 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9553 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009554 LookupCopyingConstructor(FieldClassDecl,
9555 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009556 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009557 }
9558 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009559
Richard Smithb9d0b762012-07-27 04:22:15 +00009560 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009561}
9562
9563CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9564 CXXRecordDecl *ClassDecl) {
9565 // C++ [class.copy]p4:
9566 // If the class definition does not explicitly declare a copy
9567 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009568 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009569
Richard Smithafb49182012-11-29 01:34:07 +00009570 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9571 if (DSM.isAlreadyBeingDeclared())
9572 return 0;
9573
Sean Hunt49634cf2011-05-13 06:10:58 +00009574 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9575 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009576 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009577 if (Const)
9578 ArgType = ArgType.withConst();
9579 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009580
Richard Smith7756afa2012-06-10 05:43:50 +00009581 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9582 CXXCopyConstructor,
9583 Const);
9584
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009585 DeclarationName Name
9586 = Context.DeclarationNames.getCXXConstructorName(
9587 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009588 SourceLocation ClassLoc = ClassDecl->getLocation();
9589 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009590
9591 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009592 // member of its class.
9593 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009594 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009595 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009596 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009597 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009598 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009599
Richard Smithb9d0b762012-07-27 04:22:15 +00009600 // Build an exception specification pointing back at this member.
9601 FunctionProtoType::ExtProtoInfo EPI;
9602 EPI.ExceptionSpecType = EST_Unevaluated;
9603 EPI.ExceptionSpecDecl = CopyConstructor;
9604 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009605 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009606
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009607 // Add the parameter to the constructor.
9608 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009609 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009610 /*IdentifierInfo=*/0,
9611 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009612 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009613 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009614
Richard Smithbc2a35d2012-12-08 08:32:28 +00009615 CopyConstructor->setTrivial(
9616 ClassDecl->needsOverloadResolutionForCopyConstructor()
9617 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9618 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009619
Nico Weberafcc96a2012-01-23 03:19:29 +00009620 // C++11 [class.copy]p8:
9621 // ... If the class definition does not explicitly declare a copy
9622 // constructor, there is no user-declared move constructor, and there is no
9623 // user-declared move assignment operator, a copy constructor is implicitly
9624 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009625 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009626 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009627
Richard Smithbc2a35d2012-12-08 08:32:28 +00009628 // Note that we have declared this constructor.
9629 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9630
9631 if (Scope *S = getScopeForContext(ClassDecl))
9632 PushOnScopeChains(CopyConstructor, S, false);
9633 ClassDecl->addDecl(CopyConstructor);
9634
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009635 return CopyConstructor;
9636}
9637
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009638void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009639 CXXConstructorDecl *CopyConstructor) {
9640 assert((CopyConstructor->isDefaulted() &&
9641 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009642 !CopyConstructor->doesThisDeclarationHaveABody() &&
9643 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009644 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009645
Anders Carlsson63010a72010-04-23 16:24:12 +00009646 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009647 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009648
Eli Friedman9a14db32012-10-18 20:14:08 +00009649 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009650 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009651
David Blaikie93c86172013-01-17 05:26:25 +00009652 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009653 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009654 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009655 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009656 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009657 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009658 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009659 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9660 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009661 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009662 /*isStmtExpr=*/false)
9663 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009664 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009665 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009666
9667 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009668 if (ASTMutationListener *L = getASTMutationListener()) {
9669 L->CompletedImplicitDefinition(CopyConstructor);
9670 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009671}
9672
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009673Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009674Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9675 CXXRecordDecl *ClassDecl = MD->getParent();
9676
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009677 // C++ [except.spec]p14:
9678 // An implicitly declared special member function (Clause 12) shall have an
9679 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009680 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009681 if (ClassDecl->isInvalidDecl())
9682 return ExceptSpec;
9683
9684 // Direct base-class constructors.
9685 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9686 BEnd = ClassDecl->bases_end();
9687 B != BEnd; ++B) {
9688 if (B->isVirtual()) // Handled below.
9689 continue;
9690
9691 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9692 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009693 CXXConstructorDecl *Constructor =
9694 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009695 // If this is a deleted function, add it anyway. This might be conformant
9696 // with the standard. This might not. I'm not sure. It might not matter.
9697 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009698 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009699 }
9700 }
9701
9702 // Virtual base-class constructors.
9703 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9704 BEnd = ClassDecl->vbases_end();
9705 B != BEnd; ++B) {
9706 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9707 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009708 CXXConstructorDecl *Constructor =
9709 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009710 // If this is a deleted function, add it anyway. This might be conformant
9711 // with the standard. This might not. I'm not sure. It might not matter.
9712 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009713 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009714 }
9715 }
9716
9717 // Field constructors.
9718 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9719 FEnd = ClassDecl->field_end();
9720 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009721 QualType FieldType = Context.getBaseElementType(F->getType());
9722 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9723 CXXConstructorDecl *Constructor =
9724 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009725 // If this is a deleted function, add it anyway. This might be conformant
9726 // with the standard. This might not. I'm not sure. It might not matter.
9727 // In particular, the problem is that this function never gets called. It
9728 // might just be ill-formed because this function attempts to refer to
9729 // a deleted function here.
9730 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009731 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009732 }
9733 }
9734
9735 return ExceptSpec;
9736}
9737
9738CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9739 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009740 // C++11 [class.copy]p9:
9741 // If the definition of a class X does not explicitly declare a move
9742 // constructor, one will be implicitly declared as defaulted if and only if:
9743 //
9744 // - [first 4 bullets]
9745 assert(ClassDecl->needsImplicitMoveConstructor());
9746
Richard Smithafb49182012-11-29 01:34:07 +00009747 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9748 if (DSM.isAlreadyBeingDeclared())
9749 return 0;
9750
Richard Smith1c931be2012-04-02 18:40:40 +00009751 // [Checked after we build the declaration]
9752 // - the move assignment operator would not be implicitly defined as
9753 // deleted,
9754
9755 // [DR1402]:
9756 // - each of X's non-static data members and direct or virtual base classes
9757 // has a type that either has a move constructor or is trivially copyable.
9758 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9759 ClassDecl->setFailedImplicitMoveConstructor();
9760 return 0;
9761 }
9762
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009763 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9764 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009765
Richard Smith7756afa2012-06-10 05:43:50 +00009766 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9767 CXXMoveConstructor,
9768 false);
9769
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009770 DeclarationName Name
9771 = Context.DeclarationNames.getCXXConstructorName(
9772 Context.getCanonicalType(ClassType));
9773 SourceLocation ClassLoc = ClassDecl->getLocation();
9774 DeclarationNameInfo NameInfo(Name, ClassLoc);
9775
Richard Smitha8942d72013-05-07 03:19:20 +00009776 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009777 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009778 // member of its class.
9779 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009780 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009781 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009782 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009783 MoveConstructor->setAccess(AS_public);
9784 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009785
Richard Smithb9d0b762012-07-27 04:22:15 +00009786 // Build an exception specification pointing back at this member.
9787 FunctionProtoType::ExtProtoInfo EPI;
9788 EPI.ExceptionSpecType = EST_Unevaluated;
9789 EPI.ExceptionSpecDecl = MoveConstructor;
9790 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009791 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009792
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009793 // Add the parameter to the constructor.
9794 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9795 ClassLoc, ClassLoc,
9796 /*IdentifierInfo=*/0,
9797 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009798 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009799 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009800
Richard Smithbc2a35d2012-12-08 08:32:28 +00009801 MoveConstructor->setTrivial(
9802 ClassDecl->needsOverloadResolutionForMoveConstructor()
9803 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9804 : ClassDecl->hasTrivialMoveConstructor());
9805
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009806 // C++0x [class.copy]p9:
9807 // If the definition of a class X does not explicitly declare a move
9808 // constructor, one will be implicitly declared as defaulted if and only if:
9809 // [...]
9810 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009811 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009812 // Cache this result so that we don't try to generate this over and over
9813 // on every lookup, leaking memory and wasting time.
9814 ClassDecl->setFailedImplicitMoveConstructor();
9815 return 0;
9816 }
9817
9818 // Note that we have declared this constructor.
9819 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9820
9821 if (Scope *S = getScopeForContext(ClassDecl))
9822 PushOnScopeChains(MoveConstructor, S, false);
9823 ClassDecl->addDecl(MoveConstructor);
9824
9825 return MoveConstructor;
9826}
9827
9828void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9829 CXXConstructorDecl *MoveConstructor) {
9830 assert((MoveConstructor->isDefaulted() &&
9831 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009832 !MoveConstructor->doesThisDeclarationHaveABody() &&
9833 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009834 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9835
9836 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9837 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9838
Eli Friedman9a14db32012-10-18 20:14:08 +00009839 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009840 DiagnosticErrorTrap Trap(Diags);
9841
David Blaikie93c86172013-01-17 05:26:25 +00009842 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009843 Trap.hasErrorOccurred()) {
9844 Diag(CurrentLocation, diag::note_member_synthesized_at)
9845 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9846 MoveConstructor->setInvalidDecl();
9847 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009848 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009849 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9850 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009851 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009852 /*isStmtExpr=*/false)
9853 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009854 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009855 }
9856
9857 MoveConstructor->setUsed();
9858
9859 if (ASTMutationListener *L = getASTMutationListener()) {
9860 L->CompletedImplicitDefinition(MoveConstructor);
9861 }
9862}
9863
Douglas Gregore4e68d42012-02-15 19:33:52 +00009864bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9865 return FD->isDeleted() &&
9866 (FD->isDefaulted() || FD->isImplicit()) &&
9867 isa<CXXMethodDecl>(FD);
9868}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009869
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009870/// \brief Mark the call operator of the given lambda closure type as "used".
9871static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9872 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009873 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009874 Lambda->lookup(
9875 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009876 CallOperator->setReferenced();
9877 CallOperator->setUsed();
9878}
9879
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009880void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9881 SourceLocation CurrentLocation,
9882 CXXConversionDecl *Conv)
9883{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009884 CXXRecordDecl *Lambda = Conv->getParent();
9885
9886 // Make sure that the lambda call operator is marked used.
9887 markLambdaCallOperatorUsed(*this, Lambda);
9888
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009889 Conv->setUsed();
9890
Eli Friedman9a14db32012-10-18 20:14:08 +00009891 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009892 DiagnosticErrorTrap Trap(Diags);
9893
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009894 // Return the address of the __invoke function.
9895 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9896 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009897 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009898 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9899 VK_LValue, Conv->getLocation()).take();
9900 assert(FunctionRef && "Can't refer to __invoke function?");
9901 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009902 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009903 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009904 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009905
9906 // Fill in the __invoke function with a dummy implementation. IR generation
9907 // will fill in the actual details.
9908 Invoke->setUsed();
9909 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009910 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009911
9912 if (ASTMutationListener *L = getASTMutationListener()) {
9913 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009914 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009915 }
9916}
9917
9918void Sema::DefineImplicitLambdaToBlockPointerConversion(
9919 SourceLocation CurrentLocation,
9920 CXXConversionDecl *Conv)
9921{
9922 Conv->setUsed();
9923
Eli Friedman9a14db32012-10-18 20:14:08 +00009924 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009925 DiagnosticErrorTrap Trap(Diags);
9926
Douglas Gregorac1303e2012-02-22 05:02:47 +00009927 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009928 Expr *This = ActOnCXXThis(CurrentLocation).take();
9929 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009930
Eli Friedman23f02672012-03-01 04:01:32 +00009931 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9932 Conv->getLocation(),
9933 Conv, DerefThis);
9934
9935 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9936 // behavior. Note that only the general conversion function does this
9937 // (since it's unusable otherwise); in the case where we inline the
9938 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009939 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009940 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9941 CK_CopyAndAutoreleaseBlockObject,
9942 BuildBlock.get(), 0, VK_RValue);
9943
9944 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009945 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009946 Conv->setInvalidDecl();
9947 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009948 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009949
Douglas Gregorac1303e2012-02-22 05:02:47 +00009950 // Create the return statement that returns the block from the conversion
9951 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009952 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009953 if (Return.isInvalid()) {
9954 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9955 Conv->setInvalidDecl();
9956 return;
9957 }
9958
9959 // Set the body of the conversion function.
9960 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009961 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009962 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009963 Conv->getLocation()));
9964
Douglas Gregorac1303e2012-02-22 05:02:47 +00009965 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009966 if (ASTMutationListener *L = getASTMutationListener()) {
9967 L->CompletedImplicitDefinition(Conv);
9968 }
9969}
9970
Douglas Gregorf52757d2012-03-10 06:53:13 +00009971/// \brief Determine whether the given list arguments contains exactly one
9972/// "real" (non-default) argument.
9973static bool hasOneRealArgument(MultiExprArg Args) {
9974 switch (Args.size()) {
9975 case 0:
9976 return false;
9977
9978 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009979 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009980 return false;
9981
9982 // fall through
9983 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009984 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009985 }
9986
9987 return false;
9988}
9989
John McCall60d7b3a2010-08-24 06:29:42 +00009990ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009991Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009992 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009993 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009994 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009995 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009996 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009997 unsigned ConstructKind,
9998 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009999 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010000
Douglas Gregor2f599792010-04-02 18:24:57 +000010001 // C++0x [class.copy]p34:
10002 // When certain criteria are met, an implementation is allowed to
10003 // omit the copy/move construction of a class object, even if the
10004 // copy/move constructor and/or destructor for the object have
10005 // side effects. [...]
10006 // - when a temporary class object that has not been bound to a
10007 // reference (12.2) would be copied/moved to a class object
10008 // with the same cv-unqualified type, the copy/move operation
10009 // can be omitted by constructing the temporary object
10010 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010011 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010012 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010013 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010014 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010015 }
Mike Stump1eb44332009-09-09 15:08:12 +000010016
10017 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010018 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010019 IsListInitialization, RequiresZeroInit,
10020 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010021}
10022
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010023/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10024/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010025ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010026Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10027 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010028 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010029 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010030 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010031 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010032 unsigned ConstructKind,
10033 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010034 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010035 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010036 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010037 HadMultipleCandidates,
10038 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010039 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10040 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010041}
10042
John McCall68c6c9a2010-02-02 09:10:11 +000010043void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010044 if (VD->isInvalidDecl()) return;
10045
John McCall68c6c9a2010-02-02 09:10:11 +000010046 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010047 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010048 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010049 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010050
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010051 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010052 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010053 CheckDestructorAccess(VD->getLocation(), Destructor,
10054 PDiag(diag::err_access_dtor_var)
10055 << VD->getDeclName()
10056 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010057 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010058
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010059 if (!VD->hasGlobalStorage()) return;
10060
10061 // Emit warning for non-trivial dtor in global scope (a real global,
10062 // class-static, function-static).
10063 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10064
10065 // TODO: this should be re-enabled for static locals by !CXAAtExit
10066 if (!VD->isStaticLocal())
10067 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010068}
10069
Douglas Gregor39da0b82009-09-09 23:08:42 +000010070/// \brief Given a constructor and the set of arguments provided for the
10071/// constructor, convert the arguments and add any required default arguments
10072/// to form a proper call to this constructor.
10073///
10074/// \returns true if an error occurred, false otherwise.
10075bool
10076Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10077 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010078 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010079 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010080 bool AllowExplicit,
10081 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010082 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10083 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010084 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010085
10086 const FunctionProtoType *Proto
10087 = Constructor->getType()->getAs<FunctionProtoType>();
10088 assert(Proto && "Constructor without a prototype?");
10089 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010090
10091 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010092 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010093 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010094 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010095 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010096
10097 VariadicCallType CallType =
10098 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010099 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010100 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010101 Proto, 0,
10102 llvm::makeArrayRef(Args, NumArgs),
10103 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010104 CallType, AllowExplicit,
10105 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010106 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010107
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010108 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010109
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010110 CheckConstructorCall(Constructor,
10111 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10112 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010113 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010114
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010115 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010116}
10117
Anders Carlsson20d45d22009-12-12 00:32:00 +000010118static inline bool
10119CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10120 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010121 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010122 if (isa<NamespaceDecl>(DC)) {
10123 return SemaRef.Diag(FnDecl->getLocation(),
10124 diag::err_operator_new_delete_declared_in_namespace)
10125 << FnDecl->getDeclName();
10126 }
10127
10128 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010129 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010130 return SemaRef.Diag(FnDecl->getLocation(),
10131 diag::err_operator_new_delete_declared_static)
10132 << FnDecl->getDeclName();
10133 }
10134
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010135 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010136}
10137
Anders Carlsson156c78e2009-12-13 17:53:43 +000010138static inline bool
10139CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10140 CanQualType ExpectedResultType,
10141 CanQualType ExpectedFirstParamType,
10142 unsigned DependentParamTypeDiag,
10143 unsigned InvalidParamTypeDiag) {
10144 QualType ResultType =
10145 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10146
10147 // Check that the result type is not dependent.
10148 if (ResultType->isDependentType())
10149 return SemaRef.Diag(FnDecl->getLocation(),
10150 diag::err_operator_new_delete_dependent_result_type)
10151 << FnDecl->getDeclName() << ExpectedResultType;
10152
10153 // Check that the result type is what we expect.
10154 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10155 return SemaRef.Diag(FnDecl->getLocation(),
10156 diag::err_operator_new_delete_invalid_result_type)
10157 << FnDecl->getDeclName() << ExpectedResultType;
10158
10159 // A function template must have at least 2 parameters.
10160 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10161 return SemaRef.Diag(FnDecl->getLocation(),
10162 diag::err_operator_new_delete_template_too_few_parameters)
10163 << FnDecl->getDeclName();
10164
10165 // The function decl must have at least 1 parameter.
10166 if (FnDecl->getNumParams() == 0)
10167 return SemaRef.Diag(FnDecl->getLocation(),
10168 diag::err_operator_new_delete_too_few_parameters)
10169 << FnDecl->getDeclName();
10170
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010171 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010172 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10173 if (FirstParamType->isDependentType())
10174 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10175 << FnDecl->getDeclName() << ExpectedFirstParamType;
10176
10177 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010178 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010179 ExpectedFirstParamType)
10180 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10181 << FnDecl->getDeclName() << ExpectedFirstParamType;
10182
10183 return false;
10184}
10185
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010186static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010187CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010188 // C++ [basic.stc.dynamic.allocation]p1:
10189 // A program is ill-formed if an allocation function is declared in a
10190 // namespace scope other than global scope or declared static in global
10191 // scope.
10192 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10193 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010194
10195 CanQualType SizeTy =
10196 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10197
10198 // C++ [basic.stc.dynamic.allocation]p1:
10199 // The return type shall be void*. The first parameter shall have type
10200 // std::size_t.
10201 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10202 SizeTy,
10203 diag::err_operator_new_dependent_param_type,
10204 diag::err_operator_new_param_type))
10205 return true;
10206
10207 // C++ [basic.stc.dynamic.allocation]p1:
10208 // The first parameter shall not have an associated default argument.
10209 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010210 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010211 diag::err_operator_new_default_arg)
10212 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10213
10214 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010215}
10216
10217static bool
Richard Smith444d3842012-10-20 08:26:51 +000010218CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010219 // C++ [basic.stc.dynamic.deallocation]p1:
10220 // A program is ill-formed if deallocation functions are declared in a
10221 // namespace scope other than global scope or declared static in global
10222 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010223 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10224 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010225
10226 // C++ [basic.stc.dynamic.deallocation]p2:
10227 // Each deallocation function shall return void and its first parameter
10228 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010229 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10230 SemaRef.Context.VoidPtrTy,
10231 diag::err_operator_delete_dependent_param_type,
10232 diag::err_operator_delete_param_type))
10233 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010234
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010235 return false;
10236}
10237
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010238/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10239/// of this overloaded operator is well-formed. If so, returns false;
10240/// otherwise, emits appropriate diagnostics and returns true.
10241bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010242 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010243 "Expected an overloaded operator declaration");
10244
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010245 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10246
Mike Stump1eb44332009-09-09 15:08:12 +000010247 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010248 // The allocation and deallocation functions, operator new,
10249 // operator new[], operator delete and operator delete[], are
10250 // described completely in 3.7.3. The attributes and restrictions
10251 // found in the rest of this subclause do not apply to them unless
10252 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010253 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010254 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010255
Anders Carlssona3ccda52009-12-12 00:26:23 +000010256 if (Op == OO_New || Op == OO_Array_New)
10257 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010258
10259 // C++ [over.oper]p6:
10260 // An operator function shall either be a non-static member
10261 // function or be a non-member function and have at least one
10262 // parameter whose type is a class, a reference to a class, an
10263 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010264 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10265 if (MethodDecl->isStatic())
10266 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010267 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010268 } else {
10269 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010270 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10271 ParamEnd = FnDecl->param_end();
10272 Param != ParamEnd; ++Param) {
10273 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010274 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10275 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010276 ClassOrEnumParam = true;
10277 break;
10278 }
10279 }
10280
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010281 if (!ClassOrEnumParam)
10282 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010283 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010284 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010285 }
10286
10287 // C++ [over.oper]p8:
10288 // An operator function cannot have default arguments (8.3.6),
10289 // except where explicitly stated below.
10290 //
Mike Stump1eb44332009-09-09 15:08:12 +000010291 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010292 // (C++ [over.call]p1).
10293 if (Op != OO_Call) {
10294 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10295 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010296 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010297 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010298 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010299 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010300 }
10301 }
10302
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010303 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10304 { false, false, false }
10305#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10306 , { Unary, Binary, MemberOnly }
10307#include "clang/Basic/OperatorKinds.def"
10308 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010309
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010310 bool CanBeUnaryOperator = OperatorUses[Op][0];
10311 bool CanBeBinaryOperator = OperatorUses[Op][1];
10312 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010313
10314 // C++ [over.oper]p8:
10315 // [...] Operator functions cannot have more or fewer parameters
10316 // than the number required for the corresponding operator, as
10317 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010318 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010319 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010320 if (Op != OO_Call &&
10321 ((NumParams == 1 && !CanBeUnaryOperator) ||
10322 (NumParams == 2 && !CanBeBinaryOperator) ||
10323 (NumParams < 1) || (NumParams > 2))) {
10324 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010325 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010326 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010327 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010328 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010329 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010330 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010331 assert(CanBeBinaryOperator &&
10332 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010333 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010334 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010335
Chris Lattner416e46f2008-11-21 07:57:12 +000010336 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010337 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010338 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010339
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010340 // Overloaded operators other than operator() cannot be variadic.
10341 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010342 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010343 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010344 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010345 }
10346
10347 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010348 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10349 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010350 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010351 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010352 }
10353
10354 // C++ [over.inc]p1:
10355 // The user-defined function called operator++ implements the
10356 // prefix and postfix ++ operator. If this function is a member
10357 // function with no parameters, or a non-member function with one
10358 // parameter of class or enumeration type, it defines the prefix
10359 // increment operator ++ for objects of that type. If the function
10360 // is a member function with one parameter (which shall be of type
10361 // int) or a non-member function with two parameters (the second
10362 // of which shall be of type int), it defines the postfix
10363 // increment operator ++ for objects of that type.
10364 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10365 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10366 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010367 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010368 ParamIsInt = BT->getKind() == BuiltinType::Int;
10369
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010370 if (!ParamIsInt)
10371 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010372 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010373 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010374 }
10375
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010376 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010377}
Chris Lattner5a003a42008-12-17 07:09:26 +000010378
Sean Hunta6c058d2010-01-13 09:01:02 +000010379/// CheckLiteralOperatorDeclaration - Check whether the declaration
10380/// of this literal operator function is well-formed. If so, returns
10381/// false; otherwise, emits appropriate diagnostics and returns true.
10382bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010383 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010384 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10385 << FnDecl->getDeclName();
10386 return true;
10387 }
10388
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010389 if (FnDecl->isExternC()) {
10390 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10391 return true;
10392 }
10393
Sean Hunta6c058d2010-01-13 09:01:02 +000010394 bool Valid = false;
10395
Richard Smith36f5cfe2012-03-09 08:00:36 +000010396 // This might be the definition of a literal operator template.
10397 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10398 // This might be a specialization of a literal operator template.
10399 if (!TpDecl)
10400 TpDecl = FnDecl->getPrimaryTemplate();
10401
Sean Hunt216c2782010-04-07 23:11:06 +000010402 // template <char...> type operator "" name() is the only valid template
10403 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010404 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010405 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010406 // Must have only one template parameter
10407 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10408 if (Params->size() == 1) {
10409 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010410 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010411
Sean Hunt216c2782010-04-07 23:11:06 +000010412 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010413 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10414 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10415 Valid = true;
10416 }
10417 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010418 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010419 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010420 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10421
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010422 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010423
Sean Hunt30019c02010-04-07 22:57:35 +000010424 // unsigned long long int, long double, and any character type are allowed
10425 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010426 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10427 Context.hasSameType(T, Context.LongDoubleTy) ||
10428 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010429 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010430 Context.hasSameType(T, Context.Char16Ty) ||
10431 Context.hasSameType(T, Context.Char32Ty)) {
10432 if (++Param == FnDecl->param_end())
10433 Valid = true;
10434 goto FinishedParams;
10435 }
10436
Sean Hunt30019c02010-04-07 22:57:35 +000010437 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010438 const PointerType *PT = T->getAs<PointerType>();
10439 if (!PT)
10440 goto FinishedParams;
10441 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010442 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010443 goto FinishedParams;
10444 T = T.getUnqualifiedType();
10445
10446 // Move on to the second parameter;
10447 ++Param;
10448
10449 // If there is no second parameter, the first must be a const char *
10450 if (Param == FnDecl->param_end()) {
10451 if (Context.hasSameType(T, Context.CharTy))
10452 Valid = true;
10453 goto FinishedParams;
10454 }
10455
10456 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10457 // are allowed as the first parameter to a two-parameter function
10458 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010459 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010460 Context.hasSameType(T, Context.Char16Ty) ||
10461 Context.hasSameType(T, Context.Char32Ty)))
10462 goto FinishedParams;
10463
10464 // The second and final parameter must be an std::size_t
10465 T = (*Param)->getType().getUnqualifiedType();
10466 if (Context.hasSameType(T, Context.getSizeType()) &&
10467 ++Param == FnDecl->param_end())
10468 Valid = true;
10469 }
10470
10471 // FIXME: This diagnostic is absolutely terrible.
10472FinishedParams:
10473 if (!Valid) {
10474 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10475 << FnDecl->getDeclName();
10476 return true;
10477 }
10478
Richard Smitha9e88b22012-03-09 08:16:22 +000010479 // A parameter-declaration-clause containing a default argument is not
10480 // equivalent to any of the permitted forms.
10481 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10482 ParamEnd = FnDecl->param_end();
10483 Param != ParamEnd; ++Param) {
10484 if ((*Param)->hasDefaultArg()) {
10485 Diag((*Param)->getDefaultArgRange().getBegin(),
10486 diag::err_literal_operator_default_argument)
10487 << (*Param)->getDefaultArgRange();
10488 break;
10489 }
10490 }
10491
Richard Smith2fb4ae32012-03-08 02:39:21 +000010492 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010493 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10494 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010495 // C++11 [usrlit.suffix]p1:
10496 // Literal suffix identifiers that do not start with an underscore
10497 // are reserved for future standardization.
10498 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010499 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010500
Sean Hunta6c058d2010-01-13 09:01:02 +000010501 return false;
10502}
10503
Douglas Gregor074149e2009-01-05 19:45:36 +000010504/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10505/// linkage specification, including the language and (if present)
10506/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10507/// the location of the language string literal, which is provided
10508/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10509/// the '{' brace. Otherwise, this linkage specification does not
10510/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010511Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10512 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010513 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010514 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010515 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010516 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010517 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010518 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010519 Language = LinkageSpecDecl::lang_cxx;
10520 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010521 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010522 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010523 }
Mike Stump1eb44332009-09-09 15:08:12 +000010524
Chris Lattnercc98eac2008-12-17 07:13:27 +000010525 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010526
Douglas Gregor074149e2009-01-05 19:45:36 +000010527 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010528 ExternLoc, LangLoc, Language,
10529 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010530 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010531 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010532 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010533}
10534
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010535/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010536/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10537/// valid, it's the position of the closing '}' brace in a linkage
10538/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010539Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010540 Decl *LinkageSpec,
10541 SourceLocation RBraceLoc) {
10542 if (LinkageSpec) {
10543 if (RBraceLoc.isValid()) {
10544 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10545 LSDecl->setRBraceLoc(RBraceLoc);
10546 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010547 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010548 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010549 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010550}
10551
Michael Han684aa732013-02-22 17:15:32 +000010552Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10553 AttributeList *AttrList,
10554 SourceLocation SemiLoc) {
10555 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10556 // Attribute declarations appertain to empty declaration so we handle
10557 // them here.
10558 if (AttrList)
10559 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010560
Michael Han684aa732013-02-22 17:15:32 +000010561 CurContext->addDecl(ED);
10562 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010563}
10564
Douglas Gregord308e622009-05-18 20:51:54 +000010565/// \brief Perform semantic analysis for the variable declaration that
10566/// occurs within a C++ catch clause, returning the newly-created
10567/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010568VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010569 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010570 SourceLocation StartLoc,
10571 SourceLocation Loc,
10572 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010573 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010574 QualType ExDeclType = TInfo->getType();
10575
Sebastian Redl4b07b292008-12-22 19:15:10 +000010576 // Arrays and functions decay.
10577 if (ExDeclType->isArrayType())
10578 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10579 else if (ExDeclType->isFunctionType())
10580 ExDeclType = Context.getPointerType(ExDeclType);
10581
10582 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10583 // The exception-declaration shall not denote a pointer or reference to an
10584 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010585 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010586 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010587 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010588 Invalid = true;
10589 }
Douglas Gregord308e622009-05-18 20:51:54 +000010590
Sebastian Redl4b07b292008-12-22 19:15:10 +000010591 QualType BaseType = ExDeclType;
10592 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010593 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010594 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010595 BaseType = Ptr->getPointeeType();
10596 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010597 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010598 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010599 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010600 BaseType = Ref->getPointeeType();
10601 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010602 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010603 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010604 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010605 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010606 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010607
Mike Stump1eb44332009-09-09 15:08:12 +000010608 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010609 RequireNonAbstractType(Loc, ExDeclType,
10610 diag::err_abstract_type_in_decl,
10611 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010612 Invalid = true;
10613
John McCall5a180392010-07-24 00:37:23 +000010614 // Only the non-fragile NeXT runtime currently supports C++ catches
10615 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010616 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010617 QualType T = ExDeclType;
10618 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10619 T = RT->getPointeeType();
10620
10621 if (T->isObjCObjectType()) {
10622 Diag(Loc, diag::err_objc_object_catch);
10623 Invalid = true;
10624 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010625 // FIXME: should this be a test for macosx-fragile specifically?
10626 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010627 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010628 }
10629 }
10630
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010631 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010632 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010633 ExDecl->setExceptionVariable(true);
10634
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010635 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010636 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010637 Invalid = true;
10638
Douglas Gregorc41b8782011-07-06 18:14:43 +000010639 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010640 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010641 // Insulate this from anything else we might currently be parsing.
10642 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10643
Douglas Gregor6d182892010-03-05 23:38:39 +000010644 // C++ [except.handle]p16:
10645 // The object declared in an exception-declaration or, if the
10646 // exception-declaration does not specify a name, a temporary (12.2) is
10647 // copy-initialized (8.5) from the exception object. [...]
10648 // The object is destroyed when the handler exits, after the destruction
10649 // of any automatic objects initialized within the handler.
10650 //
10651 // We just pretend to initialize the object with itself, then make sure
10652 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010653 QualType initType = ExDeclType;
10654
10655 InitializedEntity entity =
10656 InitializedEntity::InitializeVariable(ExDecl);
10657 InitializationKind initKind =
10658 InitializationKind::CreateCopy(Loc, SourceLocation());
10659
10660 Expr *opaqueValue =
10661 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010662 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10663 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010664 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010665 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010666 else {
10667 // If the constructor used was non-trivial, set this as the
10668 // "initializer".
10669 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10670 if (!construct->getConstructor()->isTrivial()) {
10671 Expr *init = MaybeCreateExprWithCleanups(construct);
10672 ExDecl->setInit(init);
10673 }
10674
10675 // And make sure it's destructable.
10676 FinalizeVarWithDestructor(ExDecl, recordType);
10677 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010678 }
10679 }
10680
Douglas Gregord308e622009-05-18 20:51:54 +000010681 if (Invalid)
10682 ExDecl->setInvalidDecl();
10683
10684 return ExDecl;
10685}
10686
10687/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10688/// handler.
John McCalld226f652010-08-21 09:40:31 +000010689Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010690 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010691 bool Invalid = D.isInvalidType();
10692
10693 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010694 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10695 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010696 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10697 D.getIdentifierLoc());
10698 Invalid = true;
10699 }
10700
Sebastian Redl4b07b292008-12-22 19:15:10 +000010701 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010702 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010703 LookupOrdinaryName,
10704 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010705 // The scope should be freshly made just for us. There is just no way
10706 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010707 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010708 if (PrevDecl->isTemplateParameter()) {
10709 // Maybe we will complain about the shadowed template parameter.
10710 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010711 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010712 }
10713 }
10714
Chris Lattnereaaebc72009-04-25 08:06:05 +000010715 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010716 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10717 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010718 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010719 }
10720
Douglas Gregor83cb9422010-09-09 17:09:21 +000010721 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010722 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010723 D.getIdentifierLoc(),
10724 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010725 if (Invalid)
10726 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010727
Sebastian Redl4b07b292008-12-22 19:15:10 +000010728 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010729 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010730 PushOnScopeChains(ExDecl, S);
10731 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010732 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010733
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010734 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010735 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010736}
Anders Carlssonfb311762009-03-14 00:25:26 +000010737
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010738Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010739 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010740 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010741 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010742 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010743
Richard Smithe3f470a2012-07-11 22:37:56 +000010744 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10745 return 0;
10746
10747 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10748 AssertMessage, RParenLoc, false);
10749}
10750
10751Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10752 Expr *AssertExpr,
10753 StringLiteral *AssertMessage,
10754 SourceLocation RParenLoc,
10755 bool Failed) {
10756 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10757 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010758 // In a static_assert-declaration, the constant-expression shall be a
10759 // constant expression that can be contextually converted to bool.
10760 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10761 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010762 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010763
Richard Smithdaaefc52011-12-14 23:32:26 +000010764 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010765 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010766 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010767 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010768 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010769
Richard Smithe3f470a2012-07-11 22:37:56 +000010770 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010771 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010772 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010773 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010774 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010775 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010776 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010777 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010778 }
Mike Stump1eb44332009-09-09 15:08:12 +000010779
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010780 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010781 AssertExpr, AssertMessage, RParenLoc,
10782 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010783
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010784 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010785 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010786}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010787
Douglas Gregor1d869352010-04-07 16:53:43 +000010788/// \brief Perform semantic analysis of the given friend type declaration.
10789///
10790/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010791FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010792 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010793 TypeSourceInfo *TSInfo) {
10794 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10795
10796 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010797 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010798
Richard Smith6b130222011-10-18 21:39:00 +000010799 // C++03 [class.friend]p2:
10800 // An elaborated-type-specifier shall be used in a friend declaration
10801 // for a class.*
10802 //
10803 // * The class-key of the elaborated-type-specifier is required.
10804 if (!ActiveTemplateInstantiations.empty()) {
10805 // Do not complain about the form of friend template types during
10806 // template instantiation; we will already have complained when the
10807 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010808 } else {
10809 if (!T->isElaboratedTypeSpecifier()) {
10810 // If we evaluated the type to a record type, suggest putting
10811 // a tag in front.
10812 if (const RecordType *RT = T->getAs<RecordType>()) {
10813 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010814
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010815 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010816
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010817 Diag(TypeRange.getBegin(),
10818 getLangOpts().CPlusPlus11 ?
10819 diag::warn_cxx98_compat_unelaborated_friend_type :
10820 diag::ext_unelaborated_friend_type)
10821 << (unsigned) RD->getTagKind()
10822 << T
10823 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10824 InsertionText);
10825 } else {
10826 Diag(FriendLoc,
10827 getLangOpts().CPlusPlus11 ?
10828 diag::warn_cxx98_compat_nonclass_type_friend :
10829 diag::ext_nonclass_type_friend)
10830 << T
10831 << TypeRange;
10832 }
10833 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010834 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010835 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010836 diag::warn_cxx98_compat_enum_friend :
10837 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010838 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010839 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010840 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010841
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010842 // C++11 [class.friend]p3:
10843 // A friend declaration that does not declare a function shall have one
10844 // of the following forms:
10845 // friend elaborated-type-specifier ;
10846 // friend simple-type-specifier ;
10847 // friend typename-specifier ;
10848 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10849 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10850 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010851
Douglas Gregor06245bf2010-04-07 17:57:12 +000010852 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010853 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010854 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010855 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010856}
10857
John McCall9a34edb2010-10-19 01:40:49 +000010858/// Handle a friend tag declaration where the scope specifier was
10859/// templated.
10860Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10861 unsigned TagSpec, SourceLocation TagLoc,
10862 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010863 IdentifierInfo *Name,
10864 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010865 AttributeList *Attr,
10866 MultiTemplateParamsArg TempParamLists) {
10867 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10868
10869 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010870 bool Invalid = false;
10871
10872 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010873 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010874 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010875 TempParamLists.size(),
10876 /*friend*/ true,
10877 isExplicitSpecialization,
10878 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010879 if (TemplateParams->size() > 0) {
10880 // This is a declaration of a class template.
10881 if (Invalid)
10882 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010883
Eric Christopher4110e132011-07-21 05:34:24 +000010884 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10885 SS, Name, NameLoc, Attr,
10886 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010887 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010888 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010889 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010890 } else {
10891 // The "template<>" header is extraneous.
10892 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10893 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10894 isExplicitSpecialization = true;
10895 }
10896 }
10897
10898 if (Invalid) return 0;
10899
John McCall9a34edb2010-10-19 01:40:49 +000010900 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010901 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010902 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010903 isAllExplicitSpecializations = false;
10904 break;
10905 }
10906 }
10907
10908 // FIXME: don't ignore attributes.
10909
10910 // If it's explicit specializations all the way down, just forget
10911 // about the template header and build an appropriate non-templated
10912 // friend. TODO: for source fidelity, remember the headers.
10913 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010914 if (SS.isEmpty()) {
10915 bool Owned = false;
10916 bool IsDependent = false;
10917 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10918 Attr, AS_public,
10919 /*ModulePrivateLoc=*/SourceLocation(),
10920 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010921 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010922 /*ScopedEnumUsesClassTag=*/false,
10923 /*UnderlyingType=*/TypeResult());
10924 }
10925
Douglas Gregor2494dd02011-03-01 01:34:45 +000010926 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010927 ElaboratedTypeKeyword Keyword
10928 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010929 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010930 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010931 if (T.isNull())
10932 return 0;
10933
10934 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10935 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010936 DependentNameTypeLoc TL =
10937 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010938 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010939 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010940 TL.setNameLoc(NameLoc);
10941 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010942 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010943 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010944 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010945 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010946 }
10947
10948 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010949 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010950 Friend->setAccess(AS_public);
10951 CurContext->addDecl(Friend);
10952 return Friend;
10953 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010954
10955 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10956
10957
John McCall9a34edb2010-10-19 01:40:49 +000010958
10959 // Handle the case of a templated-scope friend class. e.g.
10960 // template <class T> class A<T>::B;
10961 // FIXME: we don't support these right now.
10962 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10963 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10964 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010965 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010966 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010967 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010968 TL.setNameLoc(NameLoc);
10969
10970 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010971 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010972 Friend->setAccess(AS_public);
10973 Friend->setUnsupportedFriend(true);
10974 CurContext->addDecl(Friend);
10975 return Friend;
10976}
10977
10978
John McCalldd4a3b02009-09-16 22:47:08 +000010979/// Handle a friend type declaration. This works in tandem with
10980/// ActOnTag.
10981///
10982/// Notes on friend class templates:
10983///
10984/// We generally treat friend class declarations as if they were
10985/// declaring a class. So, for example, the elaborated type specifier
10986/// in a friend declaration is required to obey the restrictions of a
10987/// class-head (i.e. no typedefs in the scope chain), template
10988/// parameters are required to match up with simple template-ids, &c.
10989/// However, unlike when declaring a template specialization, it's
10990/// okay to refer to a template specialization without an empty
10991/// template parameter declaration, e.g.
10992/// friend class A<T>::B<unsigned>;
10993/// We permit this as a special case; if there are any template
10994/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010995/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010996Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010997 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010998 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010999
11000 assert(DS.isFriendSpecified());
11001 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11002
John McCalldd4a3b02009-09-16 22:47:08 +000011003 // Try to convert the decl specifier to a type. This works for
11004 // friend templates because ActOnTag never produces a ClassTemplateDecl
11005 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011006 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011007 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11008 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011009 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011010 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011011
Douglas Gregor6ccab972010-12-16 01:14:37 +000011012 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11013 return 0;
11014
John McCalldd4a3b02009-09-16 22:47:08 +000011015 // This is definitely an error in C++98. It's probably meant to
11016 // be forbidden in C++0x, too, but the specification is just
11017 // poorly written.
11018 //
11019 // The problem is with declarations like the following:
11020 // template <T> friend A<T>::foo;
11021 // where deciding whether a class C is a friend or not now hinges
11022 // on whether there exists an instantiation of A that causes
11023 // 'foo' to equal C. There are restrictions on class-heads
11024 // (which we declare (by fiat) elaborated friend declarations to
11025 // be) that makes this tractable.
11026 //
11027 // FIXME: handle "template <> friend class A<T>;", which
11028 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011029 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011030 Diag(Loc, diag::err_tagless_friend_type_template)
11031 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011032 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011033 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011034
John McCall02cace72009-08-28 07:59:38 +000011035 // C++98 [class.friend]p1: A friend of a class is a function
11036 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011037 // This is fixed in DR77, which just barely didn't make the C++03
11038 // deadline. It's also a very silly restriction that seriously
11039 // affects inner classes and which nobody else seems to implement;
11040 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011041 //
11042 // But note that we could warn about it: it's always useless to
11043 // friend one of your own members (it's not, however, worthless to
11044 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011045
John McCalldd4a3b02009-09-16 22:47:08 +000011046 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011047 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011048 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011049 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011050 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011051 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011052 DS.getFriendSpecLoc());
11053 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011054 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011055
11056 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011057 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011058
John McCalldd4a3b02009-09-16 22:47:08 +000011059 D->setAccess(AS_public);
11060 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011061
John McCalld226f652010-08-21 09:40:31 +000011062 return D;
John McCall02cace72009-08-28 07:59:38 +000011063}
11064
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011065NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11066 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011067 const DeclSpec &DS = D.getDeclSpec();
11068
11069 assert(DS.isFriendSpecified());
11070 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11071
11072 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011073 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011074
11075 // C++ [class.friend]p1
11076 // A friend of a class is a function or class....
11077 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011078 // It *doesn't* see through dependent types, which is correct
11079 // according to [temp.arg.type]p3:
11080 // If a declaration acquires a function type through a
11081 // type dependent on a template-parameter and this causes
11082 // a declaration that does not use the syntactic form of a
11083 // function declarator to have a function type, the program
11084 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011085 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011086 Diag(Loc, diag::err_unexpected_friend);
11087
11088 // It might be worthwhile to try to recover by creating an
11089 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011090 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011091 }
11092
11093 // C++ [namespace.memdef]p3
11094 // - If a friend declaration in a non-local class first declares a
11095 // class or function, the friend class or function is a member
11096 // of the innermost enclosing namespace.
11097 // - The name of the friend is not found by simple name lookup
11098 // until a matching declaration is provided in that namespace
11099 // scope (either before or after the class declaration granting
11100 // friendship).
11101 // - If a friend function is called, its name may be found by the
11102 // name lookup that considers functions from namespaces and
11103 // classes associated with the types of the function arguments.
11104 // - When looking for a prior declaration of a class or a function
11105 // declared as a friend, scopes outside the innermost enclosing
11106 // namespace scope are not considered.
11107
John McCall337ec3d2010-10-12 23:13:28 +000011108 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011109 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11110 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011111 assert(Name);
11112
Douglas Gregor6ccab972010-12-16 01:14:37 +000011113 // Check for unexpanded parameter packs.
11114 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11115 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11116 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11117 return 0;
11118
John McCall67d1a672009-08-06 02:15:43 +000011119 // The context we found the declaration in, or in which we should
11120 // create the declaration.
11121 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011122 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011123 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011124 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011125
John McCall337ec3d2010-10-12 23:13:28 +000011126 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000011127
John McCall337ec3d2010-10-12 23:13:28 +000011128 // There are four cases here.
11129 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000011130 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000011131 // there as appropriate.
11132 // Recover from invalid scope qualifiers as if they just weren't there.
11133 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000011134 // C++0x [namespace.memdef]p3:
11135 // If the name in a friend declaration is neither qualified nor
11136 // a template-id and the declaration is a function or an
11137 // elaborated-type-specifier, the lookup to determine whether
11138 // the entity has been previously declared shall not consider
11139 // any scopes outside the innermost enclosing namespace.
11140 // C++0x [class.friend]p11:
11141 // If a friend declaration appears in a local class and the name
11142 // specified is an unqualified name, a prior declaration is
11143 // looked up without considering scopes that are outside the
11144 // innermost enclosing non-class scope. For a friend function
11145 // declaration, if there is no prior declaration, the program is
11146 // ill-formed.
11147 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000011148 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011149
John McCall29ae6e52010-10-13 05:45:15 +000011150 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011151 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011152
Rafael Espindola11dc6342013-04-25 20:12:36 +000011153 // Skip class contexts. If someone can cite chapter and verse
11154 // for this behavior, that would be nice --- it's what GCC and
11155 // EDG do, and it seems like a reasonable intent, but the spec
11156 // really only says that checks for unqualified existing
11157 // declarations should stop at the nearest enclosing namespace,
11158 // not that they should only consider the nearest enclosing
11159 // namespace.
11160 while (DC->isRecord())
11161 DC = DC->getParent();
11162
11163 DeclContext *LookupDC = DC;
11164 while (LookupDC->isTransparentContext())
11165 LookupDC = LookupDC->getParent();
11166
11167 while (true) {
11168 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011169
11170 // TODO: decide what we think about using declarations.
Rafael Espindola11dc6342013-04-25 20:12:36 +000011171 if (isLocal)
John McCall67d1a672009-08-06 02:15:43 +000011172 break;
John McCall29ae6e52010-10-13 05:45:15 +000011173
Rafael Espindola11dc6342013-04-25 20:12:36 +000011174 if (!Previous.empty()) {
11175 DC = LookupDC;
11176 break;
John McCall8a407372010-10-14 22:22:28 +000011177 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011178
11179 if (isTemplateId) {
11180 if (isa<TranslationUnitDecl>(LookupDC)) break;
11181 } else {
11182 if (LookupDC->isFileContext()) break;
11183 }
11184 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011185 }
11186
John McCall380aaa42010-10-13 06:22:15 +000011187 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011188
Douglas Gregor883af832011-10-10 01:11:59 +000011189 // C++ [class.friend]p6:
11190 // A function can be defined in a friend declaration of a class if and
11191 // only if the class is a non-local class (9.8), the function name is
11192 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011193 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011194 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11195 }
11196
John McCall337ec3d2010-10-12 23:13:28 +000011197 // - There's a non-dependent scope specifier, in which case we
11198 // compute it and do a previous lookup there for a function
11199 // or function template.
11200 } else if (!SS.getScopeRep()->isDependent()) {
11201 DC = computeDeclContext(SS);
11202 if (!DC) return 0;
11203
11204 if (RequireCompleteDeclContext(SS, DC)) return 0;
11205
11206 LookupQualifiedName(Previous, DC);
11207
11208 // Ignore things found implicitly in the wrong scope.
11209 // TODO: better diagnostics for this case. Suggesting the right
11210 // qualified scope would be nice...
11211 LookupResult::Filter F = Previous.makeFilter();
11212 while (F.hasNext()) {
11213 NamedDecl *D = F.next();
11214 if (!DC->InEnclosingNamespaceSetOf(
11215 D->getDeclContext()->getRedeclContext()))
11216 F.erase();
11217 }
11218 F.done();
11219
11220 if (Previous.empty()) {
11221 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011222 Diag(Loc, diag::err_qualified_friend_not_found)
11223 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011224 return 0;
11225 }
11226
11227 // C++ [class.friend]p1: A friend of a class is a function or
11228 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011229 if (DC->Equals(CurContext))
11230 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011231 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011232 diag::warn_cxx98_compat_friend_is_member :
11233 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011234
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011235 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011236 // C++ [class.friend]p6:
11237 // A function can be defined in a friend declaration of a class if and
11238 // only if the class is a non-local class (9.8), the function name is
11239 // unqualified, and the function has namespace scope.
11240 SemaDiagnosticBuilder DB
11241 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11242
11243 DB << SS.getScopeRep();
11244 if (DC->isFileContext())
11245 DB << FixItHint::CreateRemoval(SS.getRange());
11246 SS.clear();
11247 }
John McCall337ec3d2010-10-12 23:13:28 +000011248
11249 // - There's a scope specifier that does not match any template
11250 // parameter lists, in which case we use some arbitrary context,
11251 // create a method or method template, and wait for instantiation.
11252 // - There's a scope specifier that does match some template
11253 // parameter lists, which we don't handle right now.
11254 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011255 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011256 // C++ [class.friend]p6:
11257 // A function can be defined in a friend declaration of a class if and
11258 // only if the class is a non-local class (9.8), the function name is
11259 // unqualified, and the function has namespace scope.
11260 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11261 << SS.getScopeRep();
11262 }
11263
John McCall337ec3d2010-10-12 23:13:28 +000011264 DC = CurContext;
11265 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011266 }
Douglas Gregor883af832011-10-10 01:11:59 +000011267
John McCall29ae6e52010-10-13 05:45:15 +000011268 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011269 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011270 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11271 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11272 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011273 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011274 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11275 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011276 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011277 }
John McCall67d1a672009-08-06 02:15:43 +000011278 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011279
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011280 // FIXME: This is an egregious hack to cope with cases where the scope stack
11281 // does not contain the declaration context, i.e., in an out-of-line
11282 // definition of a class.
11283 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11284 if (!DCScope) {
11285 FakeDCScope.setEntity(DC);
11286 DCScope = &FakeDCScope;
11287 }
11288
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011289 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011290 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011291 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011292 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011293
Douglas Gregor182ddf02009-09-28 00:08:27 +000011294 assert(ND->getDeclContext() == DC);
11295 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011296
John McCallab88d972009-08-31 22:39:49 +000011297 // Add the function declaration to the appropriate lookup tables,
11298 // adjusting the redeclarations list as necessary. We don't
11299 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011300 //
John McCallab88d972009-08-31 22:39:49 +000011301 // Also update the scope-based lookup if the target context's
11302 // lookup context is in lexical scope.
11303 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011304 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011305 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011306 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011307 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011308 }
John McCall02cace72009-08-28 07:59:38 +000011309
11310 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011311 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011312 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011313 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011314 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011315
John McCall1f2e1a92012-08-10 03:15:35 +000011316 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011317 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011318 } else {
11319 if (DC->isRecord()) CheckFriendAccess(ND);
11320
John McCall6102ca12010-10-16 06:59:13 +000011321 FunctionDecl *FD;
11322 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11323 FD = FTD->getTemplatedDecl();
11324 else
11325 FD = cast<FunctionDecl>(ND);
11326
11327 // Mark templated-scope function declarations as unsupported.
11328 if (FD->getNumTemplateParameterLists())
11329 FrD->setUnsupportedFriend(true);
11330 }
John McCall337ec3d2010-10-12 23:13:28 +000011331
John McCalld226f652010-08-21 09:40:31 +000011332 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011333}
11334
John McCalld226f652010-08-21 09:40:31 +000011335void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11336 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011337
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011338 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011339 if (!Fn) {
11340 Diag(DelLoc, diag::err_deleted_non_function);
11341 return;
11342 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011343
Douglas Gregoref96ee02012-01-14 16:38:05 +000011344 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011345 // Don't consider the implicit declaration we generate for explicit
11346 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011347 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11348 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011349 Diag(DelLoc, diag::err_deleted_decl_not_first);
11350 Diag(Prev->getLocation(), diag::note_previous_declaration);
11351 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011352 // If the declaration wasn't the first, we delete the function anyway for
11353 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011354 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011355 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011356
11357 if (Fn->isDeleted())
11358 return;
11359
11360 // See if we're deleting a function which is already known to override a
11361 // non-deleted virtual function.
11362 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11363 bool IssuedDiagnostic = false;
11364 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11365 E = MD->end_overridden_methods();
11366 I != E; ++I) {
11367 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11368 if (!IssuedDiagnostic) {
11369 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11370 IssuedDiagnostic = true;
11371 }
11372 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11373 }
11374 }
11375 }
11376
Sean Hunt10620eb2011-05-06 20:44:56 +000011377 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011378}
Sebastian Redl13e88542009-04-27 21:33:24 +000011379
Sean Hunte4246a62011-05-12 06:15:49 +000011380void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011381 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011382
11383 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011384 if (MD->getParent()->isDependentType()) {
11385 MD->setDefaulted();
11386 MD->setExplicitlyDefaulted();
11387 return;
11388 }
11389
Sean Hunte4246a62011-05-12 06:15:49 +000011390 CXXSpecialMember Member = getSpecialMember(MD);
11391 if (Member == CXXInvalid) {
11392 Diag(DefaultLoc, diag::err_default_special_members);
11393 return;
11394 }
11395
11396 MD->setDefaulted();
11397 MD->setExplicitlyDefaulted();
11398
Sean Huntcd10dec2011-05-23 23:14:04 +000011399 // If this definition appears within the record, do the checking when
11400 // the record is complete.
11401 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011402 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011403 // Find the uninstantiated declaration that actually had the '= default'
11404 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011405 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011406
Richard Smith12fef492013-03-27 00:22:47 +000011407 // If the method was defaulted on its first declaration, we will have
11408 // already performed the checking in CheckCompletedCXXClass. Such a
11409 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011410 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011411 return;
11412
Richard Smithb9d0b762012-07-27 04:22:15 +000011413 CheckExplicitlyDefaultedSpecialMember(MD);
11414
Richard Smith1d28caf2012-12-11 01:14:52 +000011415 // The exception specification is needed because we are defining the
11416 // function.
11417 ResolveExceptionSpec(DefaultLoc,
11418 MD->getType()->castAs<FunctionProtoType>());
11419
Sean Hunte4246a62011-05-12 06:15:49 +000011420 switch (Member) {
11421 case CXXDefaultConstructor: {
11422 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011423 if (!CD->isInvalidDecl())
11424 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11425 break;
11426 }
11427
11428 case CXXCopyConstructor: {
11429 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011430 if (!CD->isInvalidDecl())
11431 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011432 break;
11433 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011434
Sean Hunt2b188082011-05-14 05:23:28 +000011435 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011436 if (!MD->isInvalidDecl())
11437 DefineImplicitCopyAssignment(DefaultLoc, MD);
11438 break;
11439 }
11440
Sean Huntcb45a0f2011-05-12 22:46:25 +000011441 case CXXDestructor: {
11442 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011443 if (!DD->isInvalidDecl())
11444 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011445 break;
11446 }
11447
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011448 case CXXMoveConstructor: {
11449 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011450 if (!CD->isInvalidDecl())
11451 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011452 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011453 }
Sean Hunt82713172011-05-25 23:16:36 +000011454
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011455 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011456 if (!MD->isInvalidDecl())
11457 DefineImplicitMoveAssignment(DefaultLoc, MD);
11458 break;
11459 }
11460
11461 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011462 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011463 }
11464 } else {
11465 Diag(DefaultLoc, diag::err_default_special_members);
11466 }
11467}
11468
Sebastian Redl13e88542009-04-27 21:33:24 +000011469static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011470 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011471 Stmt *SubStmt = *CI;
11472 if (!SubStmt)
11473 continue;
11474 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011475 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011476 diag::err_return_in_constructor_handler);
11477 if (!isa<Expr>(SubStmt))
11478 SearchForReturnInStmt(Self, SubStmt);
11479 }
11480}
11481
11482void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11483 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11484 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11485 SearchForReturnInStmt(*this, Handler);
11486 }
11487}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011488
David Blaikie299adab2013-01-18 23:03:15 +000011489bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011490 const CXXMethodDecl *Old) {
11491 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11492 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11493
11494 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11495
11496 // If the calling conventions match, everything is fine
11497 if (NewCC == OldCC)
11498 return false;
11499
11500 // If either of the calling conventions are set to "default", we need to pick
11501 // something more sensible based on the target. This supports code where the
11502 // one method explicitly sets thiscall, and another has no explicit calling
11503 // convention.
11504 CallingConv Default =
11505 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11506 if (NewCC == CC_Default)
11507 NewCC = Default;
11508 if (OldCC == CC_Default)
11509 OldCC = Default;
11510
11511 // If the calling conventions still don't match, then report the error
11512 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011513 Diag(New->getLocation(),
11514 diag::err_conflicting_overriding_cc_attributes)
11515 << New->getDeclName() << New->getType() << Old->getType();
11516 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11517 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011518 }
11519
11520 return false;
11521}
11522
Mike Stump1eb44332009-09-09 15:08:12 +000011523bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011524 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011525 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11526 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011527
Chandler Carruth73857792010-02-15 11:53:20 +000011528 if (Context.hasSameType(NewTy, OldTy) ||
11529 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011530 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011531
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011532 // Check if the return types are covariant
11533 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011534
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011535 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011536 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11537 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011538 NewClassTy = NewPT->getPointeeType();
11539 OldClassTy = OldPT->getPointeeType();
11540 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011541 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11542 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11543 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11544 NewClassTy = NewRT->getPointeeType();
11545 OldClassTy = OldRT->getPointeeType();
11546 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011547 }
11548 }
Mike Stump1eb44332009-09-09 15:08:12 +000011549
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011550 // The return types aren't either both pointers or references to a class type.
11551 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011552 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011553 diag::err_different_return_type_for_overriding_virtual_function)
11554 << New->getDeclName() << NewTy << OldTy;
11555 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011556
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011557 return true;
11558 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011559
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011560 // C++ [class.virtual]p6:
11561 // If the return type of D::f differs from the return type of B::f, the
11562 // class type in the return type of D::f shall be complete at the point of
11563 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011564 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11565 if (!RT->isBeingDefined() &&
11566 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011567 diag::err_covariant_return_incomplete,
11568 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011569 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011570 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011571
Douglas Gregora4923eb2009-11-16 21:35:15 +000011572 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011573 // Check if the new class derives from the old class.
11574 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11575 Diag(New->getLocation(),
11576 diag::err_covariant_return_not_derived)
11577 << New->getDeclName() << NewTy << OldTy;
11578 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11579 return true;
11580 }
Mike Stump1eb44332009-09-09 15:08:12 +000011581
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011582 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011583 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011584 diag::err_covariant_return_inaccessible_base,
11585 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11586 // FIXME: Should this point to the return type?
11587 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011588 // FIXME: this note won't trigger for delayed access control
11589 // diagnostics, and it's impossible to get an undelayed error
11590 // here from access control during the original parse because
11591 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011592 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11593 return true;
11594 }
11595 }
Mike Stump1eb44332009-09-09 15:08:12 +000011596
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011597 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011598 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011599 Diag(New->getLocation(),
11600 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011601 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011602 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11603 return true;
11604 };
Mike Stump1eb44332009-09-09 15:08:12 +000011605
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011606
11607 // The new class type must have the same or less qualifiers as the old type.
11608 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11609 Diag(New->getLocation(),
11610 diag::err_covariant_return_type_class_type_more_qualified)
11611 << New->getDeclName() << NewTy << OldTy;
11612 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11613 return true;
11614 };
Mike Stump1eb44332009-09-09 15:08:12 +000011615
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011616 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011617}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011618
Douglas Gregor4ba31362009-12-01 17:24:26 +000011619/// \brief Mark the given method pure.
11620///
11621/// \param Method the method to be marked pure.
11622///
11623/// \param InitRange the source range that covers the "0" initializer.
11624bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011625 SourceLocation EndLoc = InitRange.getEnd();
11626 if (EndLoc.isValid())
11627 Method->setRangeEnd(EndLoc);
11628
Douglas Gregor4ba31362009-12-01 17:24:26 +000011629 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11630 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011631 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011632 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011633
11634 if (!Method->isInvalidDecl())
11635 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11636 << Method->getDeclName() << InitRange;
11637 return true;
11638}
11639
Douglas Gregor552e2992012-02-21 02:22:07 +000011640/// \brief Determine whether the given declaration is a static data member.
11641static bool isStaticDataMember(Decl *D) {
11642 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11643 if (!Var)
11644 return false;
11645
11646 return Var->isStaticDataMember();
11647}
John McCall731ad842009-12-19 09:28:58 +000011648/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11649/// an initializer for the out-of-line declaration 'Dcl'. The scope
11650/// is a fresh scope pushed for just this purpose.
11651///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011652/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11653/// static data member of class X, names should be looked up in the scope of
11654/// class X.
John McCalld226f652010-08-21 09:40:31 +000011655void Sema::ActOnCXXEnterDeclInitializer(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
John McCall731ad842009-12-19 09:28:58 +000011659 // We should only get called for declarations with scope specifiers, like:
11660 // int foo::bar;
11661 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011662 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011663
11664 // If we are parsing the initializer for a static data member, push a
11665 // new expression evaluation context that is associated with this static
11666 // data member.
11667 if (isStaticDataMember(D))
11668 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011669}
11670
11671/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011672/// initializer for the out-of-line declaration 'D'.
11673void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011674 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011675 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011676
Douglas Gregor552e2992012-02-21 02:22:07 +000011677 if (isStaticDataMember(D))
11678 PopExpressionEvaluationContext();
11679
John McCall731ad842009-12-19 09:28:58 +000011680 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011681 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011682}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011683
11684/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11685/// C++ if/switch/while/for statement.
11686/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011687DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011688 // C++ 6.4p2:
11689 // The declarator shall not specify a function or an array.
11690 // The type-specifier-seq shall not contain typedef and shall not declare a
11691 // new class or enumeration.
11692 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11693 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011694
11695 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011696 if (!Dcl)
11697 return true;
11698
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011699 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11700 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011701 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011702 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011703 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011704
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011705 return Dcl;
11706}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011707
Douglas Gregordfe65432011-07-28 19:11:31 +000011708void Sema::LoadExternalVTableUses() {
11709 if (!ExternalSource)
11710 return;
11711
11712 SmallVector<ExternalVTableUse, 4> VTables;
11713 ExternalSource->ReadUsedVTables(VTables);
11714 SmallVector<VTableUse, 4> NewUses;
11715 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11716 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11717 = VTablesUsed.find(VTables[I].Record);
11718 // Even if a definition wasn't required before, it may be required now.
11719 if (Pos != VTablesUsed.end()) {
11720 if (!Pos->second && VTables[I].DefinitionRequired)
11721 Pos->second = true;
11722 continue;
11723 }
11724
11725 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11726 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11727 }
11728
11729 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11730}
11731
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011732void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11733 bool DefinitionRequired) {
11734 // Ignore any vtable uses in unevaluated operands or for classes that do
11735 // not have a vtable.
11736 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011737 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011738 return;
11739
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011740 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011741 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011742 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11743 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11744 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11745 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011746 // If we already had an entry, check to see if we are promoting this vtable
11747 // to required a definition. If so, we need to reappend to the VTableUses
11748 // list, since we may have already processed the first entry.
11749 if (DefinitionRequired && !Pos.first->second) {
11750 Pos.first->second = true;
11751 } else {
11752 // Otherwise, we can early exit.
11753 return;
11754 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011755 }
11756
11757 // Local classes need to have their virtual members marked
11758 // immediately. For all other classes, we mark their virtual members
11759 // at the end of the translation unit.
11760 if (Class->isLocalClass())
11761 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011762 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011763 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011764}
11765
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011766bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011767 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011768 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011769 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011770
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011771 // Note: The VTableUses vector could grow as a result of marking
11772 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011773 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011774 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011775 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011776 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011777 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011778 if (!Class)
11779 continue;
11780
11781 SourceLocation Loc = VTableUses[I].second;
11782
Richard Smithb9d0b762012-07-27 04:22:15 +000011783 bool DefineVTable = true;
11784
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011785 // If this class has a key function, but that key function is
11786 // defined in another translation unit, we don't need to emit the
11787 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011788 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011789 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011790 switch (KeyFunction->getTemplateSpecializationKind()) {
11791 case TSK_Undeclared:
11792 case TSK_ExplicitSpecialization:
11793 case TSK_ExplicitInstantiationDeclaration:
11794 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011795 DefineVTable = false;
11796 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011797
11798 case TSK_ExplicitInstantiationDefinition:
11799 case TSK_ImplicitInstantiation:
11800 // We will be instantiating the key function.
11801 break;
11802 }
11803 } else if (!KeyFunction) {
11804 // If we have a class with no key function that is the subject
11805 // of an explicit instantiation declaration, suppress the
11806 // vtable; it will live with the explicit instantiation
11807 // definition.
11808 bool IsExplicitInstantiationDeclaration
11809 = Class->getTemplateSpecializationKind()
11810 == TSK_ExplicitInstantiationDeclaration;
11811 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11812 REnd = Class->redecls_end();
11813 R != REnd; ++R) {
11814 TemplateSpecializationKind TSK
11815 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11816 if (TSK == TSK_ExplicitInstantiationDeclaration)
11817 IsExplicitInstantiationDeclaration = true;
11818 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11819 IsExplicitInstantiationDeclaration = false;
11820 break;
11821 }
11822 }
11823
11824 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011825 DefineVTable = false;
11826 }
11827
11828 // The exception specifications for all virtual members may be needed even
11829 // if we are not providing an authoritative form of the vtable in this TU.
11830 // We may choose to emit it available_externally anyway.
11831 if (!DefineVTable) {
11832 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11833 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011834 }
11835
11836 // Mark all of the virtual members of this class as referenced, so
11837 // that we can build a vtable. Then, tell the AST consumer that a
11838 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011839 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011840 MarkVirtualMembersReferenced(Loc, Class);
11841 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11842 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11843
11844 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000011845 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011846 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011847 const FunctionDecl *KeyFunctionDef = 0;
11848 if (!KeyFunction ||
11849 (KeyFunction->hasBody(KeyFunctionDef) &&
11850 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011851 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11852 TSK_ExplicitInstantiationDefinition
11853 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11854 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011855 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011856 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011857 VTableUses.clear();
11858
Douglas Gregor78844032011-04-22 22:25:37 +000011859 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011860}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011861
Richard Smithb9d0b762012-07-27 04:22:15 +000011862void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11863 const CXXRecordDecl *RD) {
11864 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11865 E = RD->method_end(); I != E; ++I)
11866 if ((*I)->isVirtual() && !(*I)->isPure())
11867 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11868}
11869
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011870void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11871 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011872 // Mark all functions which will appear in RD's vtable as used.
11873 CXXFinalOverriderMap FinalOverriders;
11874 RD->getFinalOverriders(FinalOverriders);
11875 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11876 E = FinalOverriders.end();
11877 I != E; ++I) {
11878 for (OverridingMethods::const_iterator OI = I->second.begin(),
11879 OE = I->second.end();
11880 OI != OE; ++OI) {
11881 assert(OI->second.size() > 0 && "no final overrider");
11882 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011883
Richard Smithff817f72012-07-07 06:59:51 +000011884 // C++ [basic.def.odr]p2:
11885 // [...] A virtual member function is used if it is not pure. [...]
11886 if (!Overrider->isPure())
11887 MarkFunctionReferenced(Loc, Overrider);
11888 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011889 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011890
11891 // Only classes that have virtual bases need a VTT.
11892 if (RD->getNumVBases() == 0)
11893 return;
11894
11895 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11896 e = RD->bases_end(); i != e; ++i) {
11897 const CXXRecordDecl *Base =
11898 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011899 if (Base->getNumVBases() == 0)
11900 continue;
11901 MarkVirtualMembersReferenced(Loc, Base);
11902 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011903}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011904
11905/// SetIvarInitializers - This routine builds initialization ASTs for the
11906/// Objective-C implementation whose ivars need be initialized.
11907void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011908 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011909 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011910 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011911 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011912 CollectIvarsToConstructOrDestruct(OID, ivars);
11913 if (ivars.empty())
11914 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011915 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011916 for (unsigned i = 0; i < ivars.size(); i++) {
11917 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011918 if (Field->isInvalidDecl())
11919 continue;
11920
Sean Huntcbb67482011-01-08 20:30:50 +000011921 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011922 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11923 InitializationKind InitKind =
11924 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011925
11926 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
11927 ExprResult MemberInit =
11928 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000011929 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011930 // Note, MemberInit could actually come back empty if no initialization
11931 // is required (e.g., because it would call a trivial default constructor)
11932 if (!MemberInit.get() || MemberInit.isInvalid())
11933 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011934
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011935 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011936 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11937 SourceLocation(),
11938 MemberInit.takeAs<Expr>(),
11939 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011940 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011941
11942 // Be sure that the destructor is accessible and is marked as referenced.
11943 if (const RecordType *RecordTy
11944 = Context.getBaseElementType(Field->getType())
11945 ->getAs<RecordType>()) {
11946 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011947 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011948 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011949 CheckDestructorAccess(Field->getLocation(), Destructor,
11950 PDiag(diag::err_access_dtor_ivar)
11951 << Context.getBaseElementType(Field->getType()));
11952 }
11953 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011954 }
11955 ObjCImplementation->setIvarInitializers(Context,
11956 AllToInit.data(), AllToInit.size());
11957 }
11958}
Sean Huntfe57eef2011-05-04 05:57:24 +000011959
Sean Huntebcbe1d2011-05-04 23:29:54 +000011960static
11961void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11962 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11963 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11964 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11965 Sema &S) {
11966 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11967 CE = Current.end();
11968 if (Ctor->isInvalidDecl())
11969 return;
11970
Richard Smitha8eaf002012-08-23 06:16:52 +000011971 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11972
11973 // Target may not be determinable yet, for instance if this is a dependent
11974 // call in an uninstantiated template.
11975 if (Target) {
11976 const FunctionDecl *FNTarget = 0;
11977 (void)Target->hasBody(FNTarget);
11978 Target = const_cast<CXXConstructorDecl*>(
11979 cast_or_null<CXXConstructorDecl>(FNTarget));
11980 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011981
11982 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11983 // Avoid dereferencing a null pointer here.
11984 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11985
11986 if (!Current.insert(Canonical))
11987 return;
11988
11989 // We know that beyond here, we aren't chaining into a cycle.
11990 if (!Target || !Target->isDelegatingConstructor() ||
11991 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11992 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11993 Valid.insert(*CI);
11994 Current.clear();
11995 // We've hit a cycle.
11996 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11997 Current.count(TCanonical)) {
11998 // If we haven't diagnosed this cycle yet, do so now.
11999 if (!Invalid.count(TCanonical)) {
12000 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012001 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012002 << Ctor;
12003
Richard Smitha8eaf002012-08-23 06:16:52 +000012004 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012005 if (TCanonical != Canonical)
12006 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12007
12008 CXXConstructorDecl *C = Target;
12009 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012010 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012011 (void)C->getTargetConstructor()->hasBody(FNTarget);
12012 assert(FNTarget && "Ctor cycle through bodiless function");
12013
Richard Smitha8eaf002012-08-23 06:16:52 +000012014 C = const_cast<CXXConstructorDecl*>(
12015 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012016 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12017 }
12018 }
12019
12020 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12021 Invalid.insert(*CI);
12022 Current.clear();
12023 } else {
12024 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12025 }
12026}
12027
12028
Sean Huntfe57eef2011-05-04 05:57:24 +000012029void Sema::CheckDelegatingCtorCycles() {
12030 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12031
Sean Huntebcbe1d2011-05-04 23:29:54 +000012032 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12033 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000012034
Douglas Gregor0129b562011-07-27 21:57:17 +000012035 for (DelegatingCtorDeclsType::iterator
12036 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012037 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012038 I != E; ++I)
12039 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012040
12041 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12042 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012043}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012044
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012045namespace {
12046 /// \brief AST visitor that finds references to the 'this' expression.
12047 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12048 Sema &S;
12049
12050 public:
12051 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12052
12053 bool VisitCXXThisExpr(CXXThisExpr *E) {
12054 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12055 << E->isImplicit();
12056 return false;
12057 }
12058 };
12059}
12060
12061bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12062 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12063 if (!TSInfo)
12064 return false;
12065
12066 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012067 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012068 if (!ProtoTL)
12069 return false;
12070
12071 // C++11 [expr.prim.general]p3:
12072 // [The expression this] shall not appear before the optional
12073 // cv-qualifier-seq and it shall not appear within the declaration of a
12074 // static member function (although its type and value category are defined
12075 // within a static member function as they are within a non-static member
12076 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012077 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012078 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012079 FindCXXThisExpr Finder(*this);
12080
12081 // If the return type came after the cv-qualifier-seq, check it now.
12082 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012083 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012084 return true;
12085
12086 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012087 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12088 return true;
12089
12090 return checkThisInStaticMemberFunctionAttributes(Method);
12091}
12092
12093bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12094 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12095 if (!TSInfo)
12096 return false;
12097
12098 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012099 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012100 if (!ProtoTL)
12101 return false;
12102
David Blaikie39e6ab42013-02-18 22:06:02 +000012103 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012104 FindCXXThisExpr Finder(*this);
12105
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012106 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012107 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012108 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012109 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012110 case EST_DynamicNone:
12111 case EST_MSAny:
12112 case EST_None:
12113 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012114
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012115 case EST_ComputedNoexcept:
12116 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12117 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012118
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012119 case EST_Dynamic:
12120 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012121 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012122 E != EEnd; ++E) {
12123 if (!Finder.TraverseType(*E))
12124 return true;
12125 }
12126 break;
12127 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012128
12129 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012130}
12131
12132bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12133 FindCXXThisExpr Finder(*this);
12134
12135 // Check attributes.
12136 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12137 A != AEnd; ++A) {
12138 // FIXME: This should be emitted by tblgen.
12139 Expr *Arg = 0;
12140 ArrayRef<Expr *> Args;
12141 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12142 Arg = G->getArg();
12143 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12144 Arg = G->getArg();
12145 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12146 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12147 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12148 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12149 else if (ExclusiveLockFunctionAttr *ELF
12150 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12151 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12152 else if (SharedLockFunctionAttr *SLF
12153 = dyn_cast<SharedLockFunctionAttr>(*A))
12154 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12155 else if (ExclusiveTrylockFunctionAttr *ETLF
12156 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12157 Arg = ETLF->getSuccessValue();
12158 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12159 } else if (SharedTrylockFunctionAttr *STLF
12160 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12161 Arg = STLF->getSuccessValue();
12162 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12163 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12164 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12165 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12166 Arg = LR->getArg();
12167 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12168 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12169 else if (ExclusiveLocksRequiredAttr *ELR
12170 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12171 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12172 else if (SharedLocksRequiredAttr *SLR
12173 = dyn_cast<SharedLocksRequiredAttr>(*A))
12174 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12175
12176 if (Arg && !Finder.TraverseStmt(Arg))
12177 return true;
12178
12179 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12180 if (!Finder.TraverseStmt(Args[I]))
12181 return true;
12182 }
12183 }
12184
12185 return false;
12186}
12187
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012188void
12189Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12190 ArrayRef<ParsedType> DynamicExceptions,
12191 ArrayRef<SourceRange> DynamicExceptionRanges,
12192 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012193 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012194 FunctionProtoType::ExtProtoInfo &EPI) {
12195 Exceptions.clear();
12196 EPI.ExceptionSpecType = EST;
12197 if (EST == EST_Dynamic) {
12198 Exceptions.reserve(DynamicExceptions.size());
12199 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12200 // FIXME: Preserve type source info.
12201 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12202
12203 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12204 collectUnexpandedParameterPacks(ET, Unexpanded);
12205 if (!Unexpanded.empty()) {
12206 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12207 UPPC_ExceptionType,
12208 Unexpanded);
12209 continue;
12210 }
12211
12212 // Check that the type is valid for an exception spec, and
12213 // drop it if not.
12214 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12215 Exceptions.push_back(ET);
12216 }
12217 EPI.NumExceptions = Exceptions.size();
12218 EPI.Exceptions = Exceptions.data();
12219 return;
12220 }
12221
12222 if (EST == EST_ComputedNoexcept) {
12223 // If an error occurred, there's no expression here.
12224 if (NoexceptExpr) {
12225 assert((NoexceptExpr->isTypeDependent() ||
12226 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12227 Context.BoolTy) &&
12228 "Parser should have made sure that the expression is boolean");
12229 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12230 EPI.ExceptionSpecType = EST_BasicNoexcept;
12231 return;
12232 }
12233
12234 if (!NoexceptExpr->isValueDependent())
12235 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012236 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012237 /*AllowFold*/ false).take();
12238 EPI.NoexceptExpr = NoexceptExpr;
12239 }
12240 return;
12241 }
12242}
12243
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012244/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12245Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12246 // Implicitly declared functions (e.g. copy constructors) are
12247 // __host__ __device__
12248 if (D->isImplicit())
12249 return CFT_HostDevice;
12250
12251 if (D->hasAttr<CUDAGlobalAttr>())
12252 return CFT_Global;
12253
12254 if (D->hasAttr<CUDADeviceAttr>()) {
12255 if (D->hasAttr<CUDAHostAttr>())
12256 return CFT_HostDevice;
12257 else
12258 return CFT_Device;
12259 }
12260
12261 return CFT_Host;
12262}
12263
12264bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12265 CUDAFunctionTarget CalleeTarget) {
12266 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12267 // Callable from the device only."
12268 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12269 return true;
12270
12271 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12272 // Callable from the host only."
12273 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12274 // Callable from the host only."
12275 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12276 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12277 return true;
12278
12279 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12280 return true;
12281
12282 return false;
12283}
John McCall76da55d2013-04-16 07:28:30 +000012284
12285/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12286///
12287MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12288 SourceLocation DeclStart,
12289 Declarator &D, Expr *BitWidth,
12290 InClassInitStyle InitStyle,
12291 AccessSpecifier AS,
12292 AttributeList *MSPropertyAttr) {
12293 IdentifierInfo *II = D.getIdentifier();
12294 if (!II) {
12295 Diag(DeclStart, diag::err_anonymous_property);
12296 return NULL;
12297 }
12298 SourceLocation Loc = D.getIdentifierLoc();
12299
12300 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12301 QualType T = TInfo->getType();
12302 if (getLangOpts().CPlusPlus) {
12303 CheckExtraCXXDefaultArguments(D);
12304
12305 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12306 UPPC_DataMemberType)) {
12307 D.setInvalidType();
12308 T = Context.IntTy;
12309 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12310 }
12311 }
12312
12313 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12314
12315 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12316 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12317 diag::err_invalid_thread)
12318 << DeclSpec::getSpecifierName(TSCS);
12319
12320 // Check to see if this name was declared as a member previously
12321 NamedDecl *PrevDecl = 0;
12322 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12323 LookupName(Previous, S);
12324 switch (Previous.getResultKind()) {
12325 case LookupResult::Found:
12326 case LookupResult::FoundUnresolvedValue:
12327 PrevDecl = Previous.getAsSingle<NamedDecl>();
12328 break;
12329
12330 case LookupResult::FoundOverloaded:
12331 PrevDecl = Previous.getRepresentativeDecl();
12332 break;
12333
12334 case LookupResult::NotFound:
12335 case LookupResult::NotFoundInCurrentInstantiation:
12336 case LookupResult::Ambiguous:
12337 break;
12338 }
12339
12340 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12341 // Maybe we will complain about the shadowed template parameter.
12342 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12343 // Just pretend that we didn't see the previous declaration.
12344 PrevDecl = 0;
12345 }
12346
12347 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12348 PrevDecl = 0;
12349
12350 SourceLocation TSSL = D.getLocStart();
12351 MSPropertyDecl *NewPD;
12352 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12353 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12354 II, T, TInfo, TSSL,
12355 Data.GetterId, Data.SetterId);
12356 ProcessDeclAttributes(TUScope, NewPD, D);
12357 NewPD->setAccess(AS);
12358
12359 if (NewPD->isInvalidDecl())
12360 Record->setInvalidDecl();
12361
12362 if (D.getDeclSpec().isModulePrivateSpecified())
12363 NewPD->setModulePrivate();
12364
12365 if (NewPD->isInvalidDecl() && PrevDecl) {
12366 // Don't introduce NewFD into scope; there's already something
12367 // with the same name in the same scope.
12368 } else if (II) {
12369 PushOnScopeChains(NewPD, S);
12370 } else
12371 Record->addDecl(NewPD);
12372
12373 return NewPD;
12374}