blob: 1c943786f0b00b6c0d8e6f9c78d0955cc861cb81 [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);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param)
343 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Anders Carlsson5e300d12009-06-12 16:51:40 +0000358 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000359}
360
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367 // C++ [dcl.fct.default]p3
368 // A default argument expression shall be specified only in the
369 // parameter-declaration-clause of a function declaration or in a
370 // template-parameter (14.1). It shall not be specified for a
371 // parameter pack. If it is specified in a
372 // parameter-declaration-clause, it shall not occur within a
373 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000378 if (MightBeFunction) {
379 // This is a function declaration. It can have default arguments, but
380 // keep looking in case its return type is a function type with default
381 // arguments.
382 MightBeFunction = false;
383 continue;
384 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000393 delete Toks;
394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000395 } else if (Param->getDefaultArg()) {
396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397 << Param->getDefaultArg()->getSourceRange();
398 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000399 }
400 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000403 }
404 }
405}
406
Craig Topper1a6eac82012-09-21 04:33:26 +0000407/// MergeCXXFunctionDecl - Merge two declarations of the same C++
408/// function, once we already know that they have the same
409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
410/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
412 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000413 bool Invalid = false;
414
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000416 // For non-template functions, default arguments can be added in
417 // later declarations of a function in the same
418 // scope. Declarations in different scopes have completely
419 // distinct sets of default arguments. That is, declarations in
420 // inner scopes do not acquire default arguments from
421 // declarations in outer scopes, and vice versa. In a given
422 // function declaration, all parameters subsequent to a
423 // parameter with a default argument shall have default
424 // arguments supplied in this or previous declarations. A
425 // default argument shall not be redefined by a later
426 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000427 //
428 // C++ [dcl.fct.default]p6:
429 // Except for member functions of class templates, the default arguments
430 // in a member function definition that appears outside of the class
431 // definition are added to the set of default arguments provided by the
432 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000433 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
434 ParmVarDecl *OldParam = Old->getParamDecl(p);
435 ParmVarDecl *NewParam = New->getParamDecl(p);
436
James Molloy9cda03f2012-03-13 08:55:35 +0000437 bool OldParamHasDfl = OldParam->hasDefaultArg();
438 bool NewParamHasDfl = NewParam->hasDefaultArg();
439
440 NamedDecl *ND = Old;
441 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
442 // Ignore default parameters of old decl if they are not in
443 // the same scope.
444 OldParamHasDfl = false;
445
446 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000447
Francois Pichet8d051e02011-04-10 03:03:52 +0000448 unsigned DiagDefaultParamID =
449 diag::err_param_default_argument_redefinition;
450
451 // MSVC accepts that default parameters be redefined for member functions
452 // of template class. The new default parameter's value is ignored.
453 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000454 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000455 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
456 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000457 // Merge the old default argument into the new parameter.
458 NewParam->setHasInheritedDefaultArg();
459 if (OldParam->hasUninstantiatedDefaultArg())
460 NewParam->setUninstantiatedDefaultArg(
461 OldParam->getUninstantiatedDefaultArg());
462 else
463 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000464 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000465 Invalid = false;
466 }
467 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000468
Francois Pichet8cf90492011-04-10 04:58:30 +0000469 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
470 // hint here. Alternatively, we could walk the type-source information
471 // for NewParam to find the last source location in the type... but it
472 // isn't worth the effort right now. This is the kind of test case that
473 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000474 // int f(int);
475 // void g(int (*fp)(int) = f);
476 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000477 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000478 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000479
480 // Look for the function declaration where the default argument was
481 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000482 for (FunctionDecl *Older = Old->getPreviousDecl();
483 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000484 if (!Older->getParamDecl(p)->hasDefaultArg())
485 break;
486
487 OldParam = Older->getParamDecl(p);
488 }
489
490 Diag(OldParam->getLocation(), diag::note_previous_definition)
491 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000492 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000493 // Merge the old default argument into the new parameter.
494 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000495 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000496 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000497 if (OldParam->hasUninstantiatedDefaultArg())
498 NewParam->setUninstantiatedDefaultArg(
499 OldParam->getUninstantiatedDefaultArg());
500 else
John McCall3d6c1782010-05-04 01:53:42 +0000501 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000502 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000503 if (New->getDescribedFunctionTemplate()) {
504 // Paragraph 4, quoted above, only applies to non-template functions.
505 Diag(NewParam->getLocation(),
506 diag::err_param_default_argument_template_redecl)
507 << NewParam->getDefaultArgRange();
508 Diag(Old->getLocation(), diag::note_template_prev_declaration)
509 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000510 } else if (New->getTemplateSpecializationKind()
511 != TSK_ImplicitInstantiation &&
512 New->getTemplateSpecializationKind() != TSK_Undeclared) {
513 // C++ [temp.expr.spec]p21:
514 // Default function arguments shall not be specified in a declaration
515 // or a definition for one of the following explicit specializations:
516 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000517 // - the explicit specialization of a member function template;
518 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000519 // template where the class template specialization to which the
520 // member function specialization belongs is implicitly
521 // instantiated.
522 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
523 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
524 << New->getDeclName()
525 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000526 } else if (New->getDeclContext()->isDependentContext()) {
527 // C++ [dcl.fct.default]p6 (DR217):
528 // Default arguments for a member function of a class template shall
529 // be specified on the initial declaration of the member function
530 // within the class template.
531 //
532 // Reading the tea leaves a bit in DR217 and its reference to DR205
533 // leads me to the conclusion that one cannot add default function
534 // arguments for an out-of-line definition of a member function of a
535 // dependent type.
536 int WhichKind = 2;
537 if (CXXRecordDecl *Record
538 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
539 if (Record->getDescribedClassTemplate())
540 WhichKind = 0;
541 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
542 WhichKind = 1;
543 else
544 WhichKind = 2;
545 }
546
547 Diag(NewParam->getLocation(),
548 diag::err_param_default_argument_member_template_redecl)
549 << WhichKind
550 << NewParam->getDefaultArgRange();
551 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000552 }
553 }
554
Richard Smithb8abff62012-11-28 03:45:24 +0000555 // DR1344: If a default argument is added outside a class definition and that
556 // default argument makes the function a special member function, the program
557 // is ill-formed. This can only happen for constructors.
558 if (isa<CXXConstructorDecl>(New) &&
559 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
560 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
561 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
562 if (NewSM != OldSM) {
563 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
564 assert(NewParam->hasDefaultArg());
565 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
566 << NewParam->getDefaultArgRange() << NewSM;
567 Diag(Old->getLocation(), diag::note_previous_declaration);
568 }
569 }
570
Richard Smithff234882012-02-20 23:28:05 +0000571 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000572 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000573 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000574 if (New->isConstexpr() != Old->isConstexpr()) {
575 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
576 << New << New->isConstexpr();
577 Diag(Old->getLocation(), diag::note_previous_declaration);
578 Invalid = true;
579 }
580
Douglas Gregore13ad832010-02-12 07:32:17 +0000581 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000582 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000583
Douglas Gregorcda9c672009-02-16 17:45:42 +0000584 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585}
586
Sebastian Redl60618fa2011-03-12 11:50:43 +0000587/// \brief Merge the exception specifications of two variable declarations.
588///
589/// This is called when there's a redeclaration of a VarDecl. The function
590/// checks if the redeclaration might have an exception specification and
591/// validates compatibility and merges the specs if necessary.
592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
593 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000594 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000595 return;
596
597 assert(Context.hasSameType(New->getType(), Old->getType()) &&
598 "Should only be called if types are otherwise the same.");
599
600 QualType NewType = New->getType();
601 QualType OldType = Old->getType();
602
603 // We're only interested in pointers and references to functions, as well
604 // as pointers to member functions.
605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
606 NewType = R->getPointeeType();
607 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
608 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
609 NewType = P->getPointeeType();
610 OldType = OldType->getAs<PointerType>()->getPointeeType();
611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
612 NewType = M->getPointeeType();
613 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
614 }
615
616 if (!NewType->isFunctionProtoType())
617 return;
618
619 // There's lots of special cases for functions. For function pointers, system
620 // libraries are hopefully not as broken so that we don't need these
621 // workarounds.
622 if (CheckEquivalentExceptionSpec(
623 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
624 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
625 New->setInvalidDecl();
626 }
627}
628
Chris Lattner3d1cee32008-04-08 05:04:30 +0000629/// CheckCXXDefaultArguments - Verify that the default arguments for a
630/// function declaration are well-formed according to C++
631/// [dcl.fct.default].
632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
633 unsigned NumParams = FD->getNumParams();
634 unsigned p;
635
636 // Find first parameter with a default argument
637 for (p = 0; p < NumParams; ++p) {
638 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000639 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 break;
641 }
642
643 // C++ [dcl.fct.default]p4:
644 // In a given function declaration, all parameters
645 // subsequent to a parameter with a default argument shall
646 // have default arguments supplied in this or previous
647 // declarations. A default argument shall not be redefined
648 // by a later declaration (not even to the same value).
649 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000650 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000652 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000653 if (Param->isInvalidDecl())
654 /* We already complained about this parameter. */;
655 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000656 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000657 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000658 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000659 else
Mike Stump1eb44332009-09-09 15:08:12 +0000660 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000661 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663 LastMissingDefaultArg = p;
664 }
665 }
666
667 if (LastMissingDefaultArg > 0) {
668 // Some default arguments were missing. Clear out all of the
669 // default arguments up to (and including) the last missing
670 // default argument, so that we leave the function parameters
671 // in a semantically valid state.
672 for (p = 0; p <= LastMissingDefaultArg; ++p) {
673 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000674 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000675 Param->setDefaultArg(0);
676 }
677 }
678 }
679}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000680
Richard Smith9f569cc2011-10-01 02:31:28 +0000681// CheckConstexprParameterTypes - Check whether a function's parameter types
682// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000683// diagnostic and return false.
684static bool CheckConstexprParameterTypes(Sema &SemaRef,
685 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000686 unsigned ArgIndex = 0;
687 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
688 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
689 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
690 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
691 SourceLocation ParamLoc = PD->getLocation();
692 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000693 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000694 diag::err_constexpr_non_literal_param,
695 ArgIndex+1, PD->getSourceRange(),
696 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000697 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000698 }
Joao Matos17d35c32012-08-31 22:18:20 +0000699 return true;
700}
701
702/// \brief Get diagnostic %select index for tag kind for
703/// record diagnostic message.
704/// WARNING: Indexes apply to particular diagnostics only!
705///
706/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000707static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000708 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000709 case TTK_Struct: return 0;
710 case TTK_Interface: return 1;
711 case TTK_Class: return 2;
712 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000713 }
Joao Matos17d35c32012-08-31 22:18:20 +0000714}
715
716// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
717// the requirements of a constexpr function definition or a constexpr
718// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000719// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000720//
Richard Smith86c3ae42012-02-13 03:54:03 +0000721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
722bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000723 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
724 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000725 // C++11 [dcl.constexpr]p4:
726 // The definition of a constexpr constructor shall satisfy the following
727 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000729 const CXXRecordDecl *RD = MD->getParent();
730 if (RD->getNumVBases()) {
731 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
732 << isa<CXXConstructorDecl>(NewFD)
733 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
734 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
735 E = RD->vbases_end(); I != E; ++I)
736 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000737 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000738 return false;
739 }
Richard Smith35340502012-01-13 04:54:00 +0000740 }
741
742 if (!isa<CXXConstructorDecl>(NewFD)) {
743 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000744 // The definition of a constexpr function shall satisfy the following
745 // constraints:
746 // - it shall not be virtual;
747 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
748 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000750
Richard Smith86c3ae42012-02-13 03:54:03 +0000751 // If it's not obvious why this function is virtual, find an overridden
752 // function which uses the 'virtual' keyword.
753 const CXXMethodDecl *WrittenVirtual = Method;
754 while (!WrittenVirtual->isVirtualAsWritten())
755 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
756 if (WrittenVirtual != Method)
757 Diag(WrittenVirtual->getLocation(),
758 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000759 return false;
760 }
761
762 // - its return type shall be a literal type;
763 QualType RT = NewFD->getResultType();
764 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000765 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000766 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000768 }
769
Richard Smith35340502012-01-13 04:54:00 +0000770 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000771 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000772 return false;
773
Richard Smith9f569cc2011-10-01 02:31:28 +0000774 return true;
775}
776
777/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000778/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000779///
Richard Smitha10b9782013-04-22 15:31:51 +0000780/// \return true if the body is OK (maybe only as an extension), false if we
781/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000782static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000783 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
784 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000785 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
786 // contain only
787 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
788 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
789 switch ((*DclIt)->getKind()) {
790 case Decl::StaticAssert:
791 case Decl::Using:
792 case Decl::UsingShadow:
793 case Decl::UsingDirective:
794 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000795 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 // - static_assert-declarations
797 // - using-declarations,
798 // - using-directives,
799 continue;
800
801 case Decl::Typedef:
802 case Decl::TypeAlias: {
803 // - typedef declarations and alias-declarations that do not define
804 // classes or enumerations,
805 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
806 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
807 // Don't allow variably-modified types in constexpr functions.
808 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
809 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
810 << TL.getSourceRange() << TL.getType()
811 << isa<CXXConstructorDecl>(Dcl);
812 return false;
813 }
814 continue;
815 }
816
817 case Decl::Enum:
818 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000819 // C++1y allows types to be defined, not just declared.
820 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
821 SemaRef.Diag(DS->getLocStart(),
822 SemaRef.getLangOpts().CPlusPlus1y
823 ? diag::warn_cxx11_compat_constexpr_type_definition
824 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000825 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000826 continue;
827
Richard Smitha10b9782013-04-22 15:31:51 +0000828 case Decl::EnumConstant:
829 case Decl::IndirectField:
830 case Decl::ParmVar:
831 // These can only appear with other declarations which are banned in
832 // C++11 and permitted in C++1y, so ignore them.
833 continue;
834
835 case Decl::Var: {
836 // C++1y [dcl.constexpr]p3 allows anything except:
837 // a definition of a variable of non-literal type or of static or
838 // thread storage duration or for which no initialization is performed.
839 VarDecl *VD = cast<VarDecl>(*DclIt);
840 if (VD->isThisDeclarationADefinition()) {
841 if (VD->isStaticLocal()) {
842 SemaRef.Diag(VD->getLocation(),
843 diag::err_constexpr_local_var_static)
844 << isa<CXXConstructorDecl>(Dcl)
845 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
846 return false;
847 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000848 if (!VD->getType()->isDependentType() &&
849 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000850 VD->getLocation(), VD->getType(),
851 diag::err_constexpr_local_var_non_literal_type,
852 isa<CXXConstructorDecl>(Dcl)))
853 return false;
854 if (!VD->hasInit()) {
855 SemaRef.Diag(VD->getLocation(),
856 diag::err_constexpr_local_var_no_init)
857 << isa<CXXConstructorDecl>(Dcl);
858 return false;
859 }
860 }
861 SemaRef.Diag(VD->getLocation(),
862 SemaRef.getLangOpts().CPlusPlus1y
863 ? diag::warn_cxx11_compat_constexpr_local_var
864 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000865 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000866 continue;
867 }
868
869 case Decl::NamespaceAlias:
870 case Decl::Function:
871 // These are disallowed in C++11 and permitted in C++1y. Allow them
872 // everywhere as an extension.
873 if (!Cxx1yLoc.isValid())
874 Cxx1yLoc = DS->getLocStart();
875 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000876
877 default:
878 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882 }
883
884 return true;
885}
886
887/// Check that the given field is initialized within a constexpr constructor.
888///
889/// \param Dcl The constexpr constructor being checked.
890/// \param Field The field being checked. This may be a member of an anonymous
891/// struct or union nested within the class being checked.
892/// \param Inits All declarations, including anonymous struct/union members and
893/// indirect members, for which any initialization was provided.
894/// \param Diagnosed Set to true if an error is produced.
895static void CheckConstexprCtorInitializer(Sema &SemaRef,
896 const FunctionDecl *Dcl,
897 FieldDecl *Field,
898 llvm::SmallSet<Decl*, 16> &Inits,
899 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000900 if (Field->isUnnamedBitfield())
901 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000902
903 if (Field->isAnonymousStructOrUnion() &&
904 Field->getType()->getAsCXXRecordDecl()->isEmpty())
905 return;
906
Richard Smith9f569cc2011-10-01 02:31:28 +0000907 if (!Inits.count(Field)) {
908 if (!Diagnosed) {
909 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
910 Diagnosed = true;
911 }
912 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
913 } else if (Field->isAnonymousStructOrUnion()) {
914 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
915 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
916 I != E; ++I)
917 // If an anonymous union contains an anonymous struct of which any member
918 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000919 if (!RD->isUnion() || Inits.count(*I))
920 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000921 }
922}
923
Richard Smitha10b9782013-04-22 15:31:51 +0000924/// Check the provided statement is allowed in a constexpr function
925/// definition.
926static bool
927CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
928 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
929 SourceLocation &Cxx1yLoc) {
930 // - its function-body shall be [...] a compound-statement that contains only
931 switch (S->getStmtClass()) {
932 case Stmt::NullStmtClass:
933 // - null statements,
934 return true;
935
936 case Stmt::DeclStmtClass:
937 // - static_assert-declarations
938 // - using-declarations,
939 // - using-directives,
940 // - typedef declarations and alias-declarations that do not define
941 // classes or enumerations,
942 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
943 return false;
944 return true;
945
946 case Stmt::ReturnStmtClass:
947 // - and exactly one return statement;
948 if (isa<CXXConstructorDecl>(Dcl)) {
949 // C++1y allows return statements in constexpr constructors.
950 if (!Cxx1yLoc.isValid())
951 Cxx1yLoc = S->getLocStart();
952 return true;
953 }
954
955 ReturnStmts.push_back(S->getLocStart());
956 return true;
957
958 case Stmt::CompoundStmtClass: {
959 // C++1y allows compound-statements.
960 if (!Cxx1yLoc.isValid())
961 Cxx1yLoc = S->getLocStart();
962
963 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
964 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
965 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
966 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
967 Cxx1yLoc))
968 return false;
969 }
970 return true;
971 }
972
973 case Stmt::AttributedStmtClass:
974 if (!Cxx1yLoc.isValid())
975 Cxx1yLoc = S->getLocStart();
976 return true;
977
978 case Stmt::IfStmtClass: {
979 // C++1y allows if-statements.
980 if (!Cxx1yLoc.isValid())
981 Cxx1yLoc = S->getLocStart();
982
983 IfStmt *If = cast<IfStmt>(S);
984 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
985 Cxx1yLoc))
986 return false;
987 if (If->getElse() &&
988 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
989 Cxx1yLoc))
990 return false;
991 return true;
992 }
993
994 case Stmt::WhileStmtClass:
995 case Stmt::DoStmtClass:
996 case Stmt::ForStmtClass:
997 case Stmt::CXXForRangeStmtClass:
998 case Stmt::ContinueStmtClass:
999 // C++1y allows all of these. We don't allow them as extensions in C++11,
1000 // because they don't make sense without variable mutation.
1001 if (!SemaRef.getLangOpts().CPlusPlus1y)
1002 break;
1003 if (!Cxx1yLoc.isValid())
1004 Cxx1yLoc = S->getLocStart();
1005 for (Stmt::child_range Children = S->children(); Children; ++Children)
1006 if (*Children &&
1007 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1008 Cxx1yLoc))
1009 return false;
1010 return true;
1011
1012 case Stmt::SwitchStmtClass:
1013 case Stmt::CaseStmtClass:
1014 case Stmt::DefaultStmtClass:
1015 case Stmt::BreakStmtClass:
1016 // C++1y allows switch-statements, and since they don't need variable
1017 // mutation, we can reasonably allow them in C++11 as an extension.
1018 if (!Cxx1yLoc.isValid())
1019 Cxx1yLoc = S->getLocStart();
1020 for (Stmt::child_range Children = S->children(); Children; ++Children)
1021 if (*Children &&
1022 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1023 Cxx1yLoc))
1024 return false;
1025 return true;
1026
1027 default:
1028 if (!isa<Expr>(S))
1029 break;
1030
1031 // C++1y allows expression-statements.
1032 if (!Cxx1yLoc.isValid())
1033 Cxx1yLoc = S->getLocStart();
1034 return true;
1035 }
1036
1037 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1038 << isa<CXXConstructorDecl>(Dcl);
1039 return false;
1040}
1041
Richard Smith9f569cc2011-10-01 02:31:28 +00001042/// Check the body for the given constexpr function declaration only contains
1043/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1044///
1045/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001046bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001047 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001048 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001049 // The definition of a constexpr function shall satisfy the following
1050 // constraints: [...]
1051 // - its function-body shall be = delete, = default, or a
1052 // compound-statement
1053 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001054 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001055 // In the definition of a constexpr constructor, [...]
1056 // - its function-body shall not be a function-try-block;
1057 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1058 << isa<CXXConstructorDecl>(Dcl);
1059 return false;
1060 }
1061
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001062 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001063
1064 // - its function-body shall be [...] a compound-statement that contains only
1065 // [... list of cases ...]
1066 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1067 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001068 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1069 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001070 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1071 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001072 }
1073
Richard Smitha10b9782013-04-22 15:31:51 +00001074 if (Cxx1yLoc.isValid())
1075 Diag(Cxx1yLoc,
1076 getLangOpts().CPlusPlus1y
1077 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1078 : diag::ext_constexpr_body_invalid_stmt)
1079 << isa<CXXConstructorDecl>(Dcl);
1080
Richard Smith9f569cc2011-10-01 02:31:28 +00001081 if (const CXXConstructorDecl *Constructor
1082 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1083 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001084 // DR1359:
1085 // - every non-variant non-static data member and base class sub-object
1086 // shall be initialized;
1087 // - if the class is a non-empty union, or for each non-empty anonymous
1088 // union member of a non-union class, exactly one non-static data member
1089 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001090 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001091 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001092 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1093 return false;
1094 }
Richard Smith6e433752011-10-10 16:38:04 +00001095 } else if (!Constructor->isDependentContext() &&
1096 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001097 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1098
1099 // Skip detailed checking if we have enough initializers, and we would
1100 // allow at most one initializer per member.
1101 bool AnyAnonStructUnionMembers = false;
1102 unsigned Fields = 0;
1103 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1104 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001105 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001106 AnyAnonStructUnionMembers = true;
1107 break;
1108 }
1109 }
1110 if (AnyAnonStructUnionMembers ||
1111 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1112 // Check initialization of non-static data members. Base classes are
1113 // always initialized so do not need to be checked. Dependent bases
1114 // might not have initializers in the member initializer list.
1115 llvm::SmallSet<Decl*, 16> Inits;
1116 for (CXXConstructorDecl::init_const_iterator
1117 I = Constructor->init_begin(), E = Constructor->init_end();
1118 I != E; ++I) {
1119 if (FieldDecl *FD = (*I)->getMember())
1120 Inits.insert(FD);
1121 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1122 Inits.insert(ID->chain_begin(), ID->chain_end());
1123 }
1124
1125 bool Diagnosed = false;
1126 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1127 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001128 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001129 if (Diagnosed)
1130 return false;
1131 }
1132 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001133 } else {
1134 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001135 // C++1y doesn't require constexpr functions to contain a 'return'
1136 // statement. We still do, unless the return type is void, because
1137 // otherwise if there's no return statement, the function cannot
1138 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001139 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001140 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001141 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1142 : diag::err_constexpr_body_no_return);
1143 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001144 }
1145 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001146 Diag(ReturnStmts.back(),
1147 getLangOpts().CPlusPlus1y
1148 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1149 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001150 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1151 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001152 }
1153 }
1154
Richard Smith5ba73e12012-02-04 00:33:54 +00001155 // C++11 [dcl.constexpr]p5:
1156 // if no function argument values exist such that the function invocation
1157 // substitution would produce a constant expression, the program is
1158 // ill-formed; no diagnostic required.
1159 // C++11 [dcl.constexpr]p3:
1160 // - every constructor call and implicit conversion used in initializing the
1161 // return value shall be one of those allowed in a constant expression.
1162 // C++11 [dcl.constexpr]p4:
1163 // - every constructor involved in initializing non-static data members and
1164 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001165 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001166 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001167 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001168 << isa<CXXConstructorDecl>(Dcl);
1169 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1170 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001171 // Don't return false here: we allow this for compatibility in
1172 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001173 }
1174
Richard Smith9f569cc2011-10-01 02:31:28 +00001175 return true;
1176}
1177
Douglas Gregorb48fe382008-10-31 09:07:45 +00001178/// isCurrentClassName - Determine whether the identifier II is the
1179/// name of the class type currently being defined. In the case of
1180/// nested classes, this will only return true if II is the name of
1181/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001182bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1183 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001184 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001185
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001186 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001187 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001188 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001189 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1190 } else
1191 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1192
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001193 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001194 return &II == CurDecl->getIdentifier();
1195 else
1196 return false;
1197}
1198
Douglas Gregor229d47a2012-11-10 07:24:09 +00001199/// \brief Determine whether the given class is a base class of the given
1200/// class, including looking at dependent bases.
1201static bool findCircularInheritance(const CXXRecordDecl *Class,
1202 const CXXRecordDecl *Current) {
1203 SmallVector<const CXXRecordDecl*, 8> Queue;
1204
1205 Class = Class->getCanonicalDecl();
1206 while (true) {
1207 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1208 E = Current->bases_end();
1209 I != E; ++I) {
1210 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1211 if (!Base)
1212 continue;
1213
1214 Base = Base->getDefinition();
1215 if (!Base)
1216 continue;
1217
1218 if (Base->getCanonicalDecl() == Class)
1219 return true;
1220
1221 Queue.push_back(Base);
1222 }
1223
1224 if (Queue.empty())
1225 return false;
1226
1227 Current = Queue.back();
1228 Queue.pop_back();
1229 }
1230
1231 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001232}
1233
Mike Stump1eb44332009-09-09 15:08:12 +00001234/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001235///
1236/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1237/// and returns NULL otherwise.
1238CXXBaseSpecifier *
1239Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1240 SourceRange SpecifierRange,
1241 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001242 TypeSourceInfo *TInfo,
1243 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001244 QualType BaseType = TInfo->getType();
1245
Douglas Gregor2943aed2009-03-03 04:44:36 +00001246 // C++ [class.union]p1:
1247 // A union shall not have base classes.
1248 if (Class->isUnion()) {
1249 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1250 << SpecifierRange;
1251 return 0;
1252 }
1253
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001254 if (EllipsisLoc.isValid() &&
1255 !TInfo->getType()->containsUnexpandedParameterPack()) {
1256 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1257 << TInfo->getTypeLoc().getSourceRange();
1258 EllipsisLoc = SourceLocation();
1259 }
Douglas Gregord777e282012-11-10 01:18:17 +00001260
1261 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1262
1263 if (BaseType->isDependentType()) {
1264 // Make sure that we don't have circular inheritance among our dependent
1265 // bases. For non-dependent bases, the check for completeness below handles
1266 // this.
1267 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1268 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1269 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001270 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001271 Diag(BaseLoc, diag::err_circular_inheritance)
1272 << BaseType << Context.getTypeDeclType(Class);
1273
1274 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1275 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1276 << BaseType;
1277
1278 return 0;
1279 }
1280 }
1281
Mike Stump1eb44332009-09-09 15:08:12 +00001282 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001283 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001284 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001285 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001286
1287 // Base specifiers must be record types.
1288 if (!BaseType->isRecordType()) {
1289 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1290 return 0;
1291 }
1292
1293 // C++ [class.union]p1:
1294 // A union shall not be used as a base class.
1295 if (BaseType->isUnionType()) {
1296 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1297 return 0;
1298 }
1299
1300 // C++ [class.derived]p2:
1301 // The class-name in a base-specifier shall not be an incompletely
1302 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001303 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001304 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001305 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001306 return 0;
John McCall572fc622010-08-17 07:23:57 +00001307 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001308
Eli Friedman1d954f62009-08-15 21:55:26 +00001309 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001310 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001312 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001313 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001314 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1315 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001316
Anders Carlsson1d209272011-03-25 14:55:14 +00001317 // C++ [class]p3:
1318 // If a class is marked final and it appears as a base-type-specifier in
1319 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001320 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001321 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1322 << CXXBaseDecl->getDeclName();
1323 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1324 << CXXBaseDecl->getDeclName();
1325 return 0;
1326 }
1327
John McCall572fc622010-08-17 07:23:57 +00001328 if (BaseDecl->isInvalidDecl())
1329 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001330
1331 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001332 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001333 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001334 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001335}
1336
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001337/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1338/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001339/// example:
1340/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001341/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001342BaseResult
John McCalld226f652010-08-21 09:40:31 +00001343Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001344 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001345 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001346 ParsedType basetype, SourceLocation BaseLoc,
1347 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001348 if (!classdecl)
1349 return true;
1350
Douglas Gregor40808ce2009-03-09 23:48:35 +00001351 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001352 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001353 if (!Class)
1354 return true;
1355
Richard Smith05321402013-02-19 23:47:15 +00001356 // We do not support any C++11 attributes on base-specifiers yet.
1357 // Diagnose any attributes we see.
1358 if (!Attributes.empty()) {
1359 for (AttributeList *Attr = Attributes.getList(); Attr;
1360 Attr = Attr->getNext()) {
1361 if (Attr->isInvalid() ||
1362 Attr->getKind() == AttributeList::IgnoredAttribute)
1363 continue;
1364 Diag(Attr->getLoc(),
1365 Attr->getKind() == AttributeList::UnknownAttribute
1366 ? diag::warn_unknown_attribute_ignored
1367 : diag::err_base_specifier_attribute)
1368 << Attr->getName();
1369 }
1370 }
1371
Nick Lewycky56062202010-07-26 16:56:01 +00001372 TypeSourceInfo *TInfo = 0;
1373 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001374
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001375 if (EllipsisLoc.isInvalid() &&
1376 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001377 UPPC_BaseType))
1378 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001379
Douglas Gregor2943aed2009-03-03 04:44:36 +00001380 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001381 Virtual, Access, TInfo,
1382 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001383 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001384 else
1385 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Douglas Gregor2943aed2009-03-03 04:44:36 +00001387 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001388}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001389
Douglas Gregor2943aed2009-03-03 04:44:36 +00001390/// \brief Performs the actual work of attaching the given base class
1391/// specifiers to a C++ class.
1392bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1393 unsigned NumBases) {
1394 if (NumBases == 0)
1395 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001396
1397 // Used to keep track of which base types we have already seen, so
1398 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001399 // that the key is always the unqualified canonical type of the base
1400 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001401 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1402
1403 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001404 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001405 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001406 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001407 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001408 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001409 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001410
1411 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1412 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001413 // C++ [class.mi]p3:
1414 // A class shall not be specified as a direct base class of a
1415 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001416 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001417 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001418 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001419 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001420
1421 // Delete the duplicate base class specifier; we're going to
1422 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001423 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001424
1425 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001426 } else {
1427 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001428 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001429 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001430 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1431 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1432 if (Class->isInterface() &&
1433 (!RD->isInterface() ||
1434 KnownBase->getAccessSpecifier() != AS_public)) {
1435 // The Microsoft extension __interface does not permit bases that
1436 // are not themselves public interfaces.
1437 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1438 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1439 << RD->getSourceRange();
1440 Invalid = true;
1441 }
1442 if (RD->hasAttr<WeakAttr>())
1443 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1444 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001445 }
1446 }
1447
1448 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001449 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001450
1451 // Delete the remaining (good) base class specifiers, since their
1452 // data has been copied into the CXXRecordDecl.
1453 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001454 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001455
1456 return Invalid;
1457}
1458
1459/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1460/// class, after checking whether there are any duplicate base
1461/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001462void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001463 unsigned NumBases) {
1464 if (!ClassDecl || !Bases || !NumBases)
1465 return;
1466
1467 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001468 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001469 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001470}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001471
Douglas Gregora8f32e02009-10-06 17:59:45 +00001472/// \brief Determine whether the type \p Derived is a C++ class that is
1473/// derived from the type \p Base.
1474bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001475 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001476 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001477
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001478 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001479 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001480 return false;
1481
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001482 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001483 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001484 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001485
1486 // If either the base or the derived type is invalid, don't try to
1487 // check whether one is derived from the other.
1488 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1489 return false;
1490
John McCall86ff3082010-02-04 22:26:26 +00001491 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1492 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001493}
1494
1495/// \brief Determine whether the type \p Derived is a C++ class that is
1496/// derived from the type \p Base.
1497bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001498 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001499 return false;
1500
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001501 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001502 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001503 return false;
1504
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001505 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001506 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001507 return false;
1508
Douglas Gregora8f32e02009-10-06 17:59:45 +00001509 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1510}
1511
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001512void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001513 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001514 assert(BasePathArray.empty() && "Base path array must be empty!");
1515 assert(Paths.isRecordingPaths() && "Must record paths!");
1516
1517 const CXXBasePath &Path = Paths.front();
1518
1519 // We first go backward and check if we have a virtual base.
1520 // FIXME: It would be better if CXXBasePath had the base specifier for
1521 // the nearest virtual base.
1522 unsigned Start = 0;
1523 for (unsigned I = Path.size(); I != 0; --I) {
1524 if (Path[I - 1].Base->isVirtual()) {
1525 Start = I - 1;
1526 break;
1527 }
1528 }
1529
1530 // Now add all bases.
1531 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001532 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001533}
1534
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001535/// \brief Determine whether the given base path includes a virtual
1536/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001537bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1538 for (CXXCastPath::const_iterator B = BasePath.begin(),
1539 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001540 B != BEnd; ++B)
1541 if ((*B)->isVirtual())
1542 return true;
1543
1544 return false;
1545}
1546
Douglas Gregora8f32e02009-10-06 17:59:45 +00001547/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1548/// conversion (where Derived and Base are class types) is
1549/// well-formed, meaning that the conversion is unambiguous (and
1550/// that all of the base classes are accessible). Returns true
1551/// and emits a diagnostic if the code is ill-formed, returns false
1552/// otherwise. Loc is the location where this routine should point to
1553/// if there is an error, and Range is the source range to highlight
1554/// if there is an error.
1555bool
1556Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001557 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001558 unsigned AmbigiousBaseConvID,
1559 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001560 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001561 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001562 // First, determine whether the path from Derived to Base is
1563 // ambiguous. This is slightly more expensive than checking whether
1564 // the Derived to Base conversion exists, because here we need to
1565 // explore multiple paths to determine if there is an ambiguity.
1566 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1567 /*DetectVirtual=*/false);
1568 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1569 assert(DerivationOkay &&
1570 "Can only be used with a derived-to-base conversion");
1571 (void)DerivationOkay;
1572
1573 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001574 if (InaccessibleBaseID) {
1575 // Check that the base class can be accessed.
1576 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1577 InaccessibleBaseID)) {
1578 case AR_inaccessible:
1579 return true;
1580 case AR_accessible:
1581 case AR_dependent:
1582 case AR_delayed:
1583 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001584 }
John McCall6b2accb2010-02-10 09:31:12 +00001585 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001586
1587 // Build a base path if necessary.
1588 if (BasePath)
1589 BuildBasePathArray(Paths, *BasePath);
1590 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001591 }
1592
1593 // We know that the derived-to-base conversion is ambiguous, and
1594 // we're going to produce a diagnostic. Perform the derived-to-base
1595 // search just one more time to compute all of the possible paths so
1596 // that we can print them out. This is more expensive than any of
1597 // the previous derived-to-base checks we've done, but at this point
1598 // performance isn't as much of an issue.
1599 Paths.clear();
1600 Paths.setRecordingPaths(true);
1601 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1602 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1603 (void)StillOkay;
1604
1605 // Build up a textual representation of the ambiguous paths, e.g.,
1606 // D -> B -> A, that will be used to illustrate the ambiguous
1607 // conversions in the diagnostic. We only print one of the paths
1608 // to each base class subobject.
1609 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1610
1611 Diag(Loc, AmbigiousBaseConvID)
1612 << Derived << Base << PathDisplayStr << Range << Name;
1613 return true;
1614}
1615
1616bool
1617Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001618 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001619 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001620 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001621 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001622 IgnoreAccess ? 0
1623 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001624 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001625 Loc, Range, DeclarationName(),
1626 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001627}
1628
1629
1630/// @brief Builds a string representing ambiguous paths from a
1631/// specific derived class to different subobjects of the same base
1632/// class.
1633///
1634/// This function builds a string that can be used in error messages
1635/// to show the different paths that one can take through the
1636/// inheritance hierarchy to go from the derived class to different
1637/// subobjects of a base class. The result looks something like this:
1638/// @code
1639/// struct D -> struct B -> struct A
1640/// struct D -> struct C -> struct A
1641/// @endcode
1642std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1643 std::string PathDisplayStr;
1644 std::set<unsigned> DisplayedPaths;
1645 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1646 Path != Paths.end(); ++Path) {
1647 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1648 // We haven't displayed a path to this particular base
1649 // class subobject yet.
1650 PathDisplayStr += "\n ";
1651 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1652 for (CXXBasePath::const_iterator Element = Path->begin();
1653 Element != Path->end(); ++Element)
1654 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1655 }
1656 }
1657
1658 return PathDisplayStr;
1659}
1660
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001661//===----------------------------------------------------------------------===//
1662// C++ class member Handling
1663//===----------------------------------------------------------------------===//
1664
Abramo Bagnara6206d532010-06-05 05:09:32 +00001665/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001666bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1667 SourceLocation ASLoc,
1668 SourceLocation ColonLoc,
1669 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001670 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001671 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001672 ASLoc, ColonLoc);
1673 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001674 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001675}
1676
Richard Smitha4b39652012-08-06 03:25:17 +00001677/// CheckOverrideControl - Check C++11 override control semantics.
1678void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001679 if (D->isInvalidDecl())
1680 return;
1681
Chris Lattner5f9e2722011-07-23 10:55:15 +00001682 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001683
Richard Smitha4b39652012-08-06 03:25:17 +00001684 // Do we know which functions this declaration might be overriding?
1685 bool OverridesAreKnown = !MD ||
1686 (!MD->getParent()->hasAnyDependentBases() &&
1687 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001688
Richard Smitha4b39652012-08-06 03:25:17 +00001689 if (!MD || !MD->isVirtual()) {
1690 if (OverridesAreKnown) {
1691 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1692 Diag(OA->getLocation(),
1693 diag::override_keyword_only_allowed_on_virtual_member_functions)
1694 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1695 D->dropAttr<OverrideAttr>();
1696 }
1697 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1698 Diag(FA->getLocation(),
1699 diag::override_keyword_only_allowed_on_virtual_member_functions)
1700 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1701 D->dropAttr<FinalAttr>();
1702 }
1703 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001704 return;
1705 }
Richard Smitha4b39652012-08-06 03:25:17 +00001706
1707 if (!OverridesAreKnown)
1708 return;
1709
1710 // C++11 [class.virtual]p5:
1711 // If a virtual function is marked with the virt-specifier override and
1712 // does not override a member function of a base class, the program is
1713 // ill-formed.
1714 bool HasOverriddenMethods =
1715 MD->begin_overridden_methods() != MD->end_overridden_methods();
1716 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1717 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1718 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001719}
1720
Richard Smitha4b39652012-08-06 03:25:17 +00001721/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001722/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001723/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001724bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1725 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001726 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001727 return false;
1728
1729 Diag(New->getLocation(), diag::err_final_function_overridden)
1730 << New->getDeclName();
1731 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1732 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001733}
1734
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001735static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001736 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1737 // FIXME: Destruction of ObjC lifetime types has side-effects.
1738 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1739 return !RD->isCompleteDefinition() ||
1740 !RD->hasTrivialDefaultConstructor() ||
1741 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001742 return false;
1743}
1744
John McCall76da55d2013-04-16 07:28:30 +00001745static AttributeList *getMSPropertyAttr(AttributeList *list) {
1746 for (AttributeList* it = list; it != 0; it = it->getNext())
1747 if (it->isDeclspecPropertyAttribute())
1748 return it;
1749 return 0;
1750}
1751
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001752/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1753/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001754/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001755/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1756/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001757NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001758Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001759 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001760 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001761 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001762 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001763 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1764 DeclarationName Name = NameInfo.getName();
1765 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001766
1767 // For anonymous bitfields, the location should point to the type.
1768 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001769 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001770
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001771 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001772
John McCall4bde1e12010-06-04 08:34:12 +00001773 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001774 assert(!DS.isFriendSpecified());
1775
Richard Smith1ab0d902011-06-25 02:28:38 +00001776 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001777
John McCalle402e722012-09-25 07:32:39 +00001778 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1779 // The Microsoft extension __interface only permits public member functions
1780 // and prohibits constructors, destructors, operators, non-public member
1781 // functions, static methods and data members.
1782 unsigned InvalidDecl;
1783 bool ShowDeclName = true;
1784 if (!isFunc)
1785 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1786 else if (AS != AS_public)
1787 InvalidDecl = 2;
1788 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1789 InvalidDecl = 3;
1790 else switch (Name.getNameKind()) {
1791 case DeclarationName::CXXConstructorName:
1792 InvalidDecl = 4;
1793 ShowDeclName = false;
1794 break;
1795
1796 case DeclarationName::CXXDestructorName:
1797 InvalidDecl = 5;
1798 ShowDeclName = false;
1799 break;
1800
1801 case DeclarationName::CXXOperatorName:
1802 case DeclarationName::CXXConversionFunctionName:
1803 InvalidDecl = 6;
1804 break;
1805
1806 default:
1807 InvalidDecl = 0;
1808 break;
1809 }
1810
1811 if (InvalidDecl) {
1812 if (ShowDeclName)
1813 Diag(Loc, diag::err_invalid_member_in_interface)
1814 << (InvalidDecl-1) << Name;
1815 else
1816 Diag(Loc, diag::err_invalid_member_in_interface)
1817 << (InvalidDecl-1) << "";
1818 return 0;
1819 }
1820 }
1821
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001822 // C++ 9.2p6: A member shall not be declared to have automatic storage
1823 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001824 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1825 // data members and cannot be applied to names declared const or static,
1826 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001827 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001828 case DeclSpec::SCS_unspecified:
1829 case DeclSpec::SCS_typedef:
1830 case DeclSpec::SCS_static:
1831 break;
1832 case DeclSpec::SCS_mutable:
1833 if (isFunc) {
1834 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Richard Smithec642442013-04-12 22:46:28 +00001836 // FIXME: It would be nicer if the keyword was ignored only for this
1837 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001838 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001839 }
1840 break;
1841 default:
1842 Diag(DS.getStorageClassSpecLoc(),
1843 diag::err_storageclass_invalid_for_member);
1844 D.getMutableDeclSpec().ClearStorageClassSpecs();
1845 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001846 }
1847
Sebastian Redl669d5d72008-11-14 23:42:31 +00001848 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1849 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001850 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001851
David Blaikie1d87fba2013-01-30 01:22:18 +00001852 if (DS.isConstexprSpecified() && isInstField) {
1853 SemaDiagnosticBuilder B =
1854 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1855 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1856 if (InitStyle == ICIS_NoInit) {
1857 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1858 D.getMutableDeclSpec().ClearConstexprSpec();
1859 const char *PrevSpec;
1860 unsigned DiagID;
1861 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1862 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001863 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001864 assert(!Failed && "Making a constexpr member const shouldn't fail");
1865 } else {
1866 B << 1;
1867 const char *PrevSpec;
1868 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001869 if (D.getMutableDeclSpec().SetStorageClassSpec(
1870 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001871 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001872 "This is the only DeclSpec that should fail to be applied");
1873 B << 1;
1874 } else {
1875 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1876 isInstField = false;
1877 }
1878 }
1879 }
1880
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001881 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001882 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001883 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001884
1885 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001886 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001887 Diag(Loc, diag::err_bad_variable_name)
1888 << Name;
1889 return 0;
1890 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001891
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001892 IdentifierInfo *II = Name.getAsIdentifierInfo();
1893
Douglas Gregorf2503652011-09-21 14:40:46 +00001894 // Member field could not be with "template" keyword.
1895 // So TemplateParameterLists should be empty in this case.
1896 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001897 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001898 if (TemplateParams->size()) {
1899 // There is no such thing as a member field template.
1900 Diag(D.getIdentifierLoc(), diag::err_template_member)
1901 << II
1902 << SourceRange(TemplateParams->getTemplateLoc(),
1903 TemplateParams->getRAngleLoc());
1904 } else {
1905 // There is an extraneous 'template<>' for this member.
1906 Diag(TemplateParams->getTemplateLoc(),
1907 diag::err_template_member_noparams)
1908 << II
1909 << SourceRange(TemplateParams->getTemplateLoc(),
1910 TemplateParams->getRAngleLoc());
1911 }
1912 return 0;
1913 }
1914
Douglas Gregor922fff22010-10-13 22:19:53 +00001915 if (SS.isSet() && !SS.isInvalid()) {
1916 // The user provided a superfluous scope specifier inside a class
1917 // definition:
1918 //
1919 // class X {
1920 // int X::member;
1921 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001922 if (DeclContext *DC = computeDeclContext(SS, false))
1923 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001924 else
1925 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1926 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001927
Douglas Gregor922fff22010-10-13 22:19:53 +00001928 SS.clear();
1929 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001930
John McCall76da55d2013-04-16 07:28:30 +00001931 AttributeList *MSPropertyAttr =
1932 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1933 if (MSPropertyAttr) {
1934 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1935 BitWidth, InitStyle, AS, MSPropertyAttr);
1936 isInstField = false;
1937 } else {
1938 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1939 BitWidth, InitStyle, AS);
1940 }
Chris Lattner6f8ce142009-03-05 23:03:49 +00001941 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001942 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001943 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001944
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001945 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001946 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001947 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001948 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001949
1950 // Non-instance-fields can't have a bitfield.
1951 if (BitWidth) {
1952 if (Member->isInvalidDecl()) {
1953 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001954 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001955 // C++ 9.6p3: A bit-field shall not be a static member.
1956 // "static member 'A' cannot be a bit-field"
1957 Diag(Loc, diag::err_static_not_bitfield)
1958 << Name << BitWidth->getSourceRange();
1959 } else if (isa<TypedefDecl>(Member)) {
1960 // "typedef member 'x' cannot be a bit-field"
1961 Diag(Loc, diag::err_typedef_not_bitfield)
1962 << Name << BitWidth->getSourceRange();
1963 } else {
1964 // A function typedef ("typedef int f(); f a;").
1965 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1966 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001967 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001968 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001969 }
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Chris Lattner8b963ef2009-03-05 23:01:03 +00001971 BitWidth = 0;
1972 Member->setInvalidDecl();
1973 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001974
1975 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Douglas Gregor37b372b2009-08-20 22:52:58 +00001977 // If we have declared a member function template, set the access of the
1978 // templated declaration as well.
1979 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1980 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001981 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001982
Richard Smitha4b39652012-08-06 03:25:17 +00001983 if (VS.isOverrideSpecified())
1984 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1985 if (VS.isFinalSpecified())
1986 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001987
Douglas Gregorf5251602011-03-08 17:10:18 +00001988 if (VS.getLastLocation().isValid()) {
1989 // Update the end location of a method that has a virt-specifiers.
1990 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1991 MD->setRangeEnd(VS.getLastLocation());
1992 }
Richard Smitha4b39652012-08-06 03:25:17 +00001993
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001994 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001995
Douglas Gregor10bd3682008-11-17 22:58:34 +00001996 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001997
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001998 if (isInstField) {
1999 FieldDecl *FD = cast<FieldDecl>(Member);
2000 FieldCollector->Add(FD);
2001
2002 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2003 FD->getLocation())
2004 != DiagnosticsEngine::Ignored) {
2005 // Remember all explicit private FieldDecls that have a name, no side
2006 // effects and are not part of a dependent type declaration.
2007 if (!FD->isImplicit() && FD->getDeclName() &&
2008 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002009 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002010 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002011 !InitializationHasSideEffects(*FD))
2012 UnusedPrivateFields.insert(FD);
2013 }
2014 }
2015
John McCalld226f652010-08-21 09:40:31 +00002016 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002017}
2018
Hans Wennborg471f9852012-09-18 15:58:06 +00002019namespace {
2020 class UninitializedFieldVisitor
2021 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2022 Sema &S;
2023 ValueDecl *VD;
2024 public:
2025 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2026 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002027 S(S) {
2028 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2029 this->VD = IFD->getAnonField();
2030 else
2031 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002032 }
2033
2034 void HandleExpr(Expr *E) {
2035 if (!E) return;
2036
2037 // Expressions like x(x) sometimes lack the surrounding expressions
2038 // but need to be checked anyways.
2039 HandleValue(E);
2040 Visit(E);
2041 }
2042
2043 void HandleValue(Expr *E) {
2044 E = E->IgnoreParens();
2045
2046 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2047 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002048 return;
2049
2050 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2051 // or union.
2052 MemberExpr *FieldME = ME;
2053
Hans Wennborg471f9852012-09-18 15:58:06 +00002054 Expr *Base = E;
2055 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002056 ME = cast<MemberExpr>(Base);
2057
2058 if (isa<VarDecl>(ME->getMemberDecl()))
2059 return;
2060
2061 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2062 if (!FD->isAnonymousStructOrUnion())
2063 FieldME = ME;
2064
Hans Wennborg471f9852012-09-18 15:58:06 +00002065 Base = ME->getBase();
2066 }
2067
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002068 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002069 unsigned diag = VD->getType()->isReferenceType()
2070 ? diag::warn_reference_field_is_uninit
2071 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002072 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002073 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002074 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002075 }
2076
2077 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2078 HandleValue(CO->getTrueExpr());
2079 HandleValue(CO->getFalseExpr());
2080 return;
2081 }
2082
2083 if (BinaryConditionalOperator *BCO =
2084 dyn_cast<BinaryConditionalOperator>(E)) {
2085 HandleValue(BCO->getCommon());
2086 HandleValue(BCO->getFalseExpr());
2087 return;
2088 }
2089
2090 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2091 switch (BO->getOpcode()) {
2092 default:
2093 return;
2094 case(BO_PtrMemD):
2095 case(BO_PtrMemI):
2096 HandleValue(BO->getLHS());
2097 return;
2098 case(BO_Comma):
2099 HandleValue(BO->getRHS());
2100 return;
2101 }
2102 }
2103 }
2104
2105 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2106 if (E->getCastKind() == CK_LValueToRValue)
2107 HandleValue(E->getSubExpr());
2108
2109 Inherited::VisitImplicitCastExpr(E);
2110 }
2111
2112 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2113 Expr *Callee = E->getCallee();
2114 if (isa<MemberExpr>(Callee))
2115 HandleValue(Callee);
2116
2117 Inherited::VisitCXXMemberCallExpr(E);
2118 }
2119 };
2120 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2121 ValueDecl *VD) {
2122 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2123 }
2124} // namespace
2125
Richard Smith7a614d82011-06-11 17:19:42 +00002126/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002127/// in-class initializer for a non-static C++ class member, and after
2128/// instantiating an in-class initializer in a class template. Such actions
2129/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002130void
Richard Smithca523302012-06-10 03:12:00 +00002131Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002132 Expr *InitExpr) {
2133 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002134 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2135 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002136
2137 if (!InitExpr) {
2138 FD->setInvalidDecl();
2139 FD->removeInClassInitializer();
2140 return;
2141 }
2142
Peter Collingbournefef21892011-10-23 18:59:44 +00002143 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2144 FD->setInvalidDecl();
2145 FD->removeInClassInitializer();
2146 return;
2147 }
2148
Hans Wennborg471f9852012-09-18 15:58:06 +00002149 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2150 != DiagnosticsEngine::Ignored) {
2151 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2152 }
2153
Richard Smith7a614d82011-06-11 17:19:42 +00002154 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002155 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00002156 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002157 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00002158 << /*at end of ctor*/1 << InitExpr->getSourceRange();
2159 }
Sebastian Redl33deb352012-02-22 10:50:08 +00002160 Expr **Inits = &InitExpr;
2161 unsigned NumInits = 1;
2162 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002163 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002164 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002165 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00002166 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2167 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00002168 if (Init.isInvalid()) {
2169 FD->setInvalidDecl();
2170 return;
2171 }
Richard Smith7a614d82011-06-11 17:19:42 +00002172 }
2173
Richard Smith41956372013-01-14 22:39:08 +00002174 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002175 // The initialization of each base and member constitutes a
2176 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002177 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002178 if (Init.isInvalid()) {
2179 FD->setInvalidDecl();
2180 return;
2181 }
2182
2183 InitExpr = Init.release();
2184
2185 FD->setInClassInitializer(InitExpr);
2186}
2187
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002188/// \brief Find the direct and/or virtual base specifiers that
2189/// correspond to the given base type, for use in base initialization
2190/// within a constructor.
2191static bool FindBaseInitializer(Sema &SemaRef,
2192 CXXRecordDecl *ClassDecl,
2193 QualType BaseType,
2194 const CXXBaseSpecifier *&DirectBaseSpec,
2195 const CXXBaseSpecifier *&VirtualBaseSpec) {
2196 // First, check for a direct base class.
2197 DirectBaseSpec = 0;
2198 for (CXXRecordDecl::base_class_const_iterator Base
2199 = ClassDecl->bases_begin();
2200 Base != ClassDecl->bases_end(); ++Base) {
2201 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2202 // We found a direct base of this type. That's what we're
2203 // initializing.
2204 DirectBaseSpec = &*Base;
2205 break;
2206 }
2207 }
2208
2209 // Check for a virtual base class.
2210 // FIXME: We might be able to short-circuit this if we know in advance that
2211 // there are no virtual bases.
2212 VirtualBaseSpec = 0;
2213 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2214 // We haven't found a base yet; search the class hierarchy for a
2215 // virtual base class.
2216 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2217 /*DetectVirtual=*/false);
2218 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2219 BaseType, Paths)) {
2220 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2221 Path != Paths.end(); ++Path) {
2222 if (Path->back().Base->isVirtual()) {
2223 VirtualBaseSpec = Path->back().Base;
2224 break;
2225 }
2226 }
2227 }
2228 }
2229
2230 return DirectBaseSpec || VirtualBaseSpec;
2231}
2232
Sebastian Redl6df65482011-09-24 17:48:25 +00002233/// \brief Handle a C++ member initializer using braced-init-list syntax.
2234MemInitResult
2235Sema::ActOnMemInitializer(Decl *ConstructorD,
2236 Scope *S,
2237 CXXScopeSpec &SS,
2238 IdentifierInfo *MemberOrBase,
2239 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002240 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002241 SourceLocation IdLoc,
2242 Expr *InitList,
2243 SourceLocation EllipsisLoc) {
2244 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002245 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002246 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002247}
2248
2249/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002250MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002251Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002252 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002253 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002254 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002255 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002256 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002257 SourceLocation IdLoc,
2258 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002259 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002260 SourceLocation RParenLoc,
2261 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002262 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2263 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002264 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002265 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002266 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002267}
2268
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002269namespace {
2270
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002271// Callback to only accept typo corrections that can be a valid C++ member
2272// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002273class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2274 public:
2275 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2276 : ClassDecl(ClassDecl) {}
2277
2278 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2279 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2280 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2281 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2282 else
2283 return isa<TypeDecl>(ND);
2284 }
2285 return false;
2286 }
2287
2288 private:
2289 CXXRecordDecl *ClassDecl;
2290};
2291
2292}
2293
Sebastian Redl6df65482011-09-24 17:48:25 +00002294/// \brief Handle a C++ member initializer.
2295MemInitResult
2296Sema::BuildMemInitializer(Decl *ConstructorD,
2297 Scope *S,
2298 CXXScopeSpec &SS,
2299 IdentifierInfo *MemberOrBase,
2300 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002301 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002302 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002303 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002304 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002305 if (!ConstructorD)
2306 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002308 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002309
2310 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002311 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002312 if (!Constructor) {
2313 // The user wrote a constructor initializer on a function that is
2314 // not a C++ constructor. Ignore the error for now, because we may
2315 // have more member initializers coming; we'll diagnose it just
2316 // once in ActOnMemInitializers.
2317 return true;
2318 }
2319
2320 CXXRecordDecl *ClassDecl = Constructor->getParent();
2321
2322 // C++ [class.base.init]p2:
2323 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002324 // constructor's class and, if not found in that scope, are looked
2325 // up in the scope containing the constructor's definition.
2326 // [Note: if the constructor's class contains a member with the
2327 // same name as a direct or virtual base class of the class, a
2328 // mem-initializer-id naming the member or base class and composed
2329 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002330 // mem-initializer-id for the hidden base class may be specified
2331 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002332 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002333 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002334 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002335 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002336 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002337 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002338 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2339 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002340 if (EllipsisLoc.isValid())
2341 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002342 << MemberOrBase
2343 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002344
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002345 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002346 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002347 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002348 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002349 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002350 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002351 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002352
2353 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002354 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002355 } else if (DS.getTypeSpecType() == TST_decltype) {
2356 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002357 } else {
2358 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2359 LookupParsedName(R, S, &SS);
2360
2361 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2362 if (!TyD) {
2363 if (R.isAmbiguous()) return true;
2364
John McCallfd225442010-04-09 19:01:14 +00002365 // We don't want access-control diagnostics here.
2366 R.suppressDiagnostics();
2367
Douglas Gregor7a886e12010-01-19 06:46:48 +00002368 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2369 bool NotUnknownSpecialization = false;
2370 DeclContext *DC = computeDeclContext(SS, false);
2371 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2372 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2373
2374 if (!NotUnknownSpecialization) {
2375 // When the scope specifier can refer to a member of an unknown
2376 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002377 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2378 SS.getWithLocInContext(Context),
2379 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002380 if (BaseType.isNull())
2381 return true;
2382
Douglas Gregor7a886e12010-01-19 06:46:48 +00002383 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002384 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002385 }
2386 }
2387
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002388 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002389 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002390 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002391 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002392 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002393 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002394 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2395 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002396 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002397 // We have found a non-static data member with a similar
2398 // name to what was typed; complain and initialize that
2399 // member.
2400 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2401 << MemberOrBase << true << CorrectedQuotedStr
2402 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2403 Diag(Member->getLocation(), diag::note_previous_decl)
2404 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002405
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002406 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002407 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002408 const CXXBaseSpecifier *DirectBaseSpec;
2409 const CXXBaseSpecifier *VirtualBaseSpec;
2410 if (FindBaseInitializer(*this, ClassDecl,
2411 Context.getTypeDeclType(Type),
2412 DirectBaseSpec, VirtualBaseSpec)) {
2413 // We have found a direct or virtual base class with a
2414 // similar name to what was typed; complain and initialize
2415 // that base class.
2416 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002417 << MemberOrBase << false << CorrectedQuotedStr
2418 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002419
2420 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2421 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002422 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002423 diag::note_base_class_specified_here)
2424 << BaseSpec->getType()
2425 << BaseSpec->getSourceRange();
2426
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002427 TyD = Type;
2428 }
2429 }
2430 }
2431
Douglas Gregor7a886e12010-01-19 06:46:48 +00002432 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002433 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002434 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002435 return true;
2436 }
John McCall2b194412009-12-21 10:41:20 +00002437 }
2438
Douglas Gregor7a886e12010-01-19 06:46:48 +00002439 if (BaseType.isNull()) {
2440 BaseType = Context.getTypeDeclType(TyD);
2441 if (SS.isSet()) {
2442 NestedNameSpecifier *Qualifier =
2443 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002444
Douglas Gregor7a886e12010-01-19 06:46:48 +00002445 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002446 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002447 }
John McCall2b194412009-12-21 10:41:20 +00002448 }
2449 }
Mike Stump1eb44332009-09-09 15:08:12 +00002450
John McCalla93c9342009-12-07 02:54:59 +00002451 if (!TInfo)
2452 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002453
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002454 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002455}
2456
Chandler Carruth81c64772011-09-03 01:14:15 +00002457/// Checks a member initializer expression for cases where reference (or
2458/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002459static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2460 Expr *Init,
2461 SourceLocation IdLoc) {
2462 QualType MemberTy = Member->getType();
2463
2464 // We only handle pointers and references currently.
2465 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2466 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2467 return;
2468
2469 const bool IsPointer = MemberTy->isPointerType();
2470 if (IsPointer) {
2471 if (const UnaryOperator *Op
2472 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2473 // The only case we're worried about with pointers requires taking the
2474 // address.
2475 if (Op->getOpcode() != UO_AddrOf)
2476 return;
2477
2478 Init = Op->getSubExpr();
2479 } else {
2480 // We only handle address-of expression initializers for pointers.
2481 return;
2482 }
2483 }
2484
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002485 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2486 // Taking the address of a temporary will be diagnosed as a hard error.
2487 if (IsPointer)
2488 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002489
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002490 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2491 << Member << Init->getSourceRange();
2492 } else if (const DeclRefExpr *DRE
2493 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2494 // We only warn when referring to a non-reference parameter declaration.
2495 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2496 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002497 return;
2498
2499 S.Diag(Init->getExprLoc(),
2500 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2501 : diag::warn_bind_ref_member_to_parameter)
2502 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002503 } else {
2504 // Other initializers are fine.
2505 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002506 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002507
2508 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2509 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002510}
2511
John McCallf312b1e2010-08-26 23:41:50 +00002512MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002513Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002514 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002515 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2516 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2517 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002518 "Member must be a FieldDecl or IndirectFieldDecl");
2519
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002520 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002521 return true;
2522
Douglas Gregor464b2f02010-11-05 22:21:31 +00002523 if (Member->isInvalidDecl())
2524 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002525
John McCallb4190042009-11-04 23:02:40 +00002526 // Diagnose value-uses of fields to initialize themselves, e.g.
2527 // foo(foo)
2528 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002529 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002530 Expr **Args;
2531 unsigned NumArgs;
2532 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2533 Args = ParenList->getExprs();
2534 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002535 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002536 Args = InitList->getInits();
2537 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002538 } else {
2539 // Template instantiation doesn't reconstruct ParenListExprs for us.
2540 Args = &Init;
2541 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002542 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002543
Richard Trieude5e75c2012-06-14 23:11:34 +00002544 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2545 != DiagnosticsEngine::Ignored)
2546 for (unsigned i = 0; i < NumArgs; ++i)
2547 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002548 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002549 // initializing the i'th field, throw a warning if any of the >= i'th
2550 // fields are used, as they are not yet initialized.
2551 // Right now we are only handling the case where the i'th field uses
2552 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002553 // Also need to take into account that some fields may be initialized by
2554 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002555 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002556
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002557 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002558
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002559 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002560 // Can't check initialization for a member of dependent type or when
2561 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002562 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002563 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002564 bool InitList = false;
2565 if (isa<InitListExpr>(Init)) {
2566 InitList = true;
2567 Args = &Init;
2568 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002569
2570 if (isStdInitializerList(Member->getType(), 0)) {
2571 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2572 << /*at end of ctor*/1 << InitRange;
2573 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002574 }
2575
Chandler Carruth894aed92010-12-06 09:23:57 +00002576 // Initialize the member.
2577 InitializedEntity MemberEntity =
2578 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2579 : InitializedEntity::InitializeMember(IndirectMember, 0);
2580 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002581 InitList ? InitializationKind::CreateDirectList(IdLoc)
2582 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2583 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002584
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002585 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2586 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002587 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002588 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002589 if (MemberInit.isInvalid())
2590 return true;
2591
Richard Smith41956372013-01-14 22:39:08 +00002592 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002593 // The initialization of each base and member constitutes a
2594 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002595 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002596 if (MemberInit.isInvalid())
2597 return true;
2598
Richard Smithc83c2302012-12-19 01:39:02 +00002599 Init = MemberInit.get();
2600 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002601 }
2602
Chandler Carruth894aed92010-12-06 09:23:57 +00002603 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002604 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2605 InitRange.getBegin(), Init,
2606 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002607 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002608 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2609 InitRange.getBegin(), Init,
2610 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002611 }
Eli Friedman59c04372009-07-29 19:44:27 +00002612}
2613
John McCallf312b1e2010-08-26 23:41:50 +00002614MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002615Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002616 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002617 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002618 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002619 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002620 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002621 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002622
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002623 bool InitList = true;
2624 Expr **Args = &Init;
2625 unsigned NumArgs = 1;
2626 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2627 InitList = false;
2628 Args = ParenList->getExprs();
2629 NumArgs = ParenList->getNumExprs();
2630 }
2631
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002632 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002633 // Initialize the object.
2634 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2635 QualType(ClassDecl->getTypeForDecl(), 0));
2636 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002637 InitList ? InitializationKind::CreateDirectList(NameLoc)
2638 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2639 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002640 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2641 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002642 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002643 0);
Sean Hunt41717662011-02-26 19:13:13 +00002644 if (DelegationInit.isInvalid())
2645 return true;
2646
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002647 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2648 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002649
Richard Smith41956372013-01-14 22:39:08 +00002650 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002651 // The initialization of each base and member constitutes a
2652 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002653 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2654 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002655 if (DelegationInit.isInvalid())
2656 return true;
2657
Eli Friedmand21016f2012-05-19 23:35:23 +00002658 // If we are in a dependent context, template instantiation will
2659 // perform this type-checking again. Just save the arguments that we
2660 // received in a ParenListExpr.
2661 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2662 // of the information that we have about the base
2663 // initializer. However, deconstructing the ASTs is a dicey process,
2664 // and this approach is far more likely to get the corner cases right.
2665 if (CurContext->isDependentContext())
2666 DelegationInit = Owned(Init);
2667
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002668 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002669 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002670 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002671}
2672
2673MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002674Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002675 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002676 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002677 SourceLocation BaseLoc
2678 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002679
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002680 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2681 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2682 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2683
2684 // C++ [class.base.init]p2:
2685 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002686 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002687 // of that class, the mem-initializer is ill-formed. A
2688 // mem-initializer-list can initialize a base class using any
2689 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002690 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002691
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002692 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002693 if (EllipsisLoc.isValid()) {
2694 // This is a pack expansion.
2695 if (!BaseType->containsUnexpandedParameterPack()) {
2696 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002697 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002698
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002699 EllipsisLoc = SourceLocation();
2700 }
2701 } else {
2702 // Check for any unexpanded parameter packs.
2703 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2704 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002705
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002706 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002707 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002708 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002709
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002710 // Check for direct and virtual base classes.
2711 const CXXBaseSpecifier *DirectBaseSpec = 0;
2712 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2713 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002714 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2715 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002716 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002717
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002718 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2719 VirtualBaseSpec);
2720
2721 // C++ [base.class.init]p2:
2722 // Unless the mem-initializer-id names a nonstatic data member of the
2723 // constructor's class or a direct or virtual base of that class, the
2724 // mem-initializer is ill-formed.
2725 if (!DirectBaseSpec && !VirtualBaseSpec) {
2726 // If the class has any dependent bases, then it's possible that
2727 // one of those types will resolve to the same type as
2728 // BaseType. Therefore, just treat this as a dependent base
2729 // class initialization. FIXME: Should we try to check the
2730 // initialization anyway? It seems odd.
2731 if (ClassDecl->hasAnyDependentBases())
2732 Dependent = true;
2733 else
2734 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2735 << BaseType << Context.getTypeDeclType(ClassDecl)
2736 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2737 }
2738 }
2739
2740 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002741 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002742
Sebastian Redl6df65482011-09-24 17:48:25 +00002743 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2744 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002745 InitRange.getBegin(), Init,
2746 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002747 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002748
2749 // C++ [base.class.init]p2:
2750 // If a mem-initializer-id is ambiguous because it designates both
2751 // a direct non-virtual base class and an inherited virtual base
2752 // class, the mem-initializer is ill-formed.
2753 if (DirectBaseSpec && VirtualBaseSpec)
2754 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002755 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002756
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002757 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002758 if (!BaseSpec)
2759 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2760
2761 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002762 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002763 Expr **Args = &Init;
2764 unsigned NumArgs = 1;
2765 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002766 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002767 Args = ParenList->getExprs();
2768 NumArgs = ParenList->getNumExprs();
2769 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002770
2771 InitializedEntity BaseEntity =
2772 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2773 InitializationKind Kind =
2774 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2775 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2776 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002777 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2778 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002779 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002780 if (BaseInit.isInvalid())
2781 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002782
Richard Smith41956372013-01-14 22:39:08 +00002783 // C++11 [class.base.init]p7:
2784 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002785 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002786 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002787 if (BaseInit.isInvalid())
2788 return true;
2789
2790 // If we are in a dependent context, template instantiation will
2791 // perform this type-checking again. Just save the arguments that we
2792 // received in a ParenListExpr.
2793 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2794 // of the information that we have about the base
2795 // initializer. However, deconstructing the ASTs is a dicey process,
2796 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002797 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002798 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002799
Sean Huntcbb67482011-01-08 20:30:50 +00002800 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002801 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002802 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002803 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002804 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002805}
2806
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002807// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002808static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2809 if (T.isNull()) T = E->getType();
2810 QualType TargetType = SemaRef.BuildReferenceType(
2811 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002812 SourceLocation ExprLoc = E->getLocStart();
2813 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2814 TargetType, ExprLoc);
2815
2816 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2817 SourceRange(ExprLoc, ExprLoc),
2818 E->getSourceRange()).take();
2819}
2820
Anders Carlssone5ef7402010-04-23 03:10:23 +00002821/// ImplicitInitializerKind - How an implicit base or member initializer should
2822/// initialize its base or member.
2823enum ImplicitInitializerKind {
2824 IIK_Default,
2825 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002826 IIK_Move,
2827 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002828};
2829
Anders Carlssondefefd22010-04-23 02:00:02 +00002830static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002831BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002832 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002833 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002834 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002835 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002836 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002837 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2838 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002839
John McCall60d7b3a2010-08-24 06:29:42 +00002840 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002841
2842 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002843 case IIK_Inherit: {
2844 const CXXRecordDecl *Inherited =
2845 Constructor->getInheritedConstructor()->getParent();
2846 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2847 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2848 // C++11 [class.inhctor]p8:
2849 // Each expression in the expression-list is of the form
2850 // static_cast<T&&>(p), where p is the name of the corresponding
2851 // constructor parameter and T is the declared type of p.
2852 SmallVector<Expr*, 16> Args;
2853 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2854 ParmVarDecl *PD = Constructor->getParamDecl(I);
2855 ExprResult ArgExpr =
2856 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2857 VK_LValue, SourceLocation());
2858 if (ArgExpr.isInvalid())
2859 return true;
2860 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2861 }
2862
2863 InitializationKind InitKind = InitializationKind::CreateDirect(
2864 Constructor->getLocation(), SourceLocation(), SourceLocation());
2865 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2866 Args.data(), Args.size());
2867 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2868 break;
2869 }
2870 }
2871 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002872 case IIK_Default: {
2873 InitializationKind InitKind
2874 = InitializationKind::CreateDefault(Constructor->getLocation());
2875 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002876 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002877 break;
2878 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002879
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002880 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002881 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002882 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002883 ParmVarDecl *Param = Constructor->getParamDecl(0);
2884 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002885
Anders Carlssone5ef7402010-04-23 03:10:23 +00002886 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002887 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002888 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002889 Constructor->getLocation(), ParamType,
2890 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002891
Eli Friedman5f2987c2012-02-02 03:46:19 +00002892 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2893
Anders Carlssonc7957502010-04-24 22:02:54 +00002894 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002895 QualType ArgTy =
2896 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2897 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002898
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002899 if (Moving) {
2900 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2901 }
2902
John McCallf871d0c2010-08-07 06:22:56 +00002903 CXXCastPath BasePath;
2904 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002905 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2906 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002907 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002908 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002909
Anders Carlssone5ef7402010-04-23 03:10:23 +00002910 InitializationKind InitKind
2911 = InitializationKind::CreateDirect(Constructor->getLocation(),
2912 SourceLocation(), SourceLocation());
2913 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2914 &CopyCtorArg, 1);
2915 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002916 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002917 break;
2918 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002919 }
John McCall9ae2f072010-08-23 23:25:46 +00002920
Douglas Gregor53c374f2010-12-07 00:41:46 +00002921 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002922 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002923 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002924
Anders Carlssondefefd22010-04-23 02:00:02 +00002925 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002926 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002927 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2928 SourceLocation()),
2929 BaseSpec->isVirtual(),
2930 SourceLocation(),
2931 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002932 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002933 SourceLocation());
2934
Anders Carlssondefefd22010-04-23 02:00:02 +00002935 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002936}
2937
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002938static bool RefersToRValueRef(Expr *MemRef) {
2939 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2940 return Referenced->getType()->isRValueReferenceType();
2941}
2942
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002943static bool
2944BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002945 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002946 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002947 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002948 if (Field->isInvalidDecl())
2949 return true;
2950
Chandler Carruthf186b542010-06-29 23:50:44 +00002951 SourceLocation Loc = Constructor->getLocation();
2952
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002953 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2954 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002955 ParmVarDecl *Param = Constructor->getParamDecl(0);
2956 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002957
2958 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002959 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2960 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002961
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002962 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002963 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002964 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002965 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002966
Eli Friedman5f2987c2012-02-02 03:46:19 +00002967 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2968
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002969 if (Moving) {
2970 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2971 }
2972
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002973 // Build a reference to this field within the parameter.
2974 CXXScopeSpec SS;
2975 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2976 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002977 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2978 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002979 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002980 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002981 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002982 ParamType, Loc,
2983 /*IsArrow=*/false,
2984 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002985 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002986 /*FirstQualifierInScope=*/0,
2987 MemberLookup,
2988 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002989 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002990 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002991
2992 // C++11 [class.copy]p15:
2993 // - if a member m has rvalue reference type T&&, it is direct-initialized
2994 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002995 if (RefersToRValueRef(CtorArg.get())) {
2996 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002997 }
2998
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002999 // When the field we are copying is an array, create index variables for
3000 // each dimension of the array. We use these index variables to subscript
3001 // the source array, and other clients (e.g., CodeGen) will perform the
3002 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003003 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003004 QualType BaseType = Field->getType();
3005 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003006 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003007 while (const ConstantArrayType *Array
3008 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003009 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003010 // Create the iteration variable for this array index.
3011 IdentifierInfo *IterationVarName = 0;
3012 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003013 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003014 llvm::raw_svector_ostream OS(Str);
3015 OS << "__i" << IndexVariables.size();
3016 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3017 }
3018 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003019 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003020 IterationVarName, SizeType,
3021 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003022 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003023 IndexVariables.push_back(IterationVar);
3024
3025 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003026 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003027 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003028 assert(!IterationVarRef.isInvalid() &&
3029 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003030 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3031 assert(!IterationVarRef.isInvalid() &&
3032 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003033
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003034 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003035 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003036 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003037 Loc);
3038 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003039 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003040
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003041 BaseType = Array->getElementType();
3042 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003043
3044 // The array subscript expression is an lvalue, which is wrong for moving.
3045 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003046 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003047
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003048 // Construct the entity that we will be initializing. For an array, this
3049 // will be first element in the array, which may require several levels
3050 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003051 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003052 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003053 if (Indirect)
3054 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3055 else
3056 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003057 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3058 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3059 0,
3060 Entities.back()));
3061
3062 // Direct-initialize to use the copy constructor.
3063 InitializationKind InitKind =
3064 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3065
Sebastian Redl74e611a2011-09-04 18:14:28 +00003066 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003067 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003068 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003069
John McCall60d7b3a2010-08-24 06:29:42 +00003070 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003071 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003072 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003073 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003074 if (MemberInit.isInvalid())
3075 return true;
3076
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003077 if (Indirect) {
3078 assert(IndexVariables.size() == 0 &&
3079 "Indirect field improperly initialized");
3080 CXXMemberInit
3081 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3082 Loc, Loc,
3083 MemberInit.takeAs<Expr>(),
3084 Loc);
3085 } else
3086 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3087 Loc, MemberInit.takeAs<Expr>(),
3088 Loc,
3089 IndexVariables.data(),
3090 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003091 return false;
3092 }
3093
Richard Smith07b0fdc2013-03-18 21:12:30 +00003094 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3095 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003096
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003097 QualType FieldBaseElementType =
3098 SemaRef.Context.getBaseElementType(Field->getType());
3099
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003100 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003101 InitializedEntity InitEntity
3102 = Indirect? InitializedEntity::InitializeMember(Indirect)
3103 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003104 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003105 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003106
3107 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00003108 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00003109 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00003110
Douglas Gregor53c374f2010-12-07 00:41:46 +00003111 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003112 if (MemberInit.isInvalid())
3113 return true;
3114
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003115 if (Indirect)
3116 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3117 Indirect, Loc,
3118 Loc,
3119 MemberInit.get(),
3120 Loc);
3121 else
3122 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3123 Field, Loc, Loc,
3124 MemberInit.get(),
3125 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003126 return false;
3127 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003128
Sean Hunt1f2f3842011-05-17 00:19:05 +00003129 if (!Field->getParent()->isUnion()) {
3130 if (FieldBaseElementType->isReferenceType()) {
3131 SemaRef.Diag(Constructor->getLocation(),
3132 diag::err_uninitialized_member_in_ctor)
3133 << (int)Constructor->isImplicit()
3134 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3135 << 0 << Field->getDeclName();
3136 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3137 return true;
3138 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003139
Sean Hunt1f2f3842011-05-17 00:19:05 +00003140 if (FieldBaseElementType.isConstQualified()) {
3141 SemaRef.Diag(Constructor->getLocation(),
3142 diag::err_uninitialized_member_in_ctor)
3143 << (int)Constructor->isImplicit()
3144 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3145 << 1 << Field->getDeclName();
3146 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3147 return true;
3148 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003149 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003150
David Blaikie4e4d0842012-03-11 07:00:24 +00003151 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003152 FieldBaseElementType->isObjCRetainableType() &&
3153 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3154 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003155 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003156 // Default-initialize Objective-C pointers to NULL.
3157 CXXMemberInit
3158 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3159 Loc, Loc,
3160 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3161 Loc);
3162 return false;
3163 }
3164
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003165 // Nothing to initialize.
3166 CXXMemberInit = 0;
3167 return false;
3168}
John McCallf1860e52010-05-20 23:23:51 +00003169
3170namespace {
3171struct BaseAndFieldInfo {
3172 Sema &S;
3173 CXXConstructorDecl *Ctor;
3174 bool AnyErrorsInInits;
3175 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003176 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003177 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003178
3179 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3180 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003181 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3182 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003183 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003184 else if (Generated && Ctor->isMoveConstructor())
3185 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003186 else if (Ctor->getInheritedConstructor())
3187 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003188 else
3189 IIK = IIK_Default;
3190 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003191
3192 bool isImplicitCopyOrMove() const {
3193 switch (IIK) {
3194 case IIK_Copy:
3195 case IIK_Move:
3196 return true;
3197
3198 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003199 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003200 return false;
3201 }
David Blaikie30263482012-01-20 21:50:17 +00003202
3203 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003204 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003205
3206 bool addFieldInitializer(CXXCtorInitializer *Init) {
3207 AllToInit.push_back(Init);
3208
3209 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003210 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003211 S.UnusedPrivateFields.remove(Init->getAnyMember());
3212
3213 return false;
3214 }
John McCallf1860e52010-05-20 23:23:51 +00003215};
3216}
3217
Richard Smitha4950662011-09-19 13:34:43 +00003218/// \brief Determine whether the given indirect field declaration is somewhere
3219/// within an anonymous union.
3220static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3221 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3222 CEnd = F->chain_end();
3223 C != CEnd; ++C)
3224 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3225 if (Record->isUnion())
3226 return true;
3227
3228 return false;
3229}
3230
Douglas Gregorddb21472011-11-02 23:04:16 +00003231/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3232/// array type.
3233static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3234 if (T->isIncompleteArrayType())
3235 return true;
3236
3237 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3238 if (!ArrayT->getSize())
3239 return true;
3240
3241 T = ArrayT->getElementType();
3242 }
3243
3244 return false;
3245}
3246
Richard Smith7a614d82011-06-11 17:19:42 +00003247static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003248 FieldDecl *Field,
3249 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003250
Chandler Carruthe861c602010-06-30 02:59:29 +00003251 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003252 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3253 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003254
Richard Smith0b8220a2012-08-07 21:30:42 +00003255 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003256 // has a brace-or-equal-initializer, the entity is initialized as specified
3257 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003258 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003259 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3260 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003261 CXXCtorInitializer *Init;
3262 if (Indirect)
3263 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3264 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003265 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003266 SourceLocation());
3267 else
3268 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3269 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003270 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003271 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003272 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003273 }
3274
Richard Smithc115f632011-09-18 11:14:50 +00003275 // Don't build an implicit initializer for union members if none was
3276 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003277 if (Field->getParent()->isUnion() ||
3278 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003279 return false;
3280
Douglas Gregorddb21472011-11-02 23:04:16 +00003281 // Don't initialize incomplete or zero-length arrays.
3282 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3283 return false;
3284
John McCallf1860e52010-05-20 23:23:51 +00003285 // Don't try to build an implicit initializer if there were semantic
3286 // errors in any of the initializers (and therefore we might be
3287 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003288 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003289 return false;
3290
Sean Huntcbb67482011-01-08 20:30:50 +00003291 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003292 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3293 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003294 return true;
John McCallf1860e52010-05-20 23:23:51 +00003295
Richard Smith0b8220a2012-08-07 21:30:42 +00003296 if (!Init)
3297 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003298
Richard Smith0b8220a2012-08-07 21:30:42 +00003299 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003300}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003301
3302bool
3303Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3304 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003305 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003306 Constructor->setNumCtorInitializers(1);
3307 CXXCtorInitializer **initializer =
3308 new (Context) CXXCtorInitializer*[1];
3309 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3310 Constructor->setCtorInitializers(initializer);
3311
Sean Huntb76af9c2011-05-03 23:05:34 +00003312 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003313 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003314 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3315 }
3316
Sean Huntc1598702011-05-05 00:05:47 +00003317 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003318
Sean Hunt059ce0d2011-05-01 07:04:31 +00003319 return false;
3320}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003321
David Blaikie93c86172013-01-17 05:26:25 +00003322bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3323 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003324 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003325 // Just store the initializers as written, they will be checked during
3326 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003327 if (!Initializers.empty()) {
3328 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003329 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003330 new (Context) CXXCtorInitializer*[Initializers.size()];
3331 memcpy(baseOrMemberInitializers, Initializers.data(),
3332 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003333 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003334 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003335
3336 // Let template instantiation know whether we had errors.
3337 if (AnyErrors)
3338 Constructor->setInvalidDecl();
3339
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003340 return false;
3341 }
3342
John McCallf1860e52010-05-20 23:23:51 +00003343 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003344
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003345 // We need to build the initializer AST according to order of construction
3346 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003347 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003348 if (!ClassDecl)
3349 return true;
3350
Eli Friedman80c30da2009-11-09 19:20:36 +00003351 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003352
David Blaikie93c86172013-01-17 05:26:25 +00003353 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003354 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003355
3356 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003357 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003358 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003359 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003360 }
3361
Anders Carlsson711f34a2010-04-21 19:52:01 +00003362 // Keep track of the direct virtual bases.
3363 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3364 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3365 E = ClassDecl->bases_end(); I != E; ++I) {
3366 if (I->isVirtual())
3367 DirectVBases.insert(I);
3368 }
3369
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003370 // Push virtual bases before others.
3371 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3372 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3373
Sean Huntcbb67482011-01-08 20:30:50 +00003374 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003375 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3376 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003377 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003378 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003379 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003380 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003381 VBase, IsInheritedVirtualBase,
3382 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003383 HadError = true;
3384 continue;
3385 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003386
John McCallf1860e52010-05-20 23:23:51 +00003387 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003388 }
3389 }
Mike Stump1eb44332009-09-09 15:08:12 +00003390
John McCallf1860e52010-05-20 23:23:51 +00003391 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003392 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3393 E = ClassDecl->bases_end(); Base != E; ++Base) {
3394 // Virtuals are in the virtual base list and already constructed.
3395 if (Base->isVirtual())
3396 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003397
Sean Huntcbb67482011-01-08 20:30:50 +00003398 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003399 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3400 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003401 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003402 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003403 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003404 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003405 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003406 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003407 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003408 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003409
John McCallf1860e52010-05-20 23:23:51 +00003410 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003411 }
3412 }
Mike Stump1eb44332009-09-09 15:08:12 +00003413
John McCallf1860e52010-05-20 23:23:51 +00003414 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003415 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3416 MemEnd = ClassDecl->decls_end();
3417 Mem != MemEnd; ++Mem) {
3418 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003419 // C++ [class.bit]p2:
3420 // A declaration for a bit-field that omits the identifier declares an
3421 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3422 // initialized.
3423 if (F->isUnnamedBitfield())
3424 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003425
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003426 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003427 // handle anonymous struct/union fields based on their individual
3428 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003429 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003430 continue;
3431
3432 if (CollectFieldInitializer(*this, Info, F))
3433 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003434 continue;
3435 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003436
3437 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003438 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003439 continue;
3440
3441 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3442 if (F->getType()->isIncompleteArrayType()) {
3443 assert(ClassDecl->hasFlexibleArrayMember() &&
3444 "Incomplete array type is not valid");
3445 continue;
3446 }
3447
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003448 // Initialize each field of an anonymous struct individually.
3449 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3450 HadError = true;
3451
3452 continue;
3453 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003454 }
Mike Stump1eb44332009-09-09 15:08:12 +00003455
David Blaikie93c86172013-01-17 05:26:25 +00003456 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003457 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003458 Constructor->setNumCtorInitializers(NumInitializers);
3459 CXXCtorInitializer **baseOrMemberInitializers =
3460 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003461 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003462 NumInitializers * sizeof(CXXCtorInitializer*));
3463 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003464
John McCallef027fe2010-03-16 21:39:52 +00003465 // Constructors implicitly reference the base and member
3466 // destructors.
3467 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3468 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003469 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003470
3471 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003472}
3473
David Blaikieee000bb2013-01-17 08:49:22 +00003474static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003475 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003476 const RecordDecl *RD = RT->getDecl();
3477 if (RD->isAnonymousStructOrUnion()) {
3478 for (RecordDecl::field_iterator Field = RD->field_begin(),
3479 E = RD->field_end(); Field != E; ++Field)
3480 PopulateKeysForFields(*Field, IdealInits);
3481 return;
3482 }
Eli Friedman6347f422009-07-21 19:28:10 +00003483 }
David Blaikieee000bb2013-01-17 08:49:22 +00003484 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003485}
3486
Anders Carlssonea356fb2010-04-02 05:42:15 +00003487static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003488 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003489}
3490
Anders Carlssonea356fb2010-04-02 05:42:15 +00003491static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003492 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003493 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003494 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003495
David Blaikieee000bb2013-01-17 08:49:22 +00003496 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003497}
3498
David Blaikie93c86172013-01-17 05:26:25 +00003499static void DiagnoseBaseOrMemInitializerOrder(
3500 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3501 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003502 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003503 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003504
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003505 // Don't check initializers order unless the warning is enabled at the
3506 // location of at least one initializer.
3507 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003508 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003509 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003510 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3511 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003512 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003513 ShouldCheckOrder = true;
3514 break;
3515 }
3516 }
3517 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003518 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003519
John McCalld6ca8da2010-04-10 07:37:23 +00003520 // Build the list of bases and members in the order that they'll
3521 // actually be initialized. The explicit initializers should be in
3522 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003523 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003524
Anders Carlsson071d6102010-04-02 03:38:04 +00003525 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3526
John McCalld6ca8da2010-04-10 07:37:23 +00003527 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003528 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003529 ClassDecl->vbases_begin(),
3530 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003531 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003532
John McCalld6ca8da2010-04-10 07:37:23 +00003533 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003534 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003535 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003536 if (Base->isVirtual())
3537 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003538 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003539 }
Mike Stump1eb44332009-09-09 15:08:12 +00003540
John McCalld6ca8da2010-04-10 07:37:23 +00003541 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003542 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003543 E = ClassDecl->field_end(); Field != E; ++Field) {
3544 if (Field->isUnnamedBitfield())
3545 continue;
3546
David Blaikieee000bb2013-01-17 08:49:22 +00003547 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003548 }
3549
John McCalld6ca8da2010-04-10 07:37:23 +00003550 unsigned NumIdealInits = IdealInitKeys.size();
3551 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003552
Sean Huntcbb67482011-01-08 20:30:50 +00003553 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003554 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003555 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003556 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003557
3558 // Scan forward to try to find this initializer in the idealized
3559 // initializers list.
3560 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3561 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003562 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003563
3564 // If we didn't find this initializer, it must be because we
3565 // scanned past it on a previous iteration. That can only
3566 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003567 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003568 Sema::SemaDiagnosticBuilder D =
3569 SemaRef.Diag(PrevInit->getSourceLocation(),
3570 diag::warn_initializer_out_of_order);
3571
Francois Pichet00eb3f92010-12-04 09:14:42 +00003572 if (PrevInit->isAnyMemberInitializer())
3573 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003574 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003575 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003576
Francois Pichet00eb3f92010-12-04 09:14:42 +00003577 if (Init->isAnyMemberInitializer())
3578 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003579 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003580 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003581
3582 // Move back to the initializer's location in the ideal list.
3583 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3584 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003585 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003586
3587 assert(IdealIndex != NumIdealInits &&
3588 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003589 }
John McCalld6ca8da2010-04-10 07:37:23 +00003590
3591 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003592 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003593}
3594
John McCall3c3ccdb2010-04-10 09:28:51 +00003595namespace {
3596bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003597 CXXCtorInitializer *Init,
3598 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003599 if (!PrevInit) {
3600 PrevInit = Init;
3601 return false;
3602 }
3603
Douglas Gregordc392c12013-03-25 23:28:23 +00003604 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003605 S.Diag(Init->getSourceLocation(),
3606 diag::err_multiple_mem_initialization)
3607 << Field->getDeclName()
3608 << Init->getSourceRange();
3609 else {
John McCallf4c73712011-01-19 06:33:43 +00003610 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003611 assert(BaseClass && "neither field nor base");
3612 S.Diag(Init->getSourceLocation(),
3613 diag::err_multiple_base_initialization)
3614 << QualType(BaseClass, 0)
3615 << Init->getSourceRange();
3616 }
3617 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3618 << 0 << PrevInit->getSourceRange();
3619
3620 return true;
3621}
3622
Sean Huntcbb67482011-01-08 20:30:50 +00003623typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003624typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3625
3626bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003627 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003628 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003629 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003630 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003631 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003632
3633 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003634 if (Parent->isUnion()) {
3635 UnionEntry &En = Unions[Parent];
3636 if (En.first && En.first != Child) {
3637 S.Diag(Init->getSourceLocation(),
3638 diag::err_multiple_mem_union_initialization)
3639 << Field->getDeclName()
3640 << Init->getSourceRange();
3641 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3642 << 0 << En.second->getSourceRange();
3643 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003644 }
3645 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003646 En.first = Child;
3647 En.second = Init;
3648 }
David Blaikie6fe29652011-11-17 06:01:57 +00003649 if (!Parent->isAnonymousStructOrUnion())
3650 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003651 }
3652
3653 Child = Parent;
3654 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003655 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003656
3657 return false;
3658}
3659}
3660
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003661/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003662void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003663 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003664 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003665 bool AnyErrors) {
3666 if (!ConstructorDecl)
3667 return;
3668
3669 AdjustDeclIfTemplate(ConstructorDecl);
3670
3671 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003672 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003673
3674 if (!Constructor) {
3675 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3676 return;
3677 }
3678
John McCall3c3ccdb2010-04-10 09:28:51 +00003679 // Mapping for the duplicate initializers check.
3680 // For member initializers, this is keyed with a FieldDecl*.
3681 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003682 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003683
3684 // Mapping for the inconsistent anonymous-union initializers check.
3685 RedundantUnionMap MemberUnions;
3686
Anders Carlssonea356fb2010-04-02 05:42:15 +00003687 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003688 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003689 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003690
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003691 // Set the source order index.
3692 Init->setSourceOrder(i);
3693
Francois Pichet00eb3f92010-12-04 09:14:42 +00003694 if (Init->isAnyMemberInitializer()) {
3695 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003696 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3697 CheckRedundantUnionInit(*this, Init, MemberUnions))
3698 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003699 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003700 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3701 if (CheckRedundantInit(*this, Init, Members[Key]))
3702 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003703 } else {
3704 assert(Init->isDelegatingInitializer());
3705 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003706 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003707 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003708 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003709 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003710 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003711 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003712 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003713 // Return immediately as the initializer is set.
3714 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003715 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003716 }
3717
Anders Carlssonea356fb2010-04-02 05:42:15 +00003718 if (HadError)
3719 return;
3720
David Blaikie93c86172013-01-17 05:26:25 +00003721 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003722
David Blaikie93c86172013-01-17 05:26:25 +00003723 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003724}
3725
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003726void
John McCallef027fe2010-03-16 21:39:52 +00003727Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3728 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003729 // Ignore dependent contexts. Also ignore unions, since their members never
3730 // have destructors implicitly called.
3731 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003732 return;
John McCall58e6f342010-03-16 05:22:47 +00003733
3734 // FIXME: all the access-control diagnostics are positioned on the
3735 // field/base declaration. That's probably good; that said, the
3736 // user might reasonably want to know why the destructor is being
3737 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003738
Anders Carlsson9f853df2009-11-17 04:44:12 +00003739 // Non-static data members.
3740 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3741 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003742 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003743 if (Field->isInvalidDecl())
3744 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003745
3746 // Don't destroy incomplete or zero-length arrays.
3747 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3748 continue;
3749
Anders Carlsson9f853df2009-11-17 04:44:12 +00003750 QualType FieldType = Context.getBaseElementType(Field->getType());
3751
3752 const RecordType* RT = FieldType->getAs<RecordType>();
3753 if (!RT)
3754 continue;
3755
3756 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003757 if (FieldClassDecl->isInvalidDecl())
3758 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003759 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003760 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003761 // The destructor for an implicit anonymous union member is never invoked.
3762 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3763 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003764
Douglas Gregordb89f282010-07-01 22:47:18 +00003765 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003766 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003767 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003768 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003769 << Field->getDeclName()
3770 << FieldType);
3771
Eli Friedman5f2987c2012-02-02 03:46:19 +00003772 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003773 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003774 }
3775
John McCall58e6f342010-03-16 05:22:47 +00003776 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3777
Anders Carlsson9f853df2009-11-17 04:44:12 +00003778 // Bases.
3779 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3780 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003781 // Bases are always records in a well-formed non-dependent class.
3782 const RecordType *RT = Base->getType()->getAs<RecordType>();
3783
3784 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003785 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003786 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003787
John McCall58e6f342010-03-16 05:22:47 +00003788 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003789 // If our base class is invalid, we probably can't get its dtor anyway.
3790 if (BaseClassDecl->isInvalidDecl())
3791 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003792 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003793 continue;
John McCall58e6f342010-03-16 05:22:47 +00003794
Douglas Gregordb89f282010-07-01 22:47:18 +00003795 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003796 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003797
3798 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003799 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003800 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003801 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003802 << Base->getSourceRange(),
3803 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003804
Eli Friedman5f2987c2012-02-02 03:46:19 +00003805 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003806 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003807 }
3808
3809 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003810 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3811 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003812
3813 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003814 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003815
3816 // Ignore direct virtual bases.
3817 if (DirectVirtualBases.count(RT))
3818 continue;
3819
John McCall58e6f342010-03-16 05:22:47 +00003820 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003821 // If our base class is invalid, we probably can't get its dtor anyway.
3822 if (BaseClassDecl->isInvalidDecl())
3823 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003824 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003825 continue;
John McCall58e6f342010-03-16 05:22:47 +00003826
Douglas Gregordb89f282010-07-01 22:47:18 +00003827 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003828 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003829 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003830 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003831 << VBase->getType(),
3832 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003833
Eli Friedman5f2987c2012-02-02 03:46:19 +00003834 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003835 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003836 }
3837}
3838
John McCalld226f652010-08-21 09:40:31 +00003839void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003840 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003841 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003842
Mike Stump1eb44332009-09-09 15:08:12 +00003843 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003844 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003845 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003846}
3847
Mike Stump1eb44332009-09-09 15:08:12 +00003848bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003849 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003850 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3851 unsigned DiagID;
3852 AbstractDiagSelID SelID;
3853
3854 public:
3855 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3856 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3857
3858 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003859 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003860 if (SelID == -1)
3861 S.Diag(Loc, DiagID) << T;
3862 else
3863 S.Diag(Loc, DiagID) << SelID << T;
3864 }
3865 } Diagnoser(DiagID, SelID);
3866
3867 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003868}
3869
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003870bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003871 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003872 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003873 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003874
Anders Carlsson11f21a02009-03-23 19:10:31 +00003875 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003876 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003877
Ted Kremenek6217b802009-07-29 21:53:49 +00003878 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003879 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003880 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003881 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003882
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003883 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003884 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003885 }
Mike Stump1eb44332009-09-09 15:08:12 +00003886
Ted Kremenek6217b802009-07-29 21:53:49 +00003887 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003888 if (!RT)
3889 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003890
John McCall86ff3082010-02-04 22:26:26 +00003891 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003892
John McCall94c3b562010-08-18 09:41:07 +00003893 // We can't answer whether something is abstract until it has a
3894 // definition. If it's currently being defined, we'll walk back
3895 // over all the declarations when we have a full definition.
3896 const CXXRecordDecl *Def = RD->getDefinition();
3897 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003898 return false;
3899
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003900 if (!RD->isAbstract())
3901 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003902
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003903 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003904 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003905
John McCall94c3b562010-08-18 09:41:07 +00003906 return true;
3907}
3908
3909void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3910 // Check if we've already emitted the list of pure virtual functions
3911 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003912 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003913 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003914
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003915 CXXFinalOverriderMap FinalOverriders;
3916 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003917
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003918 // Keep a set of seen pure methods so we won't diagnose the same method
3919 // more than once.
3920 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3921
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003922 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3923 MEnd = FinalOverriders.end();
3924 M != MEnd;
3925 ++M) {
3926 for (OverridingMethods::iterator SO = M->second.begin(),
3927 SOEnd = M->second.end();
3928 SO != SOEnd; ++SO) {
3929 // C++ [class.abstract]p4:
3930 // A class is abstract if it contains or inherits at least one
3931 // pure virtual function for which the final overrider is pure
3932 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003933
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003934 //
3935 if (SO->second.size() != 1)
3936 continue;
3937
3938 if (!SO->second.front().Method->isPure())
3939 continue;
3940
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003941 if (!SeenPureMethods.insert(SO->second.front().Method))
3942 continue;
3943
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003944 Diag(SO->second.front().Method->getLocation(),
3945 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003946 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003947 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003948 }
3949
3950 if (!PureVirtualClassDiagSet)
3951 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3952 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003953}
3954
Anders Carlsson8211eff2009-03-24 01:19:16 +00003955namespace {
John McCall94c3b562010-08-18 09:41:07 +00003956struct AbstractUsageInfo {
3957 Sema &S;
3958 CXXRecordDecl *Record;
3959 CanQualType AbstractType;
3960 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003961
John McCall94c3b562010-08-18 09:41:07 +00003962 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3963 : S(S), Record(Record),
3964 AbstractType(S.Context.getCanonicalType(
3965 S.Context.getTypeDeclType(Record))),
3966 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003967
John McCall94c3b562010-08-18 09:41:07 +00003968 void DiagnoseAbstractType() {
3969 if (Invalid) return;
3970 S.DiagnoseAbstractType(Record);
3971 Invalid = true;
3972 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003973
John McCall94c3b562010-08-18 09:41:07 +00003974 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3975};
3976
3977struct CheckAbstractUsage {
3978 AbstractUsageInfo &Info;
3979 const NamedDecl *Ctx;
3980
3981 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3982 : Info(Info), Ctx(Ctx) {}
3983
3984 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3985 switch (TL.getTypeLocClass()) {
3986#define ABSTRACT_TYPELOC(CLASS, PARENT)
3987#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003988 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003989#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003990 }
John McCall94c3b562010-08-18 09:41:07 +00003991 }
Mike Stump1eb44332009-09-09 15:08:12 +00003992
John McCall94c3b562010-08-18 09:41:07 +00003993 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3994 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3995 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003996 if (!TL.getArg(I))
3997 continue;
3998
John McCall94c3b562010-08-18 09:41:07 +00003999 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4000 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004001 }
John McCall94c3b562010-08-18 09:41:07 +00004002 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004003
John McCall94c3b562010-08-18 09:41:07 +00004004 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4005 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4006 }
Mike Stump1eb44332009-09-09 15:08:12 +00004007
John McCall94c3b562010-08-18 09:41:07 +00004008 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4009 // Visit the type parameters from a permissive context.
4010 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4011 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4012 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4013 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4014 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4015 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004016 }
John McCall94c3b562010-08-18 09:41:07 +00004017 }
Mike Stump1eb44332009-09-09 15:08:12 +00004018
John McCall94c3b562010-08-18 09:41:07 +00004019 // Visit pointee types from a permissive context.
4020#define CheckPolymorphic(Type) \
4021 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4022 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4023 }
4024 CheckPolymorphic(PointerTypeLoc)
4025 CheckPolymorphic(ReferenceTypeLoc)
4026 CheckPolymorphic(MemberPointerTypeLoc)
4027 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004028 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004029
John McCall94c3b562010-08-18 09:41:07 +00004030 /// Handle all the types we haven't given a more specific
4031 /// implementation for above.
4032 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4033 // Every other kind of type that we haven't called out already
4034 // that has an inner type is either (1) sugar or (2) contains that
4035 // inner type in some way as a subobject.
4036 if (TypeLoc Next = TL.getNextTypeLoc())
4037 return Visit(Next, Sel);
4038
4039 // If there's no inner type and we're in a permissive context,
4040 // don't diagnose.
4041 if (Sel == Sema::AbstractNone) return;
4042
4043 // Check whether the type matches the abstract type.
4044 QualType T = TL.getType();
4045 if (T->isArrayType()) {
4046 Sel = Sema::AbstractArrayType;
4047 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004048 }
John McCall94c3b562010-08-18 09:41:07 +00004049 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4050 if (CT != Info.AbstractType) return;
4051
4052 // It matched; do some magic.
4053 if (Sel == Sema::AbstractArrayType) {
4054 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4055 << T << TL.getSourceRange();
4056 } else {
4057 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4058 << Sel << T << TL.getSourceRange();
4059 }
4060 Info.DiagnoseAbstractType();
4061 }
4062};
4063
4064void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4065 Sema::AbstractDiagSelID Sel) {
4066 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4067}
4068
4069}
4070
4071/// Check for invalid uses of an abstract type in a method declaration.
4072static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4073 CXXMethodDecl *MD) {
4074 // No need to do the check on definitions, which require that
4075 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004076 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004077 return;
4078
4079 // For safety's sake, just ignore it if we don't have type source
4080 // information. This should never happen for non-implicit methods,
4081 // but...
4082 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4083 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4084}
4085
4086/// Check for invalid uses of an abstract type within a class definition.
4087static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4088 CXXRecordDecl *RD) {
4089 for (CXXRecordDecl::decl_iterator
4090 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4091 Decl *D = *I;
4092 if (D->isImplicit()) continue;
4093
4094 // Methods and method templates.
4095 if (isa<CXXMethodDecl>(D)) {
4096 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4097 } else if (isa<FunctionTemplateDecl>(D)) {
4098 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4099 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4100
4101 // Fields and static variables.
4102 } else if (isa<FieldDecl>(D)) {
4103 FieldDecl *FD = cast<FieldDecl>(D);
4104 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4105 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4106 } else if (isa<VarDecl>(D)) {
4107 VarDecl *VD = cast<VarDecl>(D);
4108 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4109 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4110
4111 // Nested classes and class templates.
4112 } else if (isa<CXXRecordDecl>(D)) {
4113 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4114 } else if (isa<ClassTemplateDecl>(D)) {
4115 CheckAbstractClassUsage(Info,
4116 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4117 }
4118 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004119}
4120
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004121/// \brief Perform semantic checks on a class definition that has been
4122/// completing, introducing implicitly-declared members, checking for
4123/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004124void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004125 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004126 return;
4127
John McCall94c3b562010-08-18 09:41:07 +00004128 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4129 AbstractUsageInfo Info(*this, Record);
4130 CheckAbstractClassUsage(Info, Record);
4131 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004132
4133 // If this is not an aggregate type and has no user-declared constructor,
4134 // complain about any non-static data members of reference or const scalar
4135 // type, since they will never get initializers.
4136 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004137 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4138 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004139 bool Complained = false;
4140 for (RecordDecl::field_iterator F = Record->field_begin(),
4141 FEnd = Record->field_end();
4142 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004143 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004144 continue;
4145
Douglas Gregor325e5932010-04-15 00:00:53 +00004146 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004147 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004148 if (!Complained) {
4149 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4150 << Record->getTagKind() << Record;
4151 Complained = true;
4152 }
4153
4154 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4155 << F->getType()->isReferenceType()
4156 << F->getDeclName();
4157 }
4158 }
4159 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004160
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004161 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004162 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004163
4164 if (Record->getIdentifier()) {
4165 // C++ [class.mem]p13:
4166 // If T is the name of a class, then each of the following shall have a
4167 // name different from T:
4168 // - every member of every anonymous union that is a member of class T.
4169 //
4170 // C++ [class.mem]p14:
4171 // In addition, if class T has a user-declared constructor (12.1), every
4172 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004173 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4174 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4175 ++I) {
4176 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004177 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4178 isa<IndirectFieldDecl>(D)) {
4179 Diag(D->getLocation(), diag::err_member_name_of_class)
4180 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004181 break;
4182 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004183 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004184 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004185
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004186 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004187 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004188 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004189 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004190 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4191 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4192 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004193
David Blaikieb6b5b972012-09-21 03:21:07 +00004194 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4195 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4196 DiagnoseAbstractType(Record);
4197 }
4198
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004199 if (!Record->isDependentType()) {
4200 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4201 MEnd = Record->method_end();
4202 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004203 // See if a method overloads virtual methods in a base
4204 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004205 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004206 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004207
4208 // Check whether the explicitly-defaulted special members are valid.
4209 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4210 CheckExplicitlyDefaultedSpecialMember(*M);
4211
4212 // For an explicitly defaulted or deleted special member, we defer
4213 // determining triviality until the class is complete. That time is now!
4214 if (!M->isImplicit() && !M->isUserProvided()) {
4215 CXXSpecialMember CSM = getSpecialMember(*M);
4216 if (CSM != CXXInvalid) {
4217 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4218
4219 // Inform the class that we've finished declaring this member.
4220 Record->finishedDefaultedOrDeletedMember(*M);
4221 }
4222 }
4223 }
4224 }
4225
4226 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4227 // function that is not a constructor declares that member function to be
4228 // const. [...] The class of which that function is a member shall be
4229 // a literal type.
4230 //
4231 // If the class has virtual bases, any constexpr members will already have
4232 // been diagnosed by the checks performed on the member declaration, so
4233 // suppress this (less useful) diagnostic.
4234 //
4235 // We delay this until we know whether an explicitly-defaulted (or deleted)
4236 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004237 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004238 !Record->isLiteral() && !Record->getNumVBases()) {
4239 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4240 MEnd = Record->method_end();
4241 M != MEnd; ++M) {
4242 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4243 switch (Record->getTemplateSpecializationKind()) {
4244 case TSK_ImplicitInstantiation:
4245 case TSK_ExplicitInstantiationDeclaration:
4246 case TSK_ExplicitInstantiationDefinition:
4247 // If a template instantiates to a non-literal type, but its members
4248 // instantiate to constexpr functions, the template is technically
4249 // ill-formed, but we allow it for sanity.
4250 continue;
4251
4252 case TSK_Undeclared:
4253 case TSK_ExplicitSpecialization:
4254 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4255 diag::err_constexpr_method_non_literal);
4256 break;
4257 }
4258
4259 // Only produce one error per class.
4260 break;
4261 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004262 }
4263 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004264
Richard Smith07b0fdc2013-03-18 21:12:30 +00004265 // Declare inheriting constructors. We do this eagerly here because:
4266 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004267 // constructors from different classes.
4268 // - The lazy declaration of the other implicit constructors is so as to not
4269 // waste space and performance on classes that are not meant to be
4270 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004271 // have inheriting constructors.
4272 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004273}
4274
Richard Smith7756afa2012-06-10 05:43:50 +00004275/// Is the special member function which would be selected to perform the
4276/// specified operation on the specified class type a constexpr constructor?
4277static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4278 Sema::CXXSpecialMember CSM,
4279 bool ConstArg) {
4280 Sema::SpecialMemberOverloadResult *SMOR =
4281 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4282 false, false, false, false);
4283 if (!SMOR || !SMOR->getMethod())
4284 // A constructor we wouldn't select can't be "involved in initializing"
4285 // anything.
4286 return true;
4287 return SMOR->getMethod()->isConstexpr();
4288}
4289
4290/// Determine whether the specified special member function would be constexpr
4291/// if it were implicitly defined.
4292static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4293 Sema::CXXSpecialMember CSM,
4294 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004295 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004296 return false;
4297
4298 // C++11 [dcl.constexpr]p4:
4299 // In the definition of a constexpr constructor [...]
4300 switch (CSM) {
4301 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004302 // Since default constructor lookup is essentially trivial (and cannot
4303 // involve, for instance, template instantiation), we compute whether a
4304 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4305 //
4306 // This is important for performance; we need to know whether the default
4307 // constructor is constexpr to determine whether the type is a literal type.
4308 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4309
Richard Smith7756afa2012-06-10 05:43:50 +00004310 case Sema::CXXCopyConstructor:
4311 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004312 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004313 break;
4314
4315 case Sema::CXXCopyAssignment:
4316 case Sema::CXXMoveAssignment:
4317 case Sema::CXXDestructor:
4318 case Sema::CXXInvalid:
4319 return false;
4320 }
4321
4322 // -- if the class is a non-empty union, or for each non-empty anonymous
4323 // union member of a non-union class, exactly one non-static data member
4324 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004325 //
4326 // If we squint, this is guaranteed, since exactly one non-static data member
4327 // will be initialized (if the constructor isn't deleted), we just don't know
4328 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004329 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004330 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004331
4332 // -- the class shall not have any virtual base classes;
4333 if (ClassDecl->getNumVBases())
4334 return false;
4335
4336 // -- every constructor involved in initializing [...] base class
4337 // sub-objects shall be a constexpr constructor;
4338 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4339 BEnd = ClassDecl->bases_end();
4340 B != BEnd; ++B) {
4341 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4342 if (!BaseType) continue;
4343
4344 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4345 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4346 return false;
4347 }
4348
4349 // -- every constructor involved in initializing non-static data members
4350 // [...] shall be a constexpr constructor;
4351 // -- every non-static data member and base class sub-object shall be
4352 // initialized
4353 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4354 FEnd = ClassDecl->field_end();
4355 F != FEnd; ++F) {
4356 if (F->isInvalidDecl())
4357 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004358 if (const RecordType *RecordTy =
4359 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004360 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4361 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4362 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004363 }
4364 }
4365
4366 // All OK, it's constexpr!
4367 return true;
4368}
4369
Richard Smithb9d0b762012-07-27 04:22:15 +00004370static Sema::ImplicitExceptionSpecification
4371computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4372 switch (S.getSpecialMember(MD)) {
4373 case Sema::CXXDefaultConstructor:
4374 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4375 case Sema::CXXCopyConstructor:
4376 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4377 case Sema::CXXCopyAssignment:
4378 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4379 case Sema::CXXMoveConstructor:
4380 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4381 case Sema::CXXMoveAssignment:
4382 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4383 case Sema::CXXDestructor:
4384 return S.ComputeDefaultedDtorExceptionSpec(MD);
4385 case Sema::CXXInvalid:
4386 break;
4387 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004388 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4389 "only special members have implicit exception specs");
4390 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004391}
4392
Richard Smithdd25e802012-07-30 23:48:14 +00004393static void
4394updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4395 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4396 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4397 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004398 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4399 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004400}
4401
Richard Smithb9d0b762012-07-27 04:22:15 +00004402void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4403 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4404 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4405 return;
4406
Richard Smithdd25e802012-07-30 23:48:14 +00004407 // Evaluate the exception specification.
4408 ImplicitExceptionSpecification ExceptSpec =
4409 computeImplicitExceptionSpec(*this, Loc, MD);
4410
4411 // Update the type of the special member to use it.
4412 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4413
4414 // A user-provided destructor can be defined outside the class. When that
4415 // happens, be sure to update the exception specification on both
4416 // declarations.
4417 const FunctionProtoType *CanonicalFPT =
4418 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4419 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4420 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4421 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004422}
4423
Richard Smith3003e1d2012-05-15 04:39:51 +00004424void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4425 CXXRecordDecl *RD = MD->getParent();
4426 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004427
Richard Smith3003e1d2012-05-15 04:39:51 +00004428 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4429 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004430
4431 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004432 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004433 bool First = MD == MD->getCanonicalDecl();
4434
4435 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004436
4437 // C++11 [dcl.fct.def.default]p1:
4438 // A function that is explicitly defaulted shall
4439 // -- be a special member function (checked elsewhere),
4440 // -- have the same type (except for ref-qualifiers, and except that a
4441 // copy operation can take a non-const reference) as an implicit
4442 // declaration, and
4443 // -- not have default arguments.
4444 unsigned ExpectedParams = 1;
4445 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4446 ExpectedParams = 0;
4447 if (MD->getNumParams() != ExpectedParams) {
4448 // This also checks for default arguments: a copy or move constructor with a
4449 // default argument is classified as a default constructor, and assignment
4450 // operations and destructors can't have default arguments.
4451 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4452 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004453 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004454 } else if (MD->isVariadic()) {
4455 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4456 << CSM << MD->getSourceRange();
4457 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004458 }
4459
Richard Smith3003e1d2012-05-15 04:39:51 +00004460 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004461
Richard Smith7756afa2012-06-10 05:43:50 +00004462 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004463 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004464 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004465 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004466 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004467
Richard Smith3003e1d2012-05-15 04:39:51 +00004468 QualType ReturnType = Context.VoidTy;
4469 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4470 // Check for return type matching.
4471 ReturnType = Type->getResultType();
4472 QualType ExpectedReturnType =
4473 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4474 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4475 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4476 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4477 HadError = true;
4478 }
4479
4480 // A defaulted special member cannot have cv-qualifiers.
4481 if (Type->getTypeQuals()) {
4482 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4483 << (CSM == CXXMoveAssignment);
4484 HadError = true;
4485 }
4486 }
4487
4488 // Check for parameter type matching.
4489 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004490 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004491 if (ExpectedParams && ArgType->isReferenceType()) {
4492 // Argument must be reference to possibly-const T.
4493 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004494 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004495
4496 if (ReferentType.isVolatileQualified()) {
4497 Diag(MD->getLocation(),
4498 diag::err_defaulted_special_member_volatile_param) << CSM;
4499 HadError = true;
4500 }
4501
Richard Smith7756afa2012-06-10 05:43:50 +00004502 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004503 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4504 Diag(MD->getLocation(),
4505 diag::err_defaulted_special_member_copy_const_param)
4506 << (CSM == CXXCopyAssignment);
4507 // FIXME: Explain why this special member can't be const.
4508 } else {
4509 Diag(MD->getLocation(),
4510 diag::err_defaulted_special_member_move_const_param)
4511 << (CSM == CXXMoveAssignment);
4512 }
4513 HadError = true;
4514 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004515 } else if (ExpectedParams) {
4516 // A copy assignment operator can take its argument by value, but a
4517 // defaulted one cannot.
4518 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004519 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004520 HadError = true;
4521 }
Sean Huntbe631222011-05-17 20:44:43 +00004522
Richard Smith61802452011-12-22 02:22:31 +00004523 // C++11 [dcl.fct.def.default]p2:
4524 // An explicitly-defaulted function may be declared constexpr only if it
4525 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004526 // Do not apply this rule to members of class templates, since core issue 1358
4527 // makes such functions always instantiate to constexpr functions. For
4528 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004529 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4530 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004531 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4532 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4533 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004534 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004535 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004536 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004537
Richard Smith61802452011-12-22 02:22:31 +00004538 // and may have an explicit exception-specification only if it is compatible
4539 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004540 if (Type->hasExceptionSpec()) {
4541 // Delay the check if this is the first declaration of the special member,
4542 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004543 if (First) {
4544 // If the exception specification needs to be instantiated, do so now,
4545 // before we clobber it with an EST_Unevaluated specification below.
4546 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4547 InstantiateExceptionSpec(MD->getLocStart(), MD);
4548 Type = MD->getType()->getAs<FunctionProtoType>();
4549 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004550 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004551 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004552 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4553 }
Richard Smith61802452011-12-22 02:22:31 +00004554
4555 // If a function is explicitly defaulted on its first declaration,
4556 if (First) {
4557 // -- it is implicitly considered to be constexpr if the implicit
4558 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004559 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004560
Richard Smith3003e1d2012-05-15 04:39:51 +00004561 // -- it is implicitly considered to have the same exception-specification
4562 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004563 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4564 EPI.ExceptionSpecType = EST_Unevaluated;
4565 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004566 MD->setType(Context.getFunctionType(ReturnType,
4567 ArrayRef<QualType>(&ArgType,
4568 ExpectedParams),
4569 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004570 }
4571
Richard Smith3003e1d2012-05-15 04:39:51 +00004572 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004573 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004574 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004575 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004576 // C++11 [dcl.fct.def.default]p4:
4577 // [For a] user-provided explicitly-defaulted function [...] if such a
4578 // function is implicitly defined as deleted, the program is ill-formed.
4579 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4580 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004581 }
4582 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004583
Richard Smith3003e1d2012-05-15 04:39:51 +00004584 if (HadError)
4585 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004586}
4587
Richard Smith1d28caf2012-12-11 01:14:52 +00004588/// Check whether the exception specification provided for an
4589/// explicitly-defaulted special member matches the exception specification
4590/// that would have been generated for an implicit special member, per
4591/// C++11 [dcl.fct.def.default]p2.
4592void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4593 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4594 // Compute the implicit exception specification.
4595 FunctionProtoType::ExtProtoInfo EPI;
4596 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4597 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Jordan Rosebea522f2013-03-08 21:51:21 +00004598 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004599
4600 // Ensure that it matches.
4601 CheckEquivalentExceptionSpec(
4602 PDiag(diag::err_incorrect_defaulted_exception_spec)
4603 << getSpecialMember(MD), PDiag(),
4604 ImplicitType, SourceLocation(),
4605 SpecifiedType, MD->getLocation());
4606}
4607
4608void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4609 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4610 I != N; ++I)
4611 CheckExplicitlyDefaultedMemberExceptionSpec(
4612 DelayedDefaultedMemberExceptionSpecs[I].first,
4613 DelayedDefaultedMemberExceptionSpecs[I].second);
4614
4615 DelayedDefaultedMemberExceptionSpecs.clear();
4616}
4617
Richard Smith7d5088a2012-02-18 02:02:13 +00004618namespace {
4619struct SpecialMemberDeletionInfo {
4620 Sema &S;
4621 CXXMethodDecl *MD;
4622 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004623 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004624
4625 // Properties of the special member, computed for convenience.
4626 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4627 SourceLocation Loc;
4628
4629 bool AllFieldsAreConst;
4630
4631 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004632 Sema::CXXSpecialMember CSM, bool Diagnose)
4633 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004634 IsConstructor(false), IsAssignment(false), IsMove(false),
4635 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4636 AllFieldsAreConst(true) {
4637 switch (CSM) {
4638 case Sema::CXXDefaultConstructor:
4639 case Sema::CXXCopyConstructor:
4640 IsConstructor = true;
4641 break;
4642 case Sema::CXXMoveConstructor:
4643 IsConstructor = true;
4644 IsMove = true;
4645 break;
4646 case Sema::CXXCopyAssignment:
4647 IsAssignment = true;
4648 break;
4649 case Sema::CXXMoveAssignment:
4650 IsAssignment = true;
4651 IsMove = true;
4652 break;
4653 case Sema::CXXDestructor:
4654 break;
4655 case Sema::CXXInvalid:
4656 llvm_unreachable("invalid special member kind");
4657 }
4658
4659 if (MD->getNumParams()) {
4660 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4661 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4662 }
4663 }
4664
4665 bool inUnion() const { return MD->getParent()->isUnion(); }
4666
4667 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004668 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4669 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004670 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004671 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4672 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4673 Quals = 0;
4674 return S.LookupSpecialMember(Class, CSM,
4675 ConstArg || (Quals & Qualifiers::Const),
4676 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004677 MD->getRefQualifier() == RQ_RValue,
4678 TQ & Qualifiers::Const,
4679 TQ & Qualifiers::Volatile);
4680 }
4681
Richard Smith6c4c36c2012-03-30 20:53:28 +00004682 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004683
Richard Smith6c4c36c2012-03-30 20:53:28 +00004684 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004685 bool shouldDeleteForField(FieldDecl *FD);
4686 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004687
Richard Smith517bb842012-07-18 03:51:16 +00004688 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4689 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004690 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4691 Sema::SpecialMemberOverloadResult *SMOR,
4692 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004693
4694 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004695};
4696}
4697
John McCall12d8d802012-04-09 20:53:23 +00004698/// Is the given special member inaccessible when used on the given
4699/// sub-object.
4700bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4701 CXXMethodDecl *target) {
4702 /// If we're operating on a base class, the object type is the
4703 /// type of this special member.
4704 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004705 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004706 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4707 objectTy = S.Context.getTypeDeclType(MD->getParent());
4708 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4709
4710 // If we're operating on a field, the object type is the type of the field.
4711 } else {
4712 objectTy = S.Context.getTypeDeclType(target->getParent());
4713 }
4714
4715 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4716}
4717
Richard Smith6c4c36c2012-03-30 20:53:28 +00004718/// Check whether we should delete a special member due to the implicit
4719/// definition containing a call to a special member of a subobject.
4720bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4721 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4722 bool IsDtorCallInCtor) {
4723 CXXMethodDecl *Decl = SMOR->getMethod();
4724 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4725
4726 int DiagKind = -1;
4727
4728 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4729 DiagKind = !Decl ? 0 : 1;
4730 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4731 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004732 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004733 DiagKind = 3;
4734 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4735 !Decl->isTrivial()) {
4736 // A member of a union must have a trivial corresponding special member.
4737 // As a weird special case, a destructor call from a union's constructor
4738 // must be accessible and non-deleted, but need not be trivial. Such a
4739 // destructor is never actually called, but is semantically checked as
4740 // if it were.
4741 DiagKind = 4;
4742 }
4743
4744 if (DiagKind == -1)
4745 return false;
4746
4747 if (Diagnose) {
4748 if (Field) {
4749 S.Diag(Field->getLocation(),
4750 diag::note_deleted_special_member_class_subobject)
4751 << CSM << MD->getParent() << /*IsField*/true
4752 << Field << DiagKind << IsDtorCallInCtor;
4753 } else {
4754 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4755 S.Diag(Base->getLocStart(),
4756 diag::note_deleted_special_member_class_subobject)
4757 << CSM << MD->getParent() << /*IsField*/false
4758 << Base->getType() << DiagKind << IsDtorCallInCtor;
4759 }
4760
4761 if (DiagKind == 1)
4762 S.NoteDeletedFunction(Decl);
4763 // FIXME: Explain inaccessibility if DiagKind == 3.
4764 }
4765
4766 return true;
4767}
4768
Richard Smith9a561d52012-02-26 09:11:52 +00004769/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004770/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004771bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004772 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004773 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004774
4775 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004776 // -- any direct or virtual base class, or non-static data member with no
4777 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004778 // either M has no default constructor or overload resolution as applied
4779 // to M's default constructor results in an ambiguity or in a function
4780 // that is deleted or inaccessible
4781 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4782 // -- a direct or virtual base class B that cannot be copied/moved because
4783 // overload resolution, as applied to B's corresponding special member,
4784 // results in an ambiguity or a function that is deleted or inaccessible
4785 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004786 // C++11 [class.dtor]p5:
4787 // -- any direct or virtual base class [...] has a type with a destructor
4788 // that is deleted or inaccessible
4789 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004790 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004791 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004792 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004793
Richard Smith6c4c36c2012-03-30 20:53:28 +00004794 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4795 // -- any direct or virtual base class or non-static data member has a
4796 // type with a destructor that is deleted or inaccessible
4797 if (IsConstructor) {
4798 Sema::SpecialMemberOverloadResult *SMOR =
4799 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4800 false, false, false, false, false);
4801 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4802 return true;
4803 }
4804
Richard Smith9a561d52012-02-26 09:11:52 +00004805 return false;
4806}
4807
4808/// Check whether we should delete a special member function due to the class
4809/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004810bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004811 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004812 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004813}
4814
4815/// Check whether we should delete a special member function due to the class
4816/// having a particular non-static data member.
4817bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4818 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4819 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4820
4821 if (CSM == Sema::CXXDefaultConstructor) {
4822 // For a default constructor, all references must be initialized in-class
4823 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004824 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4825 if (Diagnose)
4826 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4827 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004828 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004829 }
Richard Smith79363f52012-02-27 06:07:25 +00004830 // C++11 [class.ctor]p5: any non-variant non-static data member of
4831 // const-qualified type (or array thereof) with no
4832 // brace-or-equal-initializer does not have a user-provided default
4833 // constructor.
4834 if (!inUnion() && FieldType.isConstQualified() &&
4835 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004836 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4837 if (Diagnose)
4838 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004839 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004840 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004841 }
4842
4843 if (inUnion() && !FieldType.isConstQualified())
4844 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004845 } else if (CSM == Sema::CXXCopyConstructor) {
4846 // For a copy constructor, data members must not be of rvalue reference
4847 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004848 if (FieldType->isRValueReferenceType()) {
4849 if (Diagnose)
4850 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4851 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004852 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004853 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004854 } else if (IsAssignment) {
4855 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004856 if (FieldType->isReferenceType()) {
4857 if (Diagnose)
4858 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4859 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004860 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004861 }
4862 if (!FieldRecord && FieldType.isConstQualified()) {
4863 // C++11 [class.copy]p23:
4864 // -- a non-static data member of const non-class type (or array thereof)
4865 if (Diagnose)
4866 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004867 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004868 return true;
4869 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004870 }
4871
4872 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004873 // Some additional restrictions exist on the variant members.
4874 if (!inUnion() && FieldRecord->isUnion() &&
4875 FieldRecord->isAnonymousStructOrUnion()) {
4876 bool AllVariantFieldsAreConst = true;
4877
Richard Smithdf8dc862012-03-29 19:00:10 +00004878 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004879 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4880 UE = FieldRecord->field_end();
4881 UI != UE; ++UI) {
4882 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004883
4884 if (!UnionFieldType.isConstQualified())
4885 AllVariantFieldsAreConst = false;
4886
Richard Smith9a561d52012-02-26 09:11:52 +00004887 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4888 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004889 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4890 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004891 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004892 }
4893
4894 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004895 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004896 FieldRecord->field_begin() != FieldRecord->field_end()) {
4897 if (Diagnose)
4898 S.Diag(FieldRecord->getLocation(),
4899 diag::note_deleted_default_ctor_all_const)
4900 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004901 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004902 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004903
Richard Smithdf8dc862012-03-29 19:00:10 +00004904 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004905 // This is technically non-conformant, but sanity demands it.
4906 return false;
4907 }
4908
Richard Smith517bb842012-07-18 03:51:16 +00004909 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4910 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004911 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004912 }
4913
4914 return false;
4915}
4916
4917/// C++11 [class.ctor] p5:
4918/// A defaulted default constructor for a class X is defined as deleted if
4919/// X is a union and all of its variant members are of const-qualified type.
4920bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004921 // This is a silly definition, because it gives an empty union a deleted
4922 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004923 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4924 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4925 if (Diagnose)
4926 S.Diag(MD->getParent()->getLocation(),
4927 diag::note_deleted_default_ctor_all_const)
4928 << MD->getParent() << /*not anonymous union*/0;
4929 return true;
4930 }
4931 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004932}
4933
4934/// Determine whether a defaulted special member function should be defined as
4935/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4936/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004937bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4938 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004939 if (MD->isInvalidDecl())
4940 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004941 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004942 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004943 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004944 return false;
4945
Richard Smith7d5088a2012-02-18 02:02:13 +00004946 // C++11 [expr.lambda.prim]p19:
4947 // The closure type associated with a lambda-expression has a
4948 // deleted (8.4.3) default constructor and a deleted copy
4949 // assignment operator.
4950 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004951 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4952 if (Diagnose)
4953 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004954 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004955 }
4956
Richard Smith5bdaac52012-04-02 20:59:25 +00004957 // For an anonymous struct or union, the copy and assignment special members
4958 // will never be used, so skip the check. For an anonymous union declared at
4959 // namespace scope, the constructor and destructor are used.
4960 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4961 RD->isAnonymousStructOrUnion())
4962 return false;
4963
Richard Smith6c4c36c2012-03-30 20:53:28 +00004964 // C++11 [class.copy]p7, p18:
4965 // If the class definition declares a move constructor or move assignment
4966 // operator, an implicitly declared copy constructor or copy assignment
4967 // operator is defined as deleted.
4968 if (MD->isImplicit() &&
4969 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4970 CXXMethodDecl *UserDeclaredMove = 0;
4971
4972 // In Microsoft mode, a user-declared move only causes the deletion of the
4973 // corresponding copy operation, not both copy operations.
4974 if (RD->hasUserDeclaredMoveConstructor() &&
4975 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4976 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004977
4978 // Find any user-declared move constructor.
4979 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4980 E = RD->ctor_end(); I != E; ++I) {
4981 if (I->isMoveConstructor()) {
4982 UserDeclaredMove = *I;
4983 break;
4984 }
4985 }
Richard Smith1c931be2012-04-02 18:40:40 +00004986 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004987 } else if (RD->hasUserDeclaredMoveAssignment() &&
4988 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4989 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004990
4991 // Find any user-declared move assignment operator.
4992 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4993 E = RD->method_end(); I != E; ++I) {
4994 if (I->isMoveAssignmentOperator()) {
4995 UserDeclaredMove = *I;
4996 break;
4997 }
4998 }
Richard Smith1c931be2012-04-02 18:40:40 +00004999 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005000 }
5001
5002 if (UserDeclaredMove) {
5003 Diag(UserDeclaredMove->getLocation(),
5004 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005005 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005006 << UserDeclaredMove->isMoveAssignmentOperator();
5007 return true;
5008 }
5009 }
Sean Hunte16da072011-10-10 06:18:57 +00005010
Richard Smith5bdaac52012-04-02 20:59:25 +00005011 // Do access control from the special member function
5012 ContextRAII MethodContext(*this, MD);
5013
Richard Smith9a561d52012-02-26 09:11:52 +00005014 // C++11 [class.dtor]p5:
5015 // -- for a virtual destructor, lookup of the non-array deallocation function
5016 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005017 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005018 FunctionDecl *OperatorDelete = 0;
5019 DeclarationName Name =
5020 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5021 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005022 OperatorDelete, false)) {
5023 if (Diagnose)
5024 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005025 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005026 }
Richard Smith9a561d52012-02-26 09:11:52 +00005027 }
5028
Richard Smith6c4c36c2012-03-30 20:53:28 +00005029 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005030
Sean Huntcdee3fe2011-05-11 22:34:38 +00005031 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005032 BE = RD->bases_end(); BI != BE; ++BI)
5033 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005034 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005035 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005036
5037 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005038 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00005039 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005040 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005041
5042 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005043 FE = RD->field_end(); FI != FE; ++FI)
5044 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005045 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005046 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005047
Richard Smith7d5088a2012-02-18 02:02:13 +00005048 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005049 return true;
5050
5051 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005052}
5053
Richard Smithac713512012-12-08 02:53:02 +00005054/// Perform lookup for a special member of the specified kind, and determine
5055/// whether it is trivial. If the triviality can be determined without the
5056/// lookup, skip it. This is intended for use when determining whether a
5057/// special member of a containing object is trivial, and thus does not ever
5058/// perform overload resolution for default constructors.
5059///
5060/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5061/// member that was most likely to be intended to be trivial, if any.
5062static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5063 Sema::CXXSpecialMember CSM, unsigned Quals,
5064 CXXMethodDecl **Selected) {
5065 if (Selected)
5066 *Selected = 0;
5067
5068 switch (CSM) {
5069 case Sema::CXXInvalid:
5070 llvm_unreachable("not a special member");
5071
5072 case Sema::CXXDefaultConstructor:
5073 // C++11 [class.ctor]p5:
5074 // A default constructor is trivial if:
5075 // - all the [direct subobjects] have trivial default constructors
5076 //
5077 // Note, no overload resolution is performed in this case.
5078 if (RD->hasTrivialDefaultConstructor())
5079 return true;
5080
5081 if (Selected) {
5082 // If there's a default constructor which could have been trivial, dig it
5083 // out. Otherwise, if there's any user-provided default constructor, point
5084 // to that as an example of why there's not a trivial one.
5085 CXXConstructorDecl *DefCtor = 0;
5086 if (RD->needsImplicitDefaultConstructor())
5087 S.DeclareImplicitDefaultConstructor(RD);
5088 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5089 CE = RD->ctor_end(); CI != CE; ++CI) {
5090 if (!CI->isDefaultConstructor())
5091 continue;
5092 DefCtor = *CI;
5093 if (!DefCtor->isUserProvided())
5094 break;
5095 }
5096
5097 *Selected = DefCtor;
5098 }
5099
5100 return false;
5101
5102 case Sema::CXXDestructor:
5103 // C++11 [class.dtor]p5:
5104 // A destructor is trivial if:
5105 // - all the direct [subobjects] have trivial destructors
5106 if (RD->hasTrivialDestructor())
5107 return true;
5108
5109 if (Selected) {
5110 if (RD->needsImplicitDestructor())
5111 S.DeclareImplicitDestructor(RD);
5112 *Selected = RD->getDestructor();
5113 }
5114
5115 return false;
5116
5117 case Sema::CXXCopyConstructor:
5118 // C++11 [class.copy]p12:
5119 // A copy constructor is trivial if:
5120 // - the constructor selected to copy each direct [subobject] is trivial
5121 if (RD->hasTrivialCopyConstructor()) {
5122 if (Quals == Qualifiers::Const)
5123 // We must either select the trivial copy constructor or reach an
5124 // ambiguity; no need to actually perform overload resolution.
5125 return true;
5126 } else if (!Selected) {
5127 return false;
5128 }
5129 // In C++98, we are not supposed to perform overload resolution here, but we
5130 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5131 // cases like B as having a non-trivial copy constructor:
5132 // struct A { template<typename T> A(T&); };
5133 // struct B { mutable A a; };
5134 goto NeedOverloadResolution;
5135
5136 case Sema::CXXCopyAssignment:
5137 // C++11 [class.copy]p25:
5138 // A copy assignment operator is trivial if:
5139 // - the assignment operator selected to copy each direct [subobject] is
5140 // trivial
5141 if (RD->hasTrivialCopyAssignment()) {
5142 if (Quals == Qualifiers::Const)
5143 return true;
5144 } else if (!Selected) {
5145 return false;
5146 }
5147 // In C++98, we are not supposed to perform overload resolution here, but we
5148 // treat that as a language defect.
5149 goto NeedOverloadResolution;
5150
5151 case Sema::CXXMoveConstructor:
5152 case Sema::CXXMoveAssignment:
5153 NeedOverloadResolution:
5154 Sema::SpecialMemberOverloadResult *SMOR =
5155 S.LookupSpecialMember(RD, CSM,
5156 Quals & Qualifiers::Const,
5157 Quals & Qualifiers::Volatile,
5158 /*RValueThis*/false, /*ConstThis*/false,
5159 /*VolatileThis*/false);
5160
5161 // The standard doesn't describe how to behave if the lookup is ambiguous.
5162 // We treat it as not making the member non-trivial, just like the standard
5163 // mandates for the default constructor. This should rarely matter, because
5164 // the member will also be deleted.
5165 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5166 return true;
5167
5168 if (!SMOR->getMethod()) {
5169 assert(SMOR->getKind() ==
5170 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5171 return false;
5172 }
5173
5174 // We deliberately don't check if we found a deleted special member. We're
5175 // not supposed to!
5176 if (Selected)
5177 *Selected = SMOR->getMethod();
5178 return SMOR->getMethod()->isTrivial();
5179 }
5180
5181 llvm_unreachable("unknown special method kind");
5182}
5183
Benjamin Kramera574c892013-02-15 12:30:38 +00005184static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005185 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5186 CI != CE; ++CI)
5187 if (!CI->isImplicit())
5188 return *CI;
5189
5190 // Look for constructor templates.
5191 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5192 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5193 if (CXXConstructorDecl *CD =
5194 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5195 return CD;
5196 }
5197
5198 return 0;
5199}
5200
5201/// The kind of subobject we are checking for triviality. The values of this
5202/// enumeration are used in diagnostics.
5203enum TrivialSubobjectKind {
5204 /// The subobject is a base class.
5205 TSK_BaseClass,
5206 /// The subobject is a non-static data member.
5207 TSK_Field,
5208 /// The object is actually the complete object.
5209 TSK_CompleteObject
5210};
5211
5212/// Check whether the special member selected for a given type would be trivial.
5213static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5214 QualType SubType,
5215 Sema::CXXSpecialMember CSM,
5216 TrivialSubobjectKind Kind,
5217 bool Diagnose) {
5218 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5219 if (!SubRD)
5220 return true;
5221
5222 CXXMethodDecl *Selected;
5223 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5224 Diagnose ? &Selected : 0))
5225 return true;
5226
5227 if (Diagnose) {
5228 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5229 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5230 << Kind << SubType.getUnqualifiedType();
5231 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5232 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5233 } else if (!Selected)
5234 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5235 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5236 else if (Selected->isUserProvided()) {
5237 if (Kind == TSK_CompleteObject)
5238 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5239 << Kind << SubType.getUnqualifiedType() << CSM;
5240 else {
5241 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5242 << Kind << SubType.getUnqualifiedType() << CSM;
5243 S.Diag(Selected->getLocation(), diag::note_declared_at);
5244 }
5245 } else {
5246 if (Kind != TSK_CompleteObject)
5247 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5248 << Kind << SubType.getUnqualifiedType() << CSM;
5249
5250 // Explain why the defaulted or deleted special member isn't trivial.
5251 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5252 }
5253 }
5254
5255 return false;
5256}
5257
5258/// Check whether the members of a class type allow a special member to be
5259/// trivial.
5260static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5261 Sema::CXXSpecialMember CSM,
5262 bool ConstArg, bool Diagnose) {
5263 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5264 FE = RD->field_end(); FI != FE; ++FI) {
5265 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5266 continue;
5267
5268 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5269
5270 // Pretend anonymous struct or union members are members of this class.
5271 if (FI->isAnonymousStructOrUnion()) {
5272 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5273 CSM, ConstArg, Diagnose))
5274 return false;
5275 continue;
5276 }
5277
5278 // C++11 [class.ctor]p5:
5279 // A default constructor is trivial if [...]
5280 // -- no non-static data member of its class has a
5281 // brace-or-equal-initializer
5282 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5283 if (Diagnose)
5284 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5285 return false;
5286 }
5287
5288 // Objective C ARC 4.3.5:
5289 // [...] nontrivally ownership-qualified types are [...] not trivially
5290 // default constructible, copy constructible, move constructible, copy
5291 // assignable, move assignable, or destructible [...]
5292 if (S.getLangOpts().ObjCAutoRefCount &&
5293 FieldType.hasNonTrivialObjCLifetime()) {
5294 if (Diagnose)
5295 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5296 << RD << FieldType.getObjCLifetime();
5297 return false;
5298 }
5299
5300 if (ConstArg && !FI->isMutable())
5301 FieldType.addConst();
5302 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5303 TSK_Field, Diagnose))
5304 return false;
5305 }
5306
5307 return true;
5308}
5309
5310/// Diagnose why the specified class does not have a trivial special member of
5311/// the given kind.
5312void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5313 QualType Ty = Context.getRecordType(RD);
5314 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5315 Ty.addConst();
5316
5317 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5318 TSK_CompleteObject, /*Diagnose*/true);
5319}
5320
5321/// Determine whether a defaulted or deleted special member function is trivial,
5322/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5323/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5324bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5325 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005326 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5327
5328 CXXRecordDecl *RD = MD->getParent();
5329
5330 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005331
5332 // C++11 [class.copy]p12, p25:
5333 // A [special member] is trivial if its declared parameter type is the same
5334 // as if it had been implicitly declared [...]
5335 switch (CSM) {
5336 case CXXDefaultConstructor:
5337 case CXXDestructor:
5338 // Trivial default constructors and destructors cannot have parameters.
5339 break;
5340
5341 case CXXCopyConstructor:
5342 case CXXCopyAssignment: {
5343 // Trivial copy operations always have const, non-volatile parameter types.
5344 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005345 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005346 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5347 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5348 if (Diagnose)
5349 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5350 << Param0->getSourceRange() << Param0->getType()
5351 << Context.getLValueReferenceType(
5352 Context.getRecordType(RD).withConst());
5353 return false;
5354 }
5355 break;
5356 }
5357
5358 case CXXMoveConstructor:
5359 case CXXMoveAssignment: {
5360 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005361 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005362 const RValueReferenceType *RT =
5363 Param0->getType()->getAs<RValueReferenceType>();
5364 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5365 if (Diagnose)
5366 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5367 << Param0->getSourceRange() << Param0->getType()
5368 << Context.getRValueReferenceType(Context.getRecordType(RD));
5369 return false;
5370 }
5371 break;
5372 }
5373
5374 case CXXInvalid:
5375 llvm_unreachable("not a special member");
5376 }
5377
5378 // FIXME: We require that the parameter-declaration-clause is equivalent to
5379 // that of an implicit declaration, not just that the declared parameter type
5380 // matches, in order to prevent absuridities like a function simultaneously
5381 // being a trivial copy constructor and a non-trivial default constructor.
5382 // This issue has not yet been assigned a core issue number.
5383 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5384 if (Diagnose)
5385 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5386 diag::note_nontrivial_default_arg)
5387 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5388 return false;
5389 }
5390 if (MD->isVariadic()) {
5391 if (Diagnose)
5392 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5393 return false;
5394 }
5395
5396 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5397 // A copy/move [constructor or assignment operator] is trivial if
5398 // -- the [member] selected to copy/move each direct base class subobject
5399 // is trivial
5400 //
5401 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5402 // A [default constructor or destructor] is trivial if
5403 // -- all the direct base classes have trivial [default constructors or
5404 // destructors]
5405 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5406 BE = RD->bases_end(); BI != BE; ++BI)
5407 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5408 ConstArg ? BI->getType().withConst()
5409 : BI->getType(),
5410 CSM, TSK_BaseClass, Diagnose))
5411 return false;
5412
5413 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5414 // A copy/move [constructor or assignment operator] for a class X is
5415 // trivial if
5416 // -- for each non-static data member of X that is of class type (or array
5417 // thereof), the constructor selected to copy/move that member is
5418 // trivial
5419 //
5420 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5421 // A [default constructor or destructor] is trivial if
5422 // -- for all of the non-static data members of its class that are of class
5423 // type (or array thereof), each such class has a trivial [default
5424 // constructor or destructor]
5425 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5426 return false;
5427
5428 // C++11 [class.dtor]p5:
5429 // A destructor is trivial if [...]
5430 // -- the destructor is not virtual
5431 if (CSM == CXXDestructor && MD->isVirtual()) {
5432 if (Diagnose)
5433 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5434 return false;
5435 }
5436
5437 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5438 // A [special member] for class X is trivial if [...]
5439 // -- class X has no virtual functions and no virtual base classes
5440 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5441 if (!Diagnose)
5442 return false;
5443
5444 if (RD->getNumVBases()) {
5445 // Check for virtual bases. We already know that the corresponding
5446 // member in all bases is trivial, so vbases must all be direct.
5447 CXXBaseSpecifier &BS = *RD->vbases_begin();
5448 assert(BS.isVirtual());
5449 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5450 return false;
5451 }
5452
5453 // Must have a virtual method.
5454 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5455 ME = RD->method_end(); MI != ME; ++MI) {
5456 if (MI->isVirtual()) {
5457 SourceLocation MLoc = MI->getLocStart();
5458 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5459 return false;
5460 }
5461 }
5462
5463 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5464 }
5465
5466 // Looks like it's trivial!
5467 return true;
5468}
5469
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005470/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005471namespace {
5472 struct FindHiddenVirtualMethodData {
5473 Sema *S;
5474 CXXMethodDecl *Method;
5475 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005476 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005477 };
5478}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005479
David Blaikie5f750682012-10-19 00:53:08 +00005480/// \brief Check whether any most overriden method from MD in Methods
5481static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5482 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5483 if (MD->size_overridden_methods() == 0)
5484 return Methods.count(MD->getCanonicalDecl());
5485 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5486 E = MD->end_overridden_methods();
5487 I != E; ++I)
5488 if (CheckMostOverridenMethods(*I, Methods))
5489 return true;
5490 return false;
5491}
5492
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005493/// \brief Member lookup function that determines whether a given C++
5494/// method overloads virtual methods in a base class without overriding any,
5495/// to be used with CXXRecordDecl::lookupInBases().
5496static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5497 CXXBasePath &Path,
5498 void *UserData) {
5499 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5500
5501 FindHiddenVirtualMethodData &Data
5502 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5503
5504 DeclarationName Name = Data.Method->getDeclName();
5505 assert(Name.getNameKind() == DeclarationName::Identifier);
5506
5507 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005508 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005509 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005510 !Path.Decls.empty();
5511 Path.Decls = Path.Decls.slice(1)) {
5512 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005513 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005514 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005515 foundSameNameMethod = true;
5516 // Interested only in hidden virtual methods.
5517 if (!MD->isVirtual())
5518 continue;
5519 // If the method we are checking overrides a method from its base
5520 // don't warn about the other overloaded methods.
5521 if (!Data.S->IsOverload(Data.Method, MD, false))
5522 return true;
5523 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005524 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005525 overloadedMethods.push_back(MD);
5526 }
5527 }
5528
5529 if (foundSameNameMethod)
5530 Data.OverloadedMethods.append(overloadedMethods.begin(),
5531 overloadedMethods.end());
5532 return foundSameNameMethod;
5533}
5534
David Blaikie5f750682012-10-19 00:53:08 +00005535/// \brief Add the most overriden methods from MD to Methods
5536static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5537 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5538 if (MD->size_overridden_methods() == 0)
5539 Methods.insert(MD->getCanonicalDecl());
5540 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5541 E = MD->end_overridden_methods();
5542 I != E; ++I)
5543 AddMostOverridenMethods(*I, Methods);
5544}
5545
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005546/// \brief See if a method overloads virtual methods in a base class without
5547/// overriding any.
5548void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5549 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005550 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005551 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005552 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005553 return;
5554
5555 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5556 /*bool RecordPaths=*/false,
5557 /*bool DetectVirtual=*/false);
5558 FindHiddenVirtualMethodData Data;
5559 Data.Method = MD;
5560 Data.S = this;
5561
5562 // Keep the base methods that were overriden or introduced in the subclass
5563 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005564 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5565 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5566 NamedDecl *ND = *I;
5567 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005568 ND = shad->getTargetDecl();
5569 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5570 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005571 }
5572
5573 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5574 !Data.OverloadedMethods.empty()) {
5575 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5576 << MD << (Data.OverloadedMethods.size() > 1);
5577
5578 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5579 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005580 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005581 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005582 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5583 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005584 }
5585 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005586}
5587
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005588void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005589 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005590 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005591 SourceLocation RBrac,
5592 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005593 if (!TagDecl)
5594 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005595
Douglas Gregor42af25f2009-05-11 19:58:34 +00005596 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005597
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005598 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5599 if (l->getKind() != AttributeList::AT_Visibility)
5600 continue;
5601 l->setInvalid();
5602 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5603 l->getName();
5604 }
5605
David Blaikie77b6de02011-09-22 02:58:26 +00005606 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005607 // strict aliasing violation!
5608 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005609 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005610
Douglas Gregor23c94db2010-07-02 17:43:08 +00005611 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005612 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005613}
5614
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005615/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5616/// special functions, such as the default constructor, copy
5617/// constructor, or destructor, to the given C++ class (C++
5618/// [special]p1). This routine can only be executed just before the
5619/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005620void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005621 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005622 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005623
Richard Smithbc2a35d2012-12-08 08:32:28 +00005624 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005625 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005626
Richard Smithbc2a35d2012-12-08 08:32:28 +00005627 // If the properties or semantics of the copy constructor couldn't be
5628 // determined while the class was being declared, force a declaration
5629 // of it now.
5630 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5631 DeclareImplicitCopyConstructor(ClassDecl);
5632 }
5633
Richard Smith80ad52f2013-01-02 11:42:31 +00005634 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005635 ++ASTContext::NumImplicitMoveConstructors;
5636
Richard Smithbc2a35d2012-12-08 08:32:28 +00005637 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5638 DeclareImplicitMoveConstructor(ClassDecl);
5639 }
5640
Douglas Gregora376d102010-07-02 21:50:04 +00005641 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5642 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005643
5644 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005645 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005646 // it shows up in the right place in the vtable and that we diagnose
5647 // problems with the implicit exception specification.
5648 if (ClassDecl->isDynamicClass() ||
5649 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005650 DeclareImplicitCopyAssignment(ClassDecl);
5651 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005652
Richard Smith80ad52f2013-01-02 11:42:31 +00005653 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005654 ++ASTContext::NumImplicitMoveAssignmentOperators;
5655
5656 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005657 if (ClassDecl->isDynamicClass() ||
5658 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005659 DeclareImplicitMoveAssignment(ClassDecl);
5660 }
5661
Douglas Gregor4923aa22010-07-02 20:37:36 +00005662 if (!ClassDecl->hasUserDeclaredDestructor()) {
5663 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005664
5665 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005666 // have to declare the destructor immediately. This ensures that, e.g., it
5667 // shows up in the right place in the vtable and that we diagnose problems
5668 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005669 if (ClassDecl->isDynamicClass() ||
5670 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005671 DeclareImplicitDestructor(ClassDecl);
5672 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005673}
5674
Francois Pichet8387e2a2011-04-22 22:18:13 +00005675void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5676 if (!D)
5677 return;
5678
5679 int NumParamList = D->getNumTemplateParameterLists();
5680 for (int i = 0; i < NumParamList; i++) {
5681 TemplateParameterList* Params = D->getTemplateParameterList(i);
5682 for (TemplateParameterList::iterator Param = Params->begin(),
5683 ParamEnd = Params->end();
5684 Param != ParamEnd; ++Param) {
5685 NamedDecl *Named = cast<NamedDecl>(*Param);
5686 if (Named->getDeclName()) {
5687 S->AddDecl(Named);
5688 IdResolver.AddDecl(Named);
5689 }
5690 }
5691 }
5692}
5693
John McCalld226f652010-08-21 09:40:31 +00005694void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005695 if (!D)
5696 return;
5697
5698 TemplateParameterList *Params = 0;
5699 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5700 Params = Template->getTemplateParameters();
5701 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5702 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5703 Params = PartialSpec->getTemplateParameters();
5704 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005705 return;
5706
Douglas Gregor6569d682009-05-27 23:11:45 +00005707 for (TemplateParameterList::iterator Param = Params->begin(),
5708 ParamEnd = Params->end();
5709 Param != ParamEnd; ++Param) {
5710 NamedDecl *Named = cast<NamedDecl>(*Param);
5711 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005712 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005713 IdResolver.AddDecl(Named);
5714 }
5715 }
5716}
5717
John McCalld226f652010-08-21 09:40:31 +00005718void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005719 if (!RecordD) return;
5720 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005721 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005722 PushDeclContext(S, Record);
5723}
5724
John McCalld226f652010-08-21 09:40:31 +00005725void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005726 if (!RecordD) return;
5727 PopDeclContext();
5728}
5729
Douglas Gregor72b505b2008-12-16 21:30:33 +00005730/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5731/// parsing a top-level (non-nested) C++ class, and we are now
5732/// parsing those parts of the given Method declaration that could
5733/// not be parsed earlier (C++ [class.mem]p2), such as default
5734/// arguments. This action should enter the scope of the given
5735/// Method declaration as if we had just parsed the qualified method
5736/// name. However, it should not bring the parameters into scope;
5737/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005738void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005739}
5740
5741/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5742/// C++ method declaration. We're (re-)introducing the given
5743/// function parameter into scope for use in parsing later parts of
5744/// the method declaration. For example, we could see an
5745/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005746void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005747 if (!ParamD)
5748 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005749
John McCalld226f652010-08-21 09:40:31 +00005750 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005751
5752 // If this parameter has an unparsed default argument, clear it out
5753 // to make way for the parsed default argument.
5754 if (Param->hasUnparsedDefaultArg())
5755 Param->setDefaultArg(0);
5756
John McCalld226f652010-08-21 09:40:31 +00005757 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005758 if (Param->getDeclName())
5759 IdResolver.AddDecl(Param);
5760}
5761
5762/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5763/// processing the delayed method declaration for Method. The method
5764/// declaration is now considered finished. There may be a separate
5765/// ActOnStartOfFunctionDef action later (not necessarily
5766/// immediately!) for this method, if it was also defined inside the
5767/// class body.
John McCalld226f652010-08-21 09:40:31 +00005768void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005769 if (!MethodD)
5770 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005771
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005772 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005773
John McCalld226f652010-08-21 09:40:31 +00005774 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005775
5776 // Now that we have our default arguments, check the constructor
5777 // again. It could produce additional diagnostics or affect whether
5778 // the class has implicitly-declared destructors, among other
5779 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005780 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5781 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005782
5783 // Check the default arguments, which we may have added.
5784 if (!Method->isInvalidDecl())
5785 CheckCXXDefaultArguments(Method);
5786}
5787
Douglas Gregor42a552f2008-11-05 20:51:48 +00005788/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005789/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005790/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005791/// emit diagnostics and set the invalid bit to true. In any case, the type
5792/// will be updated to reflect a well-formed type for the constructor and
5793/// returned.
5794QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005795 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005796 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005797
5798 // C++ [class.ctor]p3:
5799 // A constructor shall not be virtual (10.3) or static (9.4). A
5800 // constructor can be invoked for a const, volatile or const
5801 // volatile object. A constructor shall not be declared const,
5802 // volatile, or const volatile (9.3.2).
5803 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005804 if (!D.isInvalidType())
5805 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5806 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5807 << SourceRange(D.getIdentifierLoc());
5808 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005809 }
John McCalld931b082010-08-26 03:08:43 +00005810 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005811 if (!D.isInvalidType())
5812 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5813 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5814 << SourceRange(D.getIdentifierLoc());
5815 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005816 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005817 }
Mike Stump1eb44332009-09-09 15:08:12 +00005818
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005819 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005820 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005821 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005822 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5823 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005824 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005825 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5826 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005827 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005828 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5829 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005830 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005831 }
Mike Stump1eb44332009-09-09 15:08:12 +00005832
Douglas Gregorc938c162011-01-26 05:01:58 +00005833 // C++0x [class.ctor]p4:
5834 // A constructor shall not be declared with a ref-qualifier.
5835 if (FTI.hasRefQualifier()) {
5836 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5837 << FTI.RefQualifierIsLValueRef
5838 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5839 D.setInvalidType();
5840 }
5841
Douglas Gregor42a552f2008-11-05 20:51:48 +00005842 // Rebuild the function type "R" without any type qualifiers (in
5843 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005844 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005845 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005846 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5847 return R;
5848
5849 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5850 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005851 EPI.RefQualifier = RQ_None;
5852
Richard Smith07b0fdc2013-03-18 21:12:30 +00005853 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005854}
5855
Douglas Gregor72b505b2008-12-16 21:30:33 +00005856/// CheckConstructor - Checks a fully-formed constructor for
5857/// well-formedness, issuing any diagnostics required. Returns true if
5858/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005859void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005860 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005861 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5862 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005863 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005864
5865 // C++ [class.copy]p3:
5866 // A declaration of a constructor for a class X is ill-formed if
5867 // its first parameter is of type (optionally cv-qualified) X and
5868 // either there are no other parameters or else all other
5869 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005870 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005871 ((Constructor->getNumParams() == 1) ||
5872 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005873 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5874 Constructor->getTemplateSpecializationKind()
5875 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005876 QualType ParamType = Constructor->getParamDecl(0)->getType();
5877 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5878 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005879 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005880 const char *ConstRef
5881 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5882 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005883 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005884 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005885
5886 // FIXME: Rather that making the constructor invalid, we should endeavor
5887 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005888 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005889 }
5890 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005891}
5892
John McCall15442822010-08-04 01:04:25 +00005893/// CheckDestructor - Checks a fully-formed destructor definition for
5894/// well-formedness, issuing any diagnostics required. Returns true
5895/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005896bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005897 CXXRecordDecl *RD = Destructor->getParent();
5898
5899 if (Destructor->isVirtual()) {
5900 SourceLocation Loc;
5901
5902 if (!Destructor->isImplicit())
5903 Loc = Destructor->getLocation();
5904 else
5905 Loc = RD->getLocation();
5906
5907 // If we have a virtual destructor, look up the deallocation function
5908 FunctionDecl *OperatorDelete = 0;
5909 DeclarationName Name =
5910 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005911 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005912 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005913
Eli Friedman5f2987c2012-02-02 03:46:19 +00005914 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005915
5916 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005917 }
Anders Carlsson37909802009-11-30 21:24:50 +00005918
5919 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005920}
5921
Mike Stump1eb44332009-09-09 15:08:12 +00005922static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005923FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5924 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5925 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005926 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005927}
5928
Douglas Gregor42a552f2008-11-05 20:51:48 +00005929/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5930/// the well-formednes of the destructor declarator @p D with type @p
5931/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005932/// emit diagnostics and set the declarator to invalid. Even if this happens,
5933/// will be updated to reflect a well-formed type for the destructor and
5934/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005935QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005936 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005937 // C++ [class.dtor]p1:
5938 // [...] A typedef-name that names a class is a class-name
5939 // (7.1.3); however, a typedef-name that names a class shall not
5940 // be used as the identifier in the declarator for a destructor
5941 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005942 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005943 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005944 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005945 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005946 else if (const TemplateSpecializationType *TST =
5947 DeclaratorType->getAs<TemplateSpecializationType>())
5948 if (TST->isTypeAlias())
5949 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5950 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005951
5952 // C++ [class.dtor]p2:
5953 // A destructor is used to destroy objects of its class type. A
5954 // destructor takes no parameters, and no return type can be
5955 // specified for it (not even void). The address of a destructor
5956 // shall not be taken. A destructor shall not be static. A
5957 // destructor can be invoked for a const, volatile or const
5958 // volatile object. A destructor shall not be declared const,
5959 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005960 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005961 if (!D.isInvalidType())
5962 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5963 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005964 << SourceRange(D.getIdentifierLoc())
5965 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5966
John McCalld931b082010-08-26 03:08:43 +00005967 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005968 }
Chris Lattner65401802009-04-25 08:28:21 +00005969 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005970 // Destructors don't have return types, but the parser will
5971 // happily parse something like:
5972 //
5973 // class X {
5974 // float ~X();
5975 // };
5976 //
5977 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005978 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5979 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5980 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005981 }
Mike Stump1eb44332009-09-09 15:08:12 +00005982
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005983 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005984 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005985 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005986 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5987 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005988 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005989 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5990 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005991 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005992 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5993 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005994 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005995 }
5996
Douglas Gregorc938c162011-01-26 05:01:58 +00005997 // C++0x [class.dtor]p2:
5998 // A destructor shall not be declared with a ref-qualifier.
5999 if (FTI.hasRefQualifier()) {
6000 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6001 << FTI.RefQualifierIsLValueRef
6002 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6003 D.setInvalidType();
6004 }
6005
Douglas Gregor42a552f2008-11-05 20:51:48 +00006006 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006007 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006008 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6009
6010 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006011 FTI.freeArgs();
6012 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006013 }
6014
Mike Stump1eb44332009-09-09 15:08:12 +00006015 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006016 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006017 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006018 D.setInvalidType();
6019 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006020
6021 // Rebuild the function type "R" without any type qualifiers or
6022 // parameters (in case any of the errors above fired) and with
6023 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006024 // types.
John McCalle23cf432010-12-14 08:05:40 +00006025 if (!D.isInvalidType())
6026 return R;
6027
Douglas Gregord92ec472010-07-01 05:10:53 +00006028 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006029 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6030 EPI.Variadic = false;
6031 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006032 EPI.RefQualifier = RQ_None;
Jordan Rosebea522f2013-03-08 21:51:21 +00006033 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006034}
6035
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006036/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6037/// well-formednes of the conversion function declarator @p D with
6038/// type @p R. If there are any errors in the declarator, this routine
6039/// will emit diagnostics and return true. Otherwise, it will return
6040/// false. Either way, the type @p R will be updated to reflect a
6041/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006042void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006043 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006044 // C++ [class.conv.fct]p1:
6045 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006046 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006047 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006048 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006049 if (!D.isInvalidType())
6050 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6051 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6052 << SourceRange(D.getIdentifierLoc());
6053 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006054 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006055 }
John McCalla3f81372010-04-13 00:04:31 +00006056
6057 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6058
Chris Lattner6e475012009-04-25 08:35:12 +00006059 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006060 // Conversion functions don't have return types, but the parser will
6061 // happily parse something like:
6062 //
6063 // class X {
6064 // float operator bool();
6065 // };
6066 //
6067 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006068 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6069 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6070 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006071 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006072 }
6073
John McCalla3f81372010-04-13 00:04:31 +00006074 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6075
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006076 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006077 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006078 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6079
6080 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006081 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006082 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006083 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006084 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006085 D.setInvalidType();
6086 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006087
John McCalla3f81372010-04-13 00:04:31 +00006088 // Diagnose "&operator bool()" and other such nonsense. This
6089 // is actually a gcc extension which we don't support.
6090 if (Proto->getResultType() != ConvType) {
6091 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6092 << Proto->getResultType();
6093 D.setInvalidType();
6094 ConvType = Proto->getResultType();
6095 }
6096
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006097 // C++ [class.conv.fct]p4:
6098 // The conversion-type-id shall not represent a function type nor
6099 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006100 if (ConvType->isArrayType()) {
6101 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6102 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006103 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006104 } else if (ConvType->isFunctionType()) {
6105 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6106 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006107 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006108 }
6109
6110 // Rebuild the function type "R" without any parameters (in case any
6111 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006112 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006113 if (D.isInvalidType())
Jordan Rosebea522f2013-03-08 21:51:21 +00006114 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
6115 Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006116
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006117 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006118 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006119 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006120 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006121 diag::warn_cxx98_compat_explicit_conversion_functions :
6122 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006123 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006124}
6125
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006126/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6127/// the declaration of the given C++ conversion function. This routine
6128/// is responsible for recording the conversion function in the C++
6129/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006130Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006131 assert(Conversion && "Expected to receive a conversion function declaration");
6132
Douglas Gregor9d350972008-12-12 08:25:50 +00006133 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006134
6135 // Make sure we aren't redeclaring the conversion function.
6136 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006137
6138 // C++ [class.conv.fct]p1:
6139 // [...] A conversion function is never used to convert a
6140 // (possibly cv-qualified) object to the (possibly cv-qualified)
6141 // same object type (or a reference to it), to a (possibly
6142 // cv-qualified) base class of that type (or a reference to it),
6143 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006144 // FIXME: Suppress this warning if the conversion function ends up being a
6145 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006146 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006147 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006148 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006149 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006150 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6151 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006152 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006153 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006154 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6155 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006156 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006157 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006158 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006159 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006160 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006161 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006162 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006163 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006164 }
6165
Douglas Gregore80622f2010-09-29 04:25:11 +00006166 if (FunctionTemplateDecl *ConversionTemplate
6167 = Conversion->getDescribedFunctionTemplate())
6168 return ConversionTemplate;
6169
John McCalld226f652010-08-21 09:40:31 +00006170 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006171}
6172
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006173//===----------------------------------------------------------------------===//
6174// Namespace Handling
6175//===----------------------------------------------------------------------===//
6176
Richard Smithd1a55a62012-10-04 22:13:39 +00006177/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6178/// reopened.
6179static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6180 SourceLocation Loc,
6181 IdentifierInfo *II, bool *IsInline,
6182 NamespaceDecl *PrevNS) {
6183 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006184
Richard Smithc969e6a2012-10-05 01:46:25 +00006185 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6186 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6187 // inline namespaces, with the intention of bringing names into namespace std.
6188 //
6189 // We support this just well enough to get that case working; this is not
6190 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006191 if (*IsInline && II && II->getName().startswith("__atomic") &&
6192 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006193 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006194 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6195 NS = NS->getPreviousDecl())
6196 NS->setInline(*IsInline);
6197 // Patch up the lookup table for the containing namespace. This isn't really
6198 // correct, but it's good enough for this particular case.
6199 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6200 E = PrevNS->decls_end(); I != E; ++I)
6201 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6202 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6203 return;
6204 }
6205
6206 if (PrevNS->isInline())
6207 // The user probably just forgot the 'inline', so suggest that it
6208 // be added back.
6209 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6210 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6211 else
6212 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6213 << IsInline;
6214
6215 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6216 *IsInline = PrevNS->isInline();
6217}
John McCallea318642010-08-26 09:15:37 +00006218
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006219/// ActOnStartNamespaceDef - This is called at the start of a namespace
6220/// definition.
John McCalld226f652010-08-21 09:40:31 +00006221Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006222 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006223 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006224 SourceLocation IdentLoc,
6225 IdentifierInfo *II,
6226 SourceLocation LBrace,
6227 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006228 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6229 // For anonymous namespace, take the location of the left brace.
6230 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006231 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006232 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006233 bool IsStd = false;
6234 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006235 Scope *DeclRegionScope = NamespcScope->getParent();
6236
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006237 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006238 if (II) {
6239 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006240 // The identifier in an original-namespace-definition shall not
6241 // have been previously defined in the declarative region in
6242 // which the original-namespace-definition appears. The
6243 // identifier in an original-namespace-definition is the name of
6244 // the namespace. Subsequently in that declarative region, it is
6245 // treated as an original-namespace-name.
6246 //
6247 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006248 // look through using directives, just look for any ordinary names.
6249
6250 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006251 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6252 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006253 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006254 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6255 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6256 ++I) {
6257 if ((*I)->getIdentifierNamespace() & IDNS) {
6258 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006259 break;
6260 }
6261 }
6262
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006263 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6264
6265 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006266 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006267 if (IsInline != PrevNS->isInline())
6268 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6269 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006270 } else if (PrevDecl) {
6271 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006272 Diag(Loc, diag::err_redefinition_different_kind)
6273 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006274 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006275 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006276 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006277 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006278 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006279 // This is the first "real" definition of the namespace "std", so update
6280 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006281 PrevNS = getStdNamespace();
6282 IsStd = true;
6283 AddToKnown = !IsInline;
6284 } else {
6285 // We've seen this namespace for the first time.
6286 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006287 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006288 } else {
John McCall9aeed322009-10-01 00:25:31 +00006289 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006290
6291 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006292 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006293 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006294 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006295 } else {
6296 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006297 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006298 }
6299
Richard Smithd1a55a62012-10-04 22:13:39 +00006300 if (PrevNS && IsInline != PrevNS->isInline())
6301 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6302 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006303 }
6304
6305 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6306 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006307 if (IsInvalid)
6308 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006309
6310 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006311
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006312 // FIXME: Should we be merging attributes?
6313 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006314 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006315
6316 if (IsStd)
6317 StdNamespace = Namespc;
6318 if (AddToKnown)
6319 KnownNamespaces[Namespc] = false;
6320
6321 if (II) {
6322 PushOnScopeChains(Namespc, DeclRegionScope);
6323 } else {
6324 // Link the anonymous namespace into its parent.
6325 DeclContext *Parent = CurContext->getRedeclContext();
6326 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6327 TU->setAnonymousNamespace(Namespc);
6328 } else {
6329 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006330 }
John McCall9aeed322009-10-01 00:25:31 +00006331
Douglas Gregora4181472010-03-24 00:46:35 +00006332 CurContext->addDecl(Namespc);
6333
John McCall9aeed322009-10-01 00:25:31 +00006334 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6335 // behaves as if it were replaced by
6336 // namespace unique { /* empty body */ }
6337 // using namespace unique;
6338 // namespace unique { namespace-body }
6339 // where all occurrences of 'unique' in a translation unit are
6340 // replaced by the same identifier and this identifier differs
6341 // from all other identifiers in the entire program.
6342
6343 // We just create the namespace with an empty name and then add an
6344 // implicit using declaration, just like the standard suggests.
6345 //
6346 // CodeGen enforces the "universally unique" aspect by giving all
6347 // declarations semantically contained within an anonymous
6348 // namespace internal linkage.
6349
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006350 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006351 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006352 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006353 /* 'using' */ LBrace,
6354 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006355 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006356 /* identifier */ SourceLocation(),
6357 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006358 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006359 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006360 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006361 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006362 }
6363
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006364 ActOnDocumentableDecl(Namespc);
6365
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006366 // Although we could have an invalid decl (i.e. the namespace name is a
6367 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006368 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6369 // for the namespace has the declarations that showed up in that particular
6370 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006371 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006372 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006373}
6374
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006375/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6376/// is a namespace alias, returns the namespace it points to.
6377static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6378 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6379 return AD->getNamespace();
6380 return dyn_cast_or_null<NamespaceDecl>(D);
6381}
6382
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006383/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6384/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006385void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006386 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6387 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006388 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006389 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006390 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006391 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006392}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006393
John McCall384aff82010-08-25 07:42:41 +00006394CXXRecordDecl *Sema::getStdBadAlloc() const {
6395 return cast_or_null<CXXRecordDecl>(
6396 StdBadAlloc.get(Context.getExternalSource()));
6397}
6398
6399NamespaceDecl *Sema::getStdNamespace() const {
6400 return cast_or_null<NamespaceDecl>(
6401 StdNamespace.get(Context.getExternalSource()));
6402}
6403
Douglas Gregor66992202010-06-29 17:53:46 +00006404/// \brief Retrieve the special "std" namespace, which may require us to
6405/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006406NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006407 if (!StdNamespace) {
6408 // The "std" namespace has not yet been defined, so build one implicitly.
6409 StdNamespace = NamespaceDecl::Create(Context,
6410 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006411 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006412 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006413 &PP.getIdentifierTable().get("std"),
6414 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006415 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006416 }
6417
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006418 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006419}
6420
Sebastian Redl395e04d2012-01-17 22:49:33 +00006421bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006422 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006423 "Looking for std::initializer_list outside of C++.");
6424
6425 // We're looking for implicit instantiations of
6426 // template <typename E> class std::initializer_list.
6427
6428 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6429 return false;
6430
Sebastian Redl84760e32012-01-17 22:49:58 +00006431 ClassTemplateDecl *Template = 0;
6432 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006433
Sebastian Redl84760e32012-01-17 22:49:58 +00006434 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006435
Sebastian Redl84760e32012-01-17 22:49:58 +00006436 ClassTemplateSpecializationDecl *Specialization =
6437 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6438 if (!Specialization)
6439 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006440
Sebastian Redl84760e32012-01-17 22:49:58 +00006441 Template = Specialization->getSpecializedTemplate();
6442 Arguments = Specialization->getTemplateArgs().data();
6443 } else if (const TemplateSpecializationType *TST =
6444 Ty->getAs<TemplateSpecializationType>()) {
6445 Template = dyn_cast_or_null<ClassTemplateDecl>(
6446 TST->getTemplateName().getAsTemplateDecl());
6447 Arguments = TST->getArgs();
6448 }
6449 if (!Template)
6450 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006451
6452 if (!StdInitializerList) {
6453 // Haven't recognized std::initializer_list yet, maybe this is it.
6454 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6455 if (TemplateClass->getIdentifier() !=
6456 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006457 !getStdNamespace()->InEnclosingNamespaceSetOf(
6458 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006459 return false;
6460 // This is a template called std::initializer_list, but is it the right
6461 // template?
6462 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006463 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006464 return false;
6465 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6466 return false;
6467
6468 // It's the right template.
6469 StdInitializerList = Template;
6470 }
6471
6472 if (Template != StdInitializerList)
6473 return false;
6474
6475 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006476 if (Element)
6477 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006478 return true;
6479}
6480
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006481static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6482 NamespaceDecl *Std = S.getStdNamespace();
6483 if (!Std) {
6484 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6485 return 0;
6486 }
6487
6488 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6489 Loc, Sema::LookupOrdinaryName);
6490 if (!S.LookupQualifiedName(Result, Std)) {
6491 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6492 return 0;
6493 }
6494 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6495 if (!Template) {
6496 Result.suppressDiagnostics();
6497 // We found something weird. Complain about the first thing we found.
6498 NamedDecl *Found = *Result.begin();
6499 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6500 return 0;
6501 }
6502
6503 // We found some template called std::initializer_list. Now verify that it's
6504 // correct.
6505 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006506 if (Params->getMinRequiredArguments() != 1 ||
6507 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006508 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6509 return 0;
6510 }
6511
6512 return Template;
6513}
6514
6515QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6516 if (!StdInitializerList) {
6517 StdInitializerList = LookupStdInitializerList(*this, Loc);
6518 if (!StdInitializerList)
6519 return QualType();
6520 }
6521
6522 TemplateArgumentListInfo Args(Loc, Loc);
6523 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6524 Context.getTrivialTypeSourceInfo(Element,
6525 Loc)));
6526 return Context.getCanonicalType(
6527 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6528}
6529
Sebastian Redl98d36062012-01-17 22:50:14 +00006530bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6531 // C++ [dcl.init.list]p2:
6532 // A constructor is an initializer-list constructor if its first parameter
6533 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6534 // std::initializer_list<E> for some type E, and either there are no other
6535 // parameters or else all other parameters have default arguments.
6536 if (Ctor->getNumParams() < 1 ||
6537 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6538 return false;
6539
6540 QualType ArgType = Ctor->getParamDecl(0)->getType();
6541 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6542 ArgType = RT->getPointeeType().getUnqualifiedType();
6543
6544 return isStdInitializerList(ArgType, 0);
6545}
6546
Douglas Gregor9172aa62011-03-26 22:25:30 +00006547/// \brief Determine whether a using statement is in a context where it will be
6548/// apply in all contexts.
6549static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6550 switch (CurContext->getDeclKind()) {
6551 case Decl::TranslationUnit:
6552 return true;
6553 case Decl::LinkageSpec:
6554 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6555 default:
6556 return false;
6557 }
6558}
6559
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006560namespace {
6561
6562// Callback to only accept typo corrections that are namespaces.
6563class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6564 public:
6565 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6566 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6567 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6568 }
6569 return false;
6570 }
6571};
6572
6573}
6574
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006575static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6576 CXXScopeSpec &SS,
6577 SourceLocation IdentLoc,
6578 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006579 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006580 R.clear();
6581 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006582 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006583 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006584 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6585 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006586 if (DeclContext *DC = S.computeDeclContext(SS, false))
6587 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6588 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006589 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6590 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006591 else
6592 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6593 << Ident << CorrectedQuotedStr
6594 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006595
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006596 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6597 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006598
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006599 R.addDecl(Corrected.getCorrectionDecl());
6600 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006601 }
6602 return false;
6603}
6604
John McCalld226f652010-08-21 09:40:31 +00006605Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006606 SourceLocation UsingLoc,
6607 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006608 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006609 SourceLocation IdentLoc,
6610 IdentifierInfo *NamespcName,
6611 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006612 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6613 assert(NamespcName && "Invalid NamespcName.");
6614 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006615
6616 // This can only happen along a recovery path.
6617 while (S->getFlags() & Scope::TemplateParamScope)
6618 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006619 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006620
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006621 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006622 NestedNameSpecifier *Qualifier = 0;
6623 if (SS.isSet())
6624 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6625
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006626 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006627 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6628 LookupParsedName(R, S, &SS);
6629 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006630 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006631
Douglas Gregor66992202010-06-29 17:53:46 +00006632 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006633 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006634 // Allow "using namespace std;" or "using namespace ::std;" even if
6635 // "std" hasn't been defined yet, for GCC compatibility.
6636 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6637 NamespcName->isStr("std")) {
6638 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006639 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006640 R.resolveKind();
6641 }
6642 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006643 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006644 }
6645
John McCallf36e02d2009-10-09 21:13:30 +00006646 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006647 NamedDecl *Named = R.getFoundDecl();
6648 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6649 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006650 // C++ [namespace.udir]p1:
6651 // A using-directive specifies that the names in the nominated
6652 // namespace can be used in the scope in which the
6653 // using-directive appears after the using-directive. During
6654 // unqualified name lookup (3.4.1), the names appear as if they
6655 // were declared in the nearest enclosing namespace which
6656 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006657 // namespace. [Note: in this context, "contains" means "contains
6658 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006659
6660 // Find enclosing context containing both using-directive and
6661 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006662 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006663 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6664 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6665 CommonAncestor = CommonAncestor->getParent();
6666
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006667 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006668 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006669 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006670
Douglas Gregor9172aa62011-03-26 22:25:30 +00006671 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006672 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006673 Diag(IdentLoc, diag::warn_using_directive_in_header);
6674 }
6675
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006676 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006677 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006678 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006679 }
6680
Richard Smith6b3d3e52013-02-20 19:22:51 +00006681 if (UDir)
6682 ProcessDeclAttributeList(S, UDir, AttrList);
6683
John McCalld226f652010-08-21 09:40:31 +00006684 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006685}
6686
6687void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006688 // If the scope has an associated entity and the using directive is at
6689 // namespace or translation unit scope, add the UsingDirectiveDecl into
6690 // its lookup structure so qualified name lookup can find it.
6691 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6692 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006693 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006694 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006695 // Otherwise, it is at block sope. The using-directives will affect lookup
6696 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006697 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006698}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006699
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006700
John McCalld226f652010-08-21 09:40:31 +00006701Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006702 AccessSpecifier AS,
6703 bool HasUsingKeyword,
6704 SourceLocation UsingLoc,
6705 CXXScopeSpec &SS,
6706 UnqualifiedId &Name,
6707 AttributeList *AttrList,
6708 bool IsTypeName,
6709 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006710 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006711
Douglas Gregor12c118a2009-11-04 16:30:06 +00006712 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006713 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006714 case UnqualifiedId::IK_Identifier:
6715 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006716 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006717 case UnqualifiedId::IK_ConversionFunctionId:
6718 break;
6719
6720 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006721 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006722 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006723 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006724 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006725 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006726 diag::err_using_decl_constructor)
6727 << SS.getRange();
6728
Richard Smith80ad52f2013-01-02 11:42:31 +00006729 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006730
John McCalld226f652010-08-21 09:40:31 +00006731 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006732
6733 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006734 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006735 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006736 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006737
6738 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006739 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006740 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006741 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006742 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006743
6744 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6745 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006746 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006747 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006748
Richard Smith07b0fdc2013-03-18 21:12:30 +00006749 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006750 // TODO: store that the declaration was written without 'using' and
6751 // talk about access decls instead of using decls in the
6752 // diagnostics.
6753 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006754 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006755
6756 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006757 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006758 }
6759
Douglas Gregor56c04582010-12-16 00:46:58 +00006760 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6761 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6762 return 0;
6763
John McCall9488ea12009-11-17 05:59:44 +00006764 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006765 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006766 /* IsInstantiation */ false,
6767 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006768 if (UD)
6769 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006770
John McCalld226f652010-08-21 09:40:31 +00006771 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006772}
6773
Douglas Gregor09acc982010-07-07 23:08:52 +00006774/// \brief Determine whether a using declaration considers the given
6775/// declarations as "equivalent", e.g., if they are redeclarations of
6776/// the same entity or are both typedefs of the same type.
6777static bool
6778IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6779 bool &SuppressRedeclaration) {
6780 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6781 SuppressRedeclaration = false;
6782 return true;
6783 }
6784
Richard Smith162e1c12011-04-15 14:24:37 +00006785 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6786 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006787 SuppressRedeclaration = true;
6788 return Context.hasSameType(TD1->getUnderlyingType(),
6789 TD2->getUnderlyingType());
6790 }
6791
6792 return false;
6793}
6794
6795
John McCall9f54ad42009-12-10 09:41:52 +00006796/// Determines whether to create a using shadow decl for a particular
6797/// decl, given the set of decls existing prior to this using lookup.
6798bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6799 const LookupResult &Previous) {
6800 // Diagnose finding a decl which is not from a base class of the
6801 // current class. We do this now because there are cases where this
6802 // function will silently decide not to build a shadow decl, which
6803 // will pre-empt further diagnostics.
6804 //
6805 // We don't need to do this in C++0x because we do the check once on
6806 // the qualifier.
6807 //
6808 // FIXME: diagnose the following if we care enough:
6809 // struct A { int foo; };
6810 // struct B : A { using A::foo; };
6811 // template <class T> struct C : A {};
6812 // template <class T> struct D : C<T> { using B::foo; } // <---
6813 // This is invalid (during instantiation) in C++03 because B::foo
6814 // resolves to the using decl in B, which is not a base class of D<T>.
6815 // We can't diagnose it immediately because C<T> is an unknown
6816 // specialization. The UsingShadowDecl in D<T> then points directly
6817 // to A::foo, which will look well-formed when we instantiate.
6818 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006819 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006820 DeclContext *OrigDC = Orig->getDeclContext();
6821
6822 // Handle enums and anonymous structs.
6823 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6824 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6825 while (OrigRec->isAnonymousStructOrUnion())
6826 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6827
6828 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6829 if (OrigDC == CurContext) {
6830 Diag(Using->getLocation(),
6831 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006832 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006833 Diag(Orig->getLocation(), diag::note_using_decl_target);
6834 return true;
6835 }
6836
Douglas Gregordc355712011-02-25 00:36:19 +00006837 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006838 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006839 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006840 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006841 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006842 Diag(Orig->getLocation(), diag::note_using_decl_target);
6843 return true;
6844 }
6845 }
6846
6847 if (Previous.empty()) return false;
6848
6849 NamedDecl *Target = Orig;
6850 if (isa<UsingShadowDecl>(Target))
6851 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6852
John McCalld7533ec2009-12-11 02:33:26 +00006853 // If the target happens to be one of the previous declarations, we
6854 // don't have a conflict.
6855 //
6856 // FIXME: but we might be increasing its access, in which case we
6857 // should redeclare it.
6858 NamedDecl *NonTag = 0, *Tag = 0;
6859 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6860 I != E; ++I) {
6861 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006862 bool Result;
6863 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6864 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006865
6866 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6867 }
6868
John McCall9f54ad42009-12-10 09:41:52 +00006869 if (Target->isFunctionOrFunctionTemplate()) {
6870 FunctionDecl *FD;
6871 if (isa<FunctionTemplateDecl>(Target))
6872 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6873 else
6874 FD = cast<FunctionDecl>(Target);
6875
6876 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006877 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006878 case Ovl_Overload:
6879 return false;
6880
6881 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006882 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006883 break;
6884
6885 // We found a decl with the exact signature.
6886 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006887 // If we're in a record, we want to hide the target, so we
6888 // return true (without a diagnostic) to tell the caller not to
6889 // build a shadow decl.
6890 if (CurContext->isRecord())
6891 return true;
6892
6893 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006894 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006895 break;
6896 }
6897
6898 Diag(Target->getLocation(), diag::note_using_decl_target);
6899 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6900 return true;
6901 }
6902
6903 // Target is not a function.
6904
John McCall9f54ad42009-12-10 09:41:52 +00006905 if (isa<TagDecl>(Target)) {
6906 // No conflict between a tag and a non-tag.
6907 if (!Tag) return false;
6908
John McCall41ce66f2009-12-10 19:51:03 +00006909 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006910 Diag(Target->getLocation(), diag::note_using_decl_target);
6911 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6912 return true;
6913 }
6914
6915 // No conflict between a tag and a non-tag.
6916 if (!NonTag) return false;
6917
John McCall41ce66f2009-12-10 19:51:03 +00006918 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006919 Diag(Target->getLocation(), diag::note_using_decl_target);
6920 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6921 return true;
6922}
6923
John McCall9488ea12009-11-17 05:59:44 +00006924/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006925UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006926 UsingDecl *UD,
6927 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006928
6929 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006930 NamedDecl *Target = Orig;
6931 if (isa<UsingShadowDecl>(Target)) {
6932 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6933 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006934 }
6935
6936 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006937 = UsingShadowDecl::Create(Context, CurContext,
6938 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006939 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006940
6941 Shadow->setAccess(UD->getAccess());
6942 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6943 Shadow->setInvalidDecl();
6944
John McCall9488ea12009-11-17 05:59:44 +00006945 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006946 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006947 else
John McCall604e7f12009-12-08 07:46:18 +00006948 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006949
John McCall604e7f12009-12-08 07:46:18 +00006950
John McCall9f54ad42009-12-10 09:41:52 +00006951 return Shadow;
6952}
John McCall604e7f12009-12-08 07:46:18 +00006953
John McCall9f54ad42009-12-10 09:41:52 +00006954/// Hides a using shadow declaration. This is required by the current
6955/// using-decl implementation when a resolvable using declaration in a
6956/// class is followed by a declaration which would hide or override
6957/// one or more of the using decl's targets; for example:
6958///
6959/// struct Base { void foo(int); };
6960/// struct Derived : Base {
6961/// using Base::foo;
6962/// void foo(int);
6963/// };
6964///
6965/// The governing language is C++03 [namespace.udecl]p12:
6966///
6967/// When a using-declaration brings names from a base class into a
6968/// derived class scope, member functions in the derived class
6969/// override and/or hide member functions with the same name and
6970/// parameter types in a base class (rather than conflicting).
6971///
6972/// There are two ways to implement this:
6973/// (1) optimistically create shadow decls when they're not hidden
6974/// by existing declarations, or
6975/// (2) don't create any shadow decls (or at least don't make them
6976/// visible) until we've fully parsed/instantiated the class.
6977/// The problem with (1) is that we might have to retroactively remove
6978/// a shadow decl, which requires several O(n) operations because the
6979/// decl structures are (very reasonably) not designed for removal.
6980/// (2) avoids this but is very fiddly and phase-dependent.
6981void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006982 if (Shadow->getDeclName().getNameKind() ==
6983 DeclarationName::CXXConversionFunctionName)
6984 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6985
John McCall9f54ad42009-12-10 09:41:52 +00006986 // Remove it from the DeclContext...
6987 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006988
John McCall9f54ad42009-12-10 09:41:52 +00006989 // ...and the scope, if applicable...
6990 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006991 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006992 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006993 }
6994
John McCall9f54ad42009-12-10 09:41:52 +00006995 // ...and the using decl.
6996 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6997
6998 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006999 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007000}
7001
John McCall7ba107a2009-11-18 02:36:19 +00007002/// Builds a using declaration.
7003///
7004/// \param IsInstantiation - Whether this call arises from an
7005/// instantiation of an unresolved using declaration. We treat
7006/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007007NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7008 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007009 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007010 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007011 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007012 bool IsInstantiation,
7013 bool IsTypeName,
7014 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007015 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007016 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007017 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007018
Anders Carlsson550b14b2009-08-28 05:49:21 +00007019 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007020
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007021 if (SS.isEmpty()) {
7022 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007023 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007024 }
Mike Stump1eb44332009-09-09 15:08:12 +00007025
John McCall9f54ad42009-12-10 09:41:52 +00007026 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007027 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007028 ForRedeclaration);
7029 Previous.setHideTags(false);
7030 if (S) {
7031 LookupName(Previous, S);
7032
7033 // It is really dumb that we have to do this.
7034 LookupResult::Filter F = Previous.makeFilter();
7035 while (F.hasNext()) {
7036 NamedDecl *D = F.next();
7037 if (!isDeclInScope(D, CurContext, S))
7038 F.erase();
7039 }
7040 F.done();
7041 } else {
7042 assert(IsInstantiation && "no scope in non-instantiation");
7043 assert(CurContext->isRecord() && "scope not record in instantiation");
7044 LookupQualifiedName(Previous, CurContext);
7045 }
7046
John McCall9f54ad42009-12-10 09:41:52 +00007047 // Check for invalid redeclarations.
7048 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7049 return 0;
7050
7051 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007052 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7053 return 0;
7054
John McCallaf8e6ed2009-11-12 03:15:40 +00007055 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007056 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007057 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007058 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00007059 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00007060 // FIXME: not all declaration name kinds are legal here
7061 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7062 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007063 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007064 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007065 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007066 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7067 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007068 }
John McCalled976492009-12-04 22:46:56 +00007069 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007070 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7071 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007072 }
John McCalled976492009-12-04 22:46:56 +00007073 D->setAccess(AS);
7074 CurContext->addDecl(D);
7075
7076 if (!LookupContext) return D;
7077 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007078
John McCall77bb1aa2010-05-01 00:40:08 +00007079 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007080 UD->setInvalidDecl();
7081 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007082 }
7083
Richard Smithc5a89a12012-04-02 01:30:27 +00007084 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007085 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007086 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007087 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007088 return UD;
7089 }
7090
7091 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007092
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007093 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007094
John McCall604e7f12009-12-08 07:46:18 +00007095 // Unlike most lookups, we don't always want to hide tag
7096 // declarations: tag names are visible through the using declaration
7097 // even if hidden by ordinary names, *except* in a dependent context
7098 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007099 if (!IsInstantiation)
7100 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007101
John McCallb9abd8722012-04-07 03:04:20 +00007102 // For the purposes of this lookup, we have a base object type
7103 // equal to that of the current context.
7104 if (CurContext->isRecord()) {
7105 R.setBaseObjectType(
7106 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7107 }
7108
John McCalla24dc2e2009-11-17 02:14:36 +00007109 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007110
John McCallf36e02d2009-10-09 21:13:30 +00007111 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00007112 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007113 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007114 UD->setInvalidDecl();
7115 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007116 }
7117
John McCalled976492009-12-04 22:46:56 +00007118 if (R.isAmbiguous()) {
7119 UD->setInvalidDecl();
7120 return UD;
7121 }
Mike Stump1eb44332009-09-09 15:08:12 +00007122
John McCall7ba107a2009-11-18 02:36:19 +00007123 if (IsTypeName) {
7124 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007125 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007126 Diag(IdentLoc, diag::err_using_typename_non_type);
7127 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7128 Diag((*I)->getUnderlyingDecl()->getLocation(),
7129 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007130 UD->setInvalidDecl();
7131 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007132 }
7133 } else {
7134 // If we asked for a non-typename and we got a type, error out,
7135 // but only if this is an instantiation of an unresolved using
7136 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007137 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007138 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7139 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007140 UD->setInvalidDecl();
7141 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007142 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007143 }
7144
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007145 // C++0x N2914 [namespace.udecl]p6:
7146 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007147 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007148 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7149 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007150 UD->setInvalidDecl();
7151 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007152 }
Mike Stump1eb44332009-09-09 15:08:12 +00007153
John McCall9f54ad42009-12-10 09:41:52 +00007154 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7155 if (!CheckUsingShadowDecl(UD, *I, Previous))
7156 BuildUsingShadowDecl(S, UD, *I);
7157 }
John McCall9488ea12009-11-17 05:59:44 +00007158
7159 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007160}
7161
Sebastian Redlf677ea32011-02-05 19:23:19 +00007162/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007163bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7164 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007165
Douglas Gregordc355712011-02-25 00:36:19 +00007166 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007167 assert(SourceType &&
7168 "Using decl naming constructor doesn't have type in scope spec.");
7169 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7170
7171 // Check whether the named type is a direct base class.
7172 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7173 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7174 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7175 BaseIt != BaseE; ++BaseIt) {
7176 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7177 if (CanonicalSourceType == BaseType)
7178 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007179 if (BaseIt->getType()->isDependentType())
7180 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007181 }
7182
7183 if (BaseIt == BaseE) {
7184 // Did not find SourceType in the bases.
7185 Diag(UD->getUsingLocation(),
7186 diag::err_using_decl_constructor_not_in_direct_base)
7187 << UD->getNameInfo().getSourceRange()
7188 << QualType(SourceType, 0) << TargetClass;
7189 return true;
7190 }
7191
Richard Smithc5a89a12012-04-02 01:30:27 +00007192 if (!CurContext->isDependentContext())
7193 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007194
7195 return false;
7196}
7197
John McCall9f54ad42009-12-10 09:41:52 +00007198/// Checks that the given using declaration is not an invalid
7199/// redeclaration. Note that this is checking only for the using decl
7200/// itself, not for any ill-formedness among the UsingShadowDecls.
7201bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7202 bool isTypeName,
7203 const CXXScopeSpec &SS,
7204 SourceLocation NameLoc,
7205 const LookupResult &Prev) {
7206 // C++03 [namespace.udecl]p8:
7207 // C++0x [namespace.udecl]p10:
7208 // A using-declaration is a declaration and can therefore be used
7209 // repeatedly where (and only where) multiple declarations are
7210 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007211 //
John McCall8a726212010-11-29 18:01:58 +00007212 // That's in non-member contexts.
7213 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007214 return false;
7215
7216 NestedNameSpecifier *Qual
7217 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7218
7219 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7220 NamedDecl *D = *I;
7221
7222 bool DTypename;
7223 NestedNameSpecifier *DQual;
7224 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7225 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007226 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007227 } else if (UnresolvedUsingValueDecl *UD
7228 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7229 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007230 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007231 } else if (UnresolvedUsingTypenameDecl *UD
7232 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7233 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007234 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007235 } else continue;
7236
7237 // using decls differ if one says 'typename' and the other doesn't.
7238 // FIXME: non-dependent using decls?
7239 if (isTypeName != DTypename) continue;
7240
7241 // using decls differ if they name different scopes (but note that
7242 // template instantiation can cause this check to trigger when it
7243 // didn't before instantiation).
7244 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7245 Context.getCanonicalNestedNameSpecifier(DQual))
7246 continue;
7247
7248 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007249 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007250 return true;
7251 }
7252
7253 return false;
7254}
7255
John McCall604e7f12009-12-08 07:46:18 +00007256
John McCalled976492009-12-04 22:46:56 +00007257/// Checks that the given nested-name qualifier used in a using decl
7258/// in the current context is appropriately related to the current
7259/// scope. If an error is found, diagnoses it and returns true.
7260bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7261 const CXXScopeSpec &SS,
7262 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007263 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007264
John McCall604e7f12009-12-08 07:46:18 +00007265 if (!CurContext->isRecord()) {
7266 // C++03 [namespace.udecl]p3:
7267 // C++0x [namespace.udecl]p8:
7268 // A using-declaration for a class member shall be a member-declaration.
7269
7270 // If we weren't able to compute a valid scope, it must be a
7271 // dependent class scope.
7272 if (!NamedContext || NamedContext->isRecord()) {
7273 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7274 << SS.getRange();
7275 return true;
7276 }
7277
7278 // Otherwise, everything is known to be fine.
7279 return false;
7280 }
7281
7282 // The current scope is a record.
7283
7284 // If the named context is dependent, we can't decide much.
7285 if (!NamedContext) {
7286 // FIXME: in C++0x, we can diagnose if we can prove that the
7287 // nested-name-specifier does not refer to a base class, which is
7288 // still possible in some cases.
7289
7290 // Otherwise we have to conservatively report that things might be
7291 // okay.
7292 return false;
7293 }
7294
7295 if (!NamedContext->isRecord()) {
7296 // Ideally this would point at the last name in the specifier,
7297 // but we don't have that level of source info.
7298 Diag(SS.getRange().getBegin(),
7299 diag::err_using_decl_nested_name_specifier_is_not_class)
7300 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7301 return true;
7302 }
7303
Douglas Gregor6fb07292010-12-21 07:41:49 +00007304 if (!NamedContext->isDependentContext() &&
7305 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7306 return true;
7307
Richard Smith80ad52f2013-01-02 11:42:31 +00007308 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007309 // C++0x [namespace.udecl]p3:
7310 // In a using-declaration used as a member-declaration, the
7311 // nested-name-specifier shall name a base class of the class
7312 // being defined.
7313
7314 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7315 cast<CXXRecordDecl>(NamedContext))) {
7316 if (CurContext == NamedContext) {
7317 Diag(NameLoc,
7318 diag::err_using_decl_nested_name_specifier_is_current_class)
7319 << SS.getRange();
7320 return true;
7321 }
7322
7323 Diag(SS.getRange().getBegin(),
7324 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7325 << (NestedNameSpecifier*) SS.getScopeRep()
7326 << cast<CXXRecordDecl>(CurContext)
7327 << SS.getRange();
7328 return true;
7329 }
7330
7331 return false;
7332 }
7333
7334 // C++03 [namespace.udecl]p4:
7335 // A using-declaration used as a member-declaration shall refer
7336 // to a member of a base class of the class being defined [etc.].
7337
7338 // Salient point: SS doesn't have to name a base class as long as
7339 // lookup only finds members from base classes. Therefore we can
7340 // diagnose here only if we can prove that that can't happen,
7341 // i.e. if the class hierarchies provably don't intersect.
7342
7343 // TODO: it would be nice if "definitely valid" results were cached
7344 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7345 // need to be repeated.
7346
7347 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007348 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007349
7350 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7351 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7352 Data->Bases.insert(Base);
7353 return true;
7354 }
7355
7356 bool hasDependentBases(const CXXRecordDecl *Class) {
7357 return !Class->forallBases(collect, this);
7358 }
7359
7360 /// Returns true if the base is dependent or is one of the
7361 /// accumulated base classes.
7362 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7363 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7364 return !Data->Bases.count(Base);
7365 }
7366
7367 bool mightShareBases(const CXXRecordDecl *Class) {
7368 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7369 }
7370 };
7371
7372 UserData Data;
7373
7374 // Returns false if we find a dependent base.
7375 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7376 return false;
7377
7378 // Returns false if the class has a dependent base or if it or one
7379 // of its bases is present in the base set of the current context.
7380 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7381 return false;
7382
7383 Diag(SS.getRange().getBegin(),
7384 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7385 << (NestedNameSpecifier*) SS.getScopeRep()
7386 << cast<CXXRecordDecl>(CurContext)
7387 << SS.getRange();
7388
7389 return true;
John McCalled976492009-12-04 22:46:56 +00007390}
7391
Richard Smith162e1c12011-04-15 14:24:37 +00007392Decl *Sema::ActOnAliasDeclaration(Scope *S,
7393 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007394 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007395 SourceLocation UsingLoc,
7396 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007397 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007398 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007399 // Skip up to the relevant declaration scope.
7400 while (S->getFlags() & Scope::TemplateParamScope)
7401 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007402 assert((S->getFlags() & Scope::DeclScope) &&
7403 "got alias-declaration outside of declaration scope");
7404
7405 if (Type.isInvalid())
7406 return 0;
7407
7408 bool Invalid = false;
7409 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7410 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007411 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007412
7413 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7414 return 0;
7415
7416 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007417 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007418 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007419 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7420 TInfo->getTypeLoc().getBeginLoc());
7421 }
Richard Smith162e1c12011-04-15 14:24:37 +00007422
7423 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7424 LookupName(Previous, S);
7425
7426 // Warn about shadowing the name of a template parameter.
7427 if (Previous.isSingleResult() &&
7428 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007429 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007430 Previous.clear();
7431 }
7432
7433 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7434 "name in alias declaration must be an identifier");
7435 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7436 Name.StartLocation,
7437 Name.Identifier, TInfo);
7438
7439 NewTD->setAccess(AS);
7440
7441 if (Invalid)
7442 NewTD->setInvalidDecl();
7443
Richard Smith6b3d3e52013-02-20 19:22:51 +00007444 ProcessDeclAttributeList(S, NewTD, AttrList);
7445
Richard Smith3e4c6c42011-05-05 21:57:07 +00007446 CheckTypedefForVariablyModifiedType(S, NewTD);
7447 Invalid |= NewTD->isInvalidDecl();
7448
Richard Smith162e1c12011-04-15 14:24:37 +00007449 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007450
7451 NamedDecl *NewND;
7452 if (TemplateParamLists.size()) {
7453 TypeAliasTemplateDecl *OldDecl = 0;
7454 TemplateParameterList *OldTemplateParams = 0;
7455
7456 if (TemplateParamLists.size() != 1) {
7457 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007458 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7459 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007460 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007461 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007462
7463 // Only consider previous declarations in the same scope.
7464 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7465 /*ExplicitInstantiationOrSpecialization*/false);
7466 if (!Previous.empty()) {
7467 Redeclaration = true;
7468
7469 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7470 if (!OldDecl && !Invalid) {
7471 Diag(UsingLoc, diag::err_redefinition_different_kind)
7472 << Name.Identifier;
7473
7474 NamedDecl *OldD = Previous.getRepresentativeDecl();
7475 if (OldD->getLocation().isValid())
7476 Diag(OldD->getLocation(), diag::note_previous_definition);
7477
7478 Invalid = true;
7479 }
7480
7481 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7482 if (TemplateParameterListsAreEqual(TemplateParams,
7483 OldDecl->getTemplateParameters(),
7484 /*Complain=*/true,
7485 TPL_TemplateMatch))
7486 OldTemplateParams = OldDecl->getTemplateParameters();
7487 else
7488 Invalid = true;
7489
7490 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7491 if (!Invalid &&
7492 !Context.hasSameType(OldTD->getUnderlyingType(),
7493 NewTD->getUnderlyingType())) {
7494 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7495 // but we can't reasonably accept it.
7496 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7497 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7498 if (OldTD->getLocation().isValid())
7499 Diag(OldTD->getLocation(), diag::note_previous_definition);
7500 Invalid = true;
7501 }
7502 }
7503 }
7504
7505 // Merge any previous default template arguments into our parameters,
7506 // and check the parameter list.
7507 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7508 TPC_TypeAliasTemplate))
7509 return 0;
7510
7511 TypeAliasTemplateDecl *NewDecl =
7512 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7513 Name.Identifier, TemplateParams,
7514 NewTD);
7515
7516 NewDecl->setAccess(AS);
7517
7518 if (Invalid)
7519 NewDecl->setInvalidDecl();
7520 else if (OldDecl)
7521 NewDecl->setPreviousDeclaration(OldDecl);
7522
7523 NewND = NewDecl;
7524 } else {
7525 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7526 NewND = NewTD;
7527 }
Richard Smith162e1c12011-04-15 14:24:37 +00007528
7529 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007530 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007531
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007532 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007533 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007534}
7535
John McCalld226f652010-08-21 09:40:31 +00007536Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007537 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007538 SourceLocation AliasLoc,
7539 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007540 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007541 SourceLocation IdentLoc,
7542 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007543
Anders Carlsson81c85c42009-03-28 23:53:49 +00007544 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007545 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7546 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007547
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007548 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007549 NamedDecl *PrevDecl
7550 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7551 ForRedeclaration);
7552 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7553 PrevDecl = 0;
7554
7555 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007556 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007557 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007558 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007559 // FIXME: At some point, we'll want to create the (redundant)
7560 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007561 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007562 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007563 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007564 }
Mike Stump1eb44332009-09-09 15:08:12 +00007565
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007566 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7567 diag::err_redefinition_different_kind;
7568 Diag(AliasLoc, DiagID) << Alias;
7569 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007570 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007571 }
7572
John McCalla24dc2e2009-11-17 02:14:36 +00007573 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007574 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007575
John McCallf36e02d2009-10-09 21:13:30 +00007576 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007577 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007578 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007579 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007580 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007581 }
Mike Stump1eb44332009-09-09 15:08:12 +00007582
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007583 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007584 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007585 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007586 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007587
John McCall3dbd3d52010-02-16 06:53:13 +00007588 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007589 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007590}
7591
Sean Hunt001cad92011-05-10 00:49:42 +00007592Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007593Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7594 CXXMethodDecl *MD) {
7595 CXXRecordDecl *ClassDecl = MD->getParent();
7596
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007597 // C++ [except.spec]p14:
7598 // An implicitly declared special member function (Clause 12) shall have an
7599 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007600 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007601 if (ClassDecl->isInvalidDecl())
7602 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007603
Sebastian Redl60618fa2011-03-12 11:50:43 +00007604 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007605 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7606 BEnd = ClassDecl->bases_end();
7607 B != BEnd; ++B) {
7608 if (B->isVirtual()) // Handled below.
7609 continue;
7610
Douglas Gregor18274032010-07-03 00:47:00 +00007611 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7612 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007613 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7614 // If this is a deleted function, add it anyway. This might be conformant
7615 // with the standard. This might not. I'm not sure. It might not matter.
7616 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007617 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007618 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007619 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007620
7621 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007622 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7623 BEnd = ClassDecl->vbases_end();
7624 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007625 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7626 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007627 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7628 // If this is a deleted function, add it anyway. This might be conformant
7629 // with the standard. This might not. I'm not sure. It might not matter.
7630 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007631 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007632 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007633 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007634
7635 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007636 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7637 FEnd = ClassDecl->field_end();
7638 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007639 if (F->hasInClassInitializer()) {
7640 if (Expr *E = F->getInClassInitializer())
7641 ExceptSpec.CalledExpr(E);
7642 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007643 // DR1351:
7644 // If the brace-or-equal-initializer of a non-static data member
7645 // invokes a defaulted default constructor of its class or of an
7646 // enclosing class in a potentially evaluated subexpression, the
7647 // program is ill-formed.
7648 //
7649 // This resolution is unworkable: the exception specification of the
7650 // default constructor can be needed in an unevaluated context, in
7651 // particular, in the operand of a noexcept-expression, and we can be
7652 // unable to compute an exception specification for an enclosed class.
7653 //
7654 // We do not allow an in-class initializer to require the evaluation
7655 // of the exception specification for any in-class initializer whose
7656 // definition is not lexically complete.
7657 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007658 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007659 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007660 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7661 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7662 // If this is a deleted function, add it anyway. This might be conformant
7663 // with the standard. This might not. I'm not sure. It might not matter.
7664 // In particular, the problem is that this function never gets called. It
7665 // might just be ill-formed because this function attempts to refer to
7666 // a deleted function here.
7667 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007668 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007669 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007670 }
John McCalle23cf432010-12-14 08:05:40 +00007671
Sean Hunt001cad92011-05-10 00:49:42 +00007672 return ExceptSpec;
7673}
7674
Richard Smith07b0fdc2013-03-18 21:12:30 +00007675Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007676Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7677 CXXRecordDecl *ClassDecl = CD->getParent();
7678
7679 // C++ [except.spec]p14:
7680 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007681 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007682 if (ClassDecl->isInvalidDecl())
7683 return ExceptSpec;
7684
7685 // Inherited constructor.
7686 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7687 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7688 // FIXME: Copying or moving the parameters could add extra exceptions to the
7689 // set, as could the default arguments for the inherited constructor. This
7690 // will be addressed when we implement the resolution of core issue 1351.
7691 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7692
7693 // Direct base-class constructors.
7694 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7695 BEnd = ClassDecl->bases_end();
7696 B != BEnd; ++B) {
7697 if (B->isVirtual()) // Handled below.
7698 continue;
7699
7700 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7701 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7702 if (BaseClassDecl == InheritedDecl)
7703 continue;
7704 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7705 if (Constructor)
7706 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7707 }
7708 }
7709
7710 // Virtual base-class constructors.
7711 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7712 BEnd = ClassDecl->vbases_end();
7713 B != BEnd; ++B) {
7714 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7715 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7716 if (BaseClassDecl == InheritedDecl)
7717 continue;
7718 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7719 if (Constructor)
7720 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7721 }
7722 }
7723
7724 // Field constructors.
7725 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7726 FEnd = ClassDecl->field_end();
7727 F != FEnd; ++F) {
7728 if (F->hasInClassInitializer()) {
7729 if (Expr *E = F->getInClassInitializer())
7730 ExceptSpec.CalledExpr(E);
7731 else if (!F->isInvalidDecl())
7732 Diag(CD->getLocation(),
7733 diag::err_in_class_initializer_references_def_ctor) << CD;
7734 } else if (const RecordType *RecordTy
7735 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7736 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7737 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7738 if (Constructor)
7739 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7740 }
7741 }
7742
Richard Smith07b0fdc2013-03-18 21:12:30 +00007743 return ExceptSpec;
7744}
7745
Richard Smithafb49182012-11-29 01:34:07 +00007746namespace {
7747/// RAII object to register a special member as being currently declared.
7748struct DeclaringSpecialMember {
7749 Sema &S;
7750 Sema::SpecialMemberDecl D;
7751 bool WasAlreadyBeingDeclared;
7752
7753 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7754 : S(S), D(RD, CSM) {
7755 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7756 if (WasAlreadyBeingDeclared)
7757 // This almost never happens, but if it does, ensure that our cache
7758 // doesn't contain a stale result.
7759 S.SpecialMemberCache.clear();
7760
7761 // FIXME: Register a note to be produced if we encounter an error while
7762 // declaring the special member.
7763 }
7764 ~DeclaringSpecialMember() {
7765 if (!WasAlreadyBeingDeclared)
7766 S.SpecialMembersBeingDeclared.erase(D);
7767 }
7768
7769 /// \brief Are we already trying to declare this special member?
7770 bool isAlreadyBeingDeclared() const {
7771 return WasAlreadyBeingDeclared;
7772 }
7773};
7774}
7775
Sean Hunt001cad92011-05-10 00:49:42 +00007776CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7777 CXXRecordDecl *ClassDecl) {
7778 // C++ [class.ctor]p5:
7779 // A default constructor for a class X is a constructor of class X
7780 // that can be called without an argument. If there is no
7781 // user-declared constructor for class X, a default constructor is
7782 // implicitly declared. An implicitly-declared default constructor
7783 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007784 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007785 "Should not build implicit default constructor!");
7786
Richard Smithafb49182012-11-29 01:34:07 +00007787 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7788 if (DSM.isAlreadyBeingDeclared())
7789 return 0;
7790
Richard Smith7756afa2012-06-10 05:43:50 +00007791 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7792 CXXDefaultConstructor,
7793 false);
7794
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007795 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007796 CanQualType ClassType
7797 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007798 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007799 DeclarationName Name
7800 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007801 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007802 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007803 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007804 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007805 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007806 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007807 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007808 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007809
7810 // Build an exception specification pointing back at this constructor.
7811 FunctionProtoType::ExtProtoInfo EPI;
7812 EPI.ExceptionSpecType = EST_Unevaluated;
7813 EPI.ExceptionSpecDecl = DefaultCon;
Jordan Rosebea522f2013-03-08 21:51:21 +00007814 DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7815 ArrayRef<QualType>(),
7816 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007817
Richard Smithbc2a35d2012-12-08 08:32:28 +00007818 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7819 // constructors is easy to compute.
7820 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7821
7822 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007823 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007824
Douglas Gregor18274032010-07-03 00:47:00 +00007825 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007826 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007827
Douglas Gregor23c94db2010-07-02 17:43:08 +00007828 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007829 PushOnScopeChains(DefaultCon, S, false);
7830 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007831
Douglas Gregor32df23e2010-07-01 22:02:46 +00007832 return DefaultCon;
7833}
7834
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007835void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7836 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007837 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007838 !Constructor->doesThisDeclarationHaveABody() &&
7839 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007840 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007841
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007842 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007843 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007844
Eli Friedman9a14db32012-10-18 20:14:08 +00007845 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007846 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007847 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007848 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007849 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007850 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007851 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007852 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007853 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007854
7855 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007856 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007857
7858 Constructor->setUsed();
7859 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007860
7861 if (ASTMutationListener *L = getASTMutationListener()) {
7862 L->CompletedImplicitDefinition(Constructor);
7863 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007864}
7865
Richard Smith7a614d82011-06-11 17:19:42 +00007866void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007867 // Check that any explicitly-defaulted methods have exception specifications
7868 // compatible with their implicit exception specifications.
7869 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007870}
7871
Richard Smith4841ca52013-04-10 05:48:59 +00007872namespace {
7873/// Information on inheriting constructors to declare.
7874class InheritingConstructorInfo {
7875public:
7876 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7877 : SemaRef(SemaRef), Derived(Derived) {
7878 // Mark the constructors that we already have in the derived class.
7879 //
7880 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7881 // unless there is a user-declared constructor with the same signature in
7882 // the class where the using-declaration appears.
7883 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7884 }
7885
7886 void inheritAll(CXXRecordDecl *RD) {
7887 visitAll(RD, &InheritingConstructorInfo::inherit);
7888 }
7889
7890private:
7891 /// Information about an inheriting constructor.
7892 struct InheritingConstructor {
7893 InheritingConstructor()
7894 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7895
7896 /// If \c true, a constructor with this signature is already declared
7897 /// in the derived class.
7898 bool DeclaredInDerived;
7899
7900 /// The constructor which is inherited.
7901 const CXXConstructorDecl *BaseCtor;
7902
7903 /// The derived constructor we declared.
7904 CXXConstructorDecl *DerivedCtor;
7905 };
7906
7907 /// Inheriting constructors with a given canonical type. There can be at
7908 /// most one such non-template constructor, and any number of templated
7909 /// constructors.
7910 struct InheritingConstructorsForType {
7911 InheritingConstructor NonTemplate;
7912 llvm::SmallVector<
7913 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7914
7915 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7916 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7917 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7918 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7919 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7920 false, S.TPL_TemplateMatch))
7921 return Templates[I].second;
7922 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7923 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007924 }
Richard Smith4841ca52013-04-10 05:48:59 +00007925
7926 return NonTemplate;
7927 }
7928 };
7929
7930 /// Get or create the inheriting constructor record for a constructor.
7931 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7932 QualType CtorType) {
7933 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7934 .getEntry(SemaRef, Ctor);
7935 }
7936
7937 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7938
7939 /// Process all constructors for a class.
7940 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7941 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7942 CtorE = RD->ctor_end();
7943 CtorIt != CtorE; ++CtorIt)
7944 (this->*Callback)(*CtorIt);
7945 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7946 I(RD->decls_begin()), E(RD->decls_end());
7947 I != E; ++I) {
7948 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7949 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7950 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007951 }
7952 }
Richard Smith4841ca52013-04-10 05:48:59 +00007953
7954 /// Note that a constructor (or constructor template) was declared in Derived.
7955 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7956 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7957 }
7958
7959 /// Inherit a single constructor.
7960 void inherit(const CXXConstructorDecl *Ctor) {
7961 const FunctionProtoType *CtorType =
7962 Ctor->getType()->castAs<FunctionProtoType>();
7963 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7964 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7965
7966 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7967
7968 // Core issue (no number yet): the ellipsis is always discarded.
7969 if (EPI.Variadic) {
7970 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7971 SemaRef.Diag(Ctor->getLocation(),
7972 diag::note_using_decl_constructor_ellipsis);
7973 EPI.Variadic = false;
7974 }
7975
7976 // Declare a constructor for each number of parameters.
7977 //
7978 // C++11 [class.inhctor]p1:
7979 // The candidate set of inherited constructors from the class X named in
7980 // the using-declaration consists of [... modulo defects ...] for each
7981 // constructor or constructor template of X, the set of constructors or
7982 // constructor templates that results from omitting any ellipsis parameter
7983 // specification and successively omitting parameters with a default
7984 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00007985 unsigned MinParams = minParamsToInherit(Ctor);
7986 unsigned Params = Ctor->getNumParams();
7987 if (Params >= MinParams) {
7988 do
7989 declareCtor(UsingLoc, Ctor,
7990 SemaRef.Context.getFunctionType(
7991 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7992 while (Params > MinParams &&
7993 Ctor->getParamDecl(--Params)->hasDefaultArg());
7994 }
Richard Smith4841ca52013-04-10 05:48:59 +00007995 }
7996
7997 /// Find the using-declaration which specified that we should inherit the
7998 /// constructors of \p Base.
7999 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8000 // No fancy lookup required; just look for the base constructor name
8001 // directly within the derived class.
8002 ASTContext &Context = SemaRef.Context;
8003 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8004 Context.getCanonicalType(Context.getRecordType(Base)));
8005 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8006 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8007 }
8008
8009 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8010 // C++11 [class.inhctor]p3:
8011 // [F]or each constructor template in the candidate set of inherited
8012 // constructors, a constructor template is implicitly declared
8013 if (Ctor->getDescribedFunctionTemplate())
8014 return 0;
8015
8016 // For each non-template constructor in the candidate set of inherited
8017 // constructors other than a constructor having no parameters or a
8018 // copy/move constructor having a single parameter, a constructor is
8019 // implicitly declared [...]
8020 if (Ctor->getNumParams() == 0)
8021 return 1;
8022 if (Ctor->isCopyOrMoveConstructor())
8023 return 2;
8024
8025 // Per discussion on core reflector, never inherit a constructor which
8026 // would become a default, copy, or move constructor of Derived either.
8027 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8028 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8029 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8030 }
8031
8032 /// Declare a single inheriting constructor, inheriting the specified
8033 /// constructor, with the given type.
8034 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8035 QualType DerivedType) {
8036 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8037
8038 // C++11 [class.inhctor]p3:
8039 // ... a constructor is implicitly declared with the same constructor
8040 // characteristics unless there is a user-declared constructor with
8041 // the same signature in the class where the using-declaration appears
8042 if (Entry.DeclaredInDerived)
8043 return;
8044
8045 // C++11 [class.inhctor]p7:
8046 // If two using-declarations declare inheriting constructors with the
8047 // same signature, the program is ill-formed
8048 if (Entry.DerivedCtor) {
8049 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8050 // Only diagnose this once per constructor.
8051 if (Entry.DerivedCtor->isInvalidDecl())
8052 return;
8053 Entry.DerivedCtor->setInvalidDecl();
8054
8055 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8056 SemaRef.Diag(BaseCtor->getLocation(),
8057 diag::note_using_decl_constructor_conflict_current_ctor);
8058 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8059 diag::note_using_decl_constructor_conflict_previous_ctor);
8060 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8061 diag::note_using_decl_constructor_conflict_previous_using);
8062 } else {
8063 // Core issue (no number): if the same inheriting constructor is
8064 // produced by multiple base class constructors from the same base
8065 // class, the inheriting constructor is defined as deleted.
8066 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8067 }
8068
8069 return;
8070 }
8071
8072 ASTContext &Context = SemaRef.Context;
8073 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8074 Context.getCanonicalType(Context.getRecordType(Derived)));
8075 DeclarationNameInfo NameInfo(Name, UsingLoc);
8076
8077 TemplateParameterList *TemplateParams = 0;
8078 if (const FunctionTemplateDecl *FTD =
8079 BaseCtor->getDescribedFunctionTemplate()) {
8080 TemplateParams = FTD->getTemplateParameters();
8081 // We're reusing template parameters from a different DeclContext. This
8082 // is questionable at best, but works out because the template depth in
8083 // both places is guaranteed to be 0.
8084 // FIXME: Rebuild the template parameters in the new context, and
8085 // transform the function type to refer to them.
8086 }
8087
8088 // Build type source info pointing at the using-declaration. This is
8089 // required by template instantiation.
8090 TypeSourceInfo *TInfo =
8091 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8092 FunctionProtoTypeLoc ProtoLoc =
8093 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8094
8095 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8096 Context, Derived, UsingLoc, NameInfo, DerivedType,
8097 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8098 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8099
8100 // Build an unevaluated exception specification for this constructor.
8101 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8102 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8103 EPI.ExceptionSpecType = EST_Unevaluated;
8104 EPI.ExceptionSpecDecl = DerivedCtor;
8105 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8106 FPT->getArgTypes(), EPI));
8107
8108 // Build the parameter declarations.
8109 SmallVector<ParmVarDecl *, 16> ParamDecls;
8110 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8111 TypeSourceInfo *TInfo =
8112 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8113 ParmVarDecl *PD = ParmVarDecl::Create(
8114 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8115 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8116 PD->setScopeInfo(0, I);
8117 PD->setImplicit();
8118 ParamDecls.push_back(PD);
8119 ProtoLoc.setArg(I, PD);
8120 }
8121
8122 // Set up the new constructor.
8123 DerivedCtor->setAccess(BaseCtor->getAccess());
8124 DerivedCtor->setParams(ParamDecls);
8125 DerivedCtor->setInheritedConstructor(BaseCtor);
8126 if (BaseCtor->isDeleted())
8127 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8128
8129 // If this is a constructor template, build the template declaration.
8130 if (TemplateParams) {
8131 FunctionTemplateDecl *DerivedTemplate =
8132 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8133 TemplateParams, DerivedCtor);
8134 DerivedTemplate->setAccess(BaseCtor->getAccess());
8135 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8136 Derived->addDecl(DerivedTemplate);
8137 } else {
8138 Derived->addDecl(DerivedCtor);
8139 }
8140
8141 Entry.BaseCtor = BaseCtor;
8142 Entry.DerivedCtor = DerivedCtor;
8143 }
8144
8145 Sema &SemaRef;
8146 CXXRecordDecl *Derived;
8147 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8148 MapType Map;
8149};
8150}
8151
8152void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8153 // Defer declaring the inheriting constructors until the class is
8154 // instantiated.
8155 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008156 return;
8157
Richard Smith4841ca52013-04-10 05:48:59 +00008158 // Find base classes from which we might inherit constructors.
8159 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8160 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8161 BaseE = ClassDecl->bases_end();
8162 BaseIt != BaseE; ++BaseIt)
8163 if (BaseIt->getInheritConstructors())
8164 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008165
Richard Smith4841ca52013-04-10 05:48:59 +00008166 // Go no further if we're not inheriting any constructors.
8167 if (InheritedBases.empty())
8168 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008169
Richard Smith4841ca52013-04-10 05:48:59 +00008170 // Declare the inherited constructors.
8171 InheritingConstructorInfo ICI(*this, ClassDecl);
8172 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8173 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008174}
8175
Richard Smith07b0fdc2013-03-18 21:12:30 +00008176void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8177 CXXConstructorDecl *Constructor) {
8178 CXXRecordDecl *ClassDecl = Constructor->getParent();
8179 assert(Constructor->getInheritedConstructor() &&
8180 !Constructor->doesThisDeclarationHaveABody() &&
8181 !Constructor->isDeleted());
8182
8183 SynthesizedFunctionScope Scope(*this, Constructor);
8184 DiagnosticErrorTrap Trap(Diags);
8185 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8186 Trap.hasErrorOccurred()) {
8187 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8188 << Context.getTagDeclType(ClassDecl);
8189 Constructor->setInvalidDecl();
8190 return;
8191 }
8192
8193 SourceLocation Loc = Constructor->getLocation();
8194 Constructor->setBody(new (Context) CompoundStmt(Loc));
8195
8196 Constructor->setUsed();
8197 MarkVTableUsed(CurrentLocation, ClassDecl);
8198
8199 if (ASTMutationListener *L = getASTMutationListener()) {
8200 L->CompletedImplicitDefinition(Constructor);
8201 }
8202}
8203
8204
Sean Huntcb45a0f2011-05-12 22:46:25 +00008205Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008206Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8207 CXXRecordDecl *ClassDecl = MD->getParent();
8208
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008209 // C++ [except.spec]p14:
8210 // An implicitly declared special member function (Clause 12) shall have
8211 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008212 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008213 if (ClassDecl->isInvalidDecl())
8214 return ExceptSpec;
8215
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008216 // Direct base-class destructors.
8217 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8218 BEnd = ClassDecl->bases_end();
8219 B != BEnd; ++B) {
8220 if (B->isVirtual()) // Handled below.
8221 continue;
8222
8223 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008224 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008225 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008226 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008227
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008228 // Virtual base-class destructors.
8229 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8230 BEnd = ClassDecl->vbases_end();
8231 B != BEnd; ++B) {
8232 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008233 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008234 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008235 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008236
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008237 // Field destructors.
8238 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8239 FEnd = ClassDecl->field_end();
8240 F != FEnd; ++F) {
8241 if (const RecordType *RecordTy
8242 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008243 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008244 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008245 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008246
Sean Huntcb45a0f2011-05-12 22:46:25 +00008247 return ExceptSpec;
8248}
8249
8250CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8251 // C++ [class.dtor]p2:
8252 // If a class has no user-declared destructor, a destructor is
8253 // declared implicitly. An implicitly-declared destructor is an
8254 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008255 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008256
Richard Smithafb49182012-11-29 01:34:07 +00008257 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8258 if (DSM.isAlreadyBeingDeclared())
8259 return 0;
8260
Douglas Gregor4923aa22010-07-02 20:37:36 +00008261 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008262 CanQualType ClassType
8263 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008264 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008265 DeclarationName Name
8266 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008267 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008268 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008269 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8270 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008271 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008272 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008273 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008274 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008275
8276 // Build an exception specification pointing back at this destructor.
8277 FunctionProtoType::ExtProtoInfo EPI;
8278 EPI.ExceptionSpecType = EST_Unevaluated;
8279 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008280 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8281 ArrayRef<QualType>(),
8282 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008283
Richard Smithbc2a35d2012-12-08 08:32:28 +00008284 AddOverriddenMethods(ClassDecl, Destructor);
8285
8286 // We don't need to use SpecialMemberIsTrivial here; triviality for
8287 // destructors is easy to compute.
8288 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8289
8290 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008291 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008292
Douglas Gregor4923aa22010-07-02 20:37:36 +00008293 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008294 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008295
Douglas Gregor4923aa22010-07-02 20:37:36 +00008296 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008297 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008298 PushOnScopeChains(Destructor, S, false);
8299 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008300
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008301 return Destructor;
8302}
8303
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008304void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008305 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008306 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008307 !Destructor->doesThisDeclarationHaveABody() &&
8308 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008309 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008310 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008311 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008312
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008313 if (Destructor->isInvalidDecl())
8314 return;
8315
Eli Friedman9a14db32012-10-18 20:14:08 +00008316 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008317
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008318 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008319 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8320 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008321
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008322 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008323 Diag(CurrentLocation, diag::note_member_synthesized_at)
8324 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8325
8326 Destructor->setInvalidDecl();
8327 return;
8328 }
8329
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008330 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008331 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008332 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008333 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008334 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008335
8336 if (ASTMutationListener *L = getASTMutationListener()) {
8337 L->CompletedImplicitDefinition(Destructor);
8338 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008339}
8340
Richard Smitha4156b82012-04-21 18:42:51 +00008341/// \brief Perform any semantic analysis which needs to be delayed until all
8342/// pending class member declarations have been parsed.
8343void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008344 // If the context is an invalid C++ class, just suppress these checks.
8345 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8346 if (Record->isInvalidDecl()) {
8347 DelayedDestructorExceptionSpecChecks.clear();
8348 return;
8349 }
8350 }
8351
Richard Smitha4156b82012-04-21 18:42:51 +00008352 // Perform any deferred checking of exception specifications for virtual
8353 // destructors.
8354 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8355 i != e; ++i) {
8356 const CXXDestructorDecl *Dtor =
8357 DelayedDestructorExceptionSpecChecks[i].first;
8358 assert(!Dtor->getParent()->isDependentType() &&
8359 "Should not ever add destructors of templates into the list.");
8360 CheckOverridingFunctionExceptionSpec(Dtor,
8361 DelayedDestructorExceptionSpecChecks[i].second);
8362 }
8363 DelayedDestructorExceptionSpecChecks.clear();
8364}
8365
Richard Smithb9d0b762012-07-27 04:22:15 +00008366void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8367 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008368 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008369 "adjusting dtor exception specs was introduced in c++11");
8370
Sebastian Redl0ee33912011-05-19 05:13:44 +00008371 // C++11 [class.dtor]p3:
8372 // A declaration of a destructor that does not have an exception-
8373 // specification is implicitly considered to have the same exception-
8374 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008375 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008376 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008377 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008378 return;
8379
Chandler Carruth3f224b22011-09-20 04:55:26 +00008380 // Replace the destructor's type, building off the existing one. Fortunately,
8381 // the only thing of interest in the destructor type is its extended info.
8382 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008383 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8384 EPI.ExceptionSpecType = EST_Unevaluated;
8385 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008386 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8387 ArrayRef<QualType>(),
8388 EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008389
Sebastian Redl0ee33912011-05-19 05:13:44 +00008390 // FIXME: If the destructor has a body that could throw, and the newly created
8391 // spec doesn't allow exceptions, we should emit a warning, because this
8392 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008393 // However, we don't have a body or an exception specification yet, so it
8394 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008395}
8396
Richard Smith8c889532012-11-14 00:50:40 +00008397/// When generating a defaulted copy or move assignment operator, if a field
8398/// should be copied with __builtin_memcpy rather than via explicit assignments,
8399/// do so. This optimization only applies for arrays of scalars, and for arrays
8400/// of class type where the selected copy/move-assignment operator is trivial.
8401static StmtResult
8402buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8403 Expr *To, Expr *From) {
8404 // Compute the size of the memory buffer to be copied.
8405 QualType SizeType = S.Context.getSizeType();
8406 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8407 S.Context.getTypeSizeInChars(T).getQuantity());
8408
8409 // Take the address of the field references for "from" and "to". We
8410 // directly construct UnaryOperators here because semantic analysis
8411 // does not permit us to take the address of an xvalue.
8412 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8413 S.Context.getPointerType(From->getType()),
8414 VK_RValue, OK_Ordinary, Loc);
8415 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8416 S.Context.getPointerType(To->getType()),
8417 VK_RValue, OK_Ordinary, Loc);
8418
8419 const Type *E = T->getBaseElementTypeUnsafe();
8420 bool NeedsCollectableMemCpy =
8421 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8422
8423 // Create a reference to the __builtin_objc_memmove_collectable function
8424 StringRef MemCpyName = NeedsCollectableMemCpy ?
8425 "__builtin_objc_memmove_collectable" :
8426 "__builtin_memcpy";
8427 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8428 Sema::LookupOrdinaryName);
8429 S.LookupName(R, S.TUScope, true);
8430
8431 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8432 if (!MemCpy)
8433 // Something went horribly wrong earlier, and we will have complained
8434 // about it.
8435 return StmtError();
8436
8437 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8438 VK_RValue, Loc, 0);
8439 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8440
8441 Expr *CallArgs[] = {
8442 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8443 };
8444 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8445 Loc, CallArgs, Loc);
8446
8447 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8448 return S.Owned(Call.takeAs<Stmt>());
8449}
8450
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008451/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008452/// \c To.
8453///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008454/// This routine is used to copy/move the members of a class with an
8455/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008456/// copied are arrays, this routine builds for loops to copy them.
8457///
8458/// \param S The Sema object used for type-checking.
8459///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008460/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008461///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008462/// \param T The type of the expressions being copied/moved. Both expressions
8463/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008464///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008465/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008466///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008467/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008468///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008469/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008470/// Otherwise, it's a non-static member subobject.
8471///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008472/// \param Copying Whether we're copying or moving.
8473///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008474/// \param Depth Internal parameter recording the depth of the recursion.
8475///
Richard Smith8c889532012-11-14 00:50:40 +00008476/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8477/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008478static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008479buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8480 Expr *To, Expr *From,
8481 bool CopyingBaseSubobject, bool Copying,
8482 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008483 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008484 // Each subobject is assigned in the manner appropriate to its type:
8485 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008486 // - if the subobject is of class type, as if by a call to operator= with
8487 // the subobject as the object expression and the corresponding
8488 // subobject of x as a single function argument (as if by explicit
8489 // qualification; that is, ignoring any possible virtual overriding
8490 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008491 //
8492 // C++03 [class.copy]p13:
8493 // - if the subobject is of class type, the copy assignment operator for
8494 // the class is used (as if by explicit qualification; that is,
8495 // ignoring any possible virtual overriding functions in more derived
8496 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008497 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8498 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008499
Douglas Gregor06a9f362010-05-01 20:49:11 +00008500 // Look for operator=.
8501 DeclarationName Name
8502 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8503 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8504 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008505
Richard Smith044c8aa2012-11-13 00:54:12 +00008506 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8507 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008508 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008509 LookupResult::Filter F = OpLookup.makeFilter();
8510 while (F.hasNext()) {
8511 NamedDecl *D = F.next();
8512 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8513 if (Method->isCopyAssignmentOperator() ||
8514 (!Copying && Method->isMoveAssignmentOperator()))
8515 continue;
8516
8517 F.erase();
8518 }
8519 F.done();
John McCallb0207482010-03-16 06:11:48 +00008520 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008521
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008522 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008523 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008524 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008525 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008526 // ambiguities), we need to cast "this" to that subobject type; to
8527 // ensure that we don't go through the virtual call mechanism, we need
8528 // to qualify the operator= name with the base class (see below). However,
8529 // this means that if the base class has a protected copy assignment
8530 // operator, the protected member access check will fail. So, we
8531 // rewrite "protected" access to "public" access in this case, since we
8532 // know by construction that we're calling from a derived class.
8533 if (CopyingBaseSubobject) {
8534 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8535 L != LEnd; ++L) {
8536 if (L.getAccess() == AS_protected)
8537 L.setAccess(AS_public);
8538 }
8539 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008540
Douglas Gregor06a9f362010-05-01 20:49:11 +00008541 // Create the nested-name-specifier that will be used to qualify the
8542 // reference to operator=; this is required to suppress the virtual
8543 // call mechanism.
8544 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008545 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008546 SS.MakeTrivial(S.Context,
8547 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008548 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008549 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008550
Douglas Gregor06a9f362010-05-01 20:49:11 +00008551 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008552 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008553 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008554 /*TemplateKWLoc=*/SourceLocation(),
8555 /*FirstQualifierInScope=*/0,
8556 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008557 /*TemplateArgs=*/0,
8558 /*SuppressQualifierCheck=*/true);
8559 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008560 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008561
Douglas Gregor06a9f362010-05-01 20:49:11 +00008562 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008563
Richard Smith044c8aa2012-11-13 00:54:12 +00008564 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008565 OpEqualRef.takeAs<Expr>(),
8566 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008567 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008568 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008569
Richard Smith8c889532012-11-14 00:50:40 +00008570 // If we built a call to a trivial 'operator=' while copying an array,
8571 // bail out. We'll replace the whole shebang with a memcpy.
8572 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8573 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8574 return StmtResult((Stmt*)0);
8575
Richard Smith044c8aa2012-11-13 00:54:12 +00008576 // Convert to an expression-statement, and clean up any produced
8577 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008578 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008579 }
John McCallb0207482010-03-16 06:11:48 +00008580
Richard Smith044c8aa2012-11-13 00:54:12 +00008581 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008582 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008583 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008584 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008585 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008586 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008587 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008588 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008589 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008590
8591 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008592 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008593
Douglas Gregor06a9f362010-05-01 20:49:11 +00008594 // Construct a loop over the array bounds, e.g.,
8595 //
8596 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8597 //
8598 // that will copy each of the array elements.
8599 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008600
Douglas Gregor06a9f362010-05-01 20:49:11 +00008601 // Create the iteration variable.
8602 IdentifierInfo *IterationVarName = 0;
8603 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008604 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008605 llvm::raw_svector_ostream OS(Str);
8606 OS << "__i" << Depth;
8607 IterationVarName = &S.Context.Idents.get(OS.str());
8608 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008609 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008610 IterationVarName, SizeType,
8611 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008612 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008613
Douglas Gregor06a9f362010-05-01 20:49:11 +00008614 // Initialize the iteration variable to zero.
8615 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008616 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008617
8618 // Create a reference to the iteration variable; we'll use this several
8619 // times throughout.
8620 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008621 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008622 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008623 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8624 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8625
Douglas Gregor06a9f362010-05-01 20:49:11 +00008626 // Create the DeclStmt that holds the iteration variable.
8627 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008628
Douglas Gregor06a9f362010-05-01 20:49:11 +00008629 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008630 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008631 IterationVarRefRVal,
8632 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008633 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008634 IterationVarRefRVal,
8635 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008636 if (!Copying) // Cast to rvalue
8637 From = CastForMoving(S, From);
8638
8639 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008640 StmtResult Copy =
8641 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8642 To, From, CopyingBaseSubobject,
8643 Copying, Depth + 1);
8644 // Bail out if copying fails or if we determined that we should use memcpy.
8645 if (Copy.isInvalid() || !Copy.get())
8646 return Copy;
8647
8648 // Create the comparison against the array bound.
8649 llvm::APInt Upper
8650 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8651 Expr *Comparison
8652 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8653 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8654 BO_NE, S.Context.BoolTy,
8655 VK_RValue, OK_Ordinary, Loc, false);
8656
8657 // Create the pre-increment of the iteration variable.
8658 Expr *Increment
8659 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8660 VK_LValue, OK_Ordinary, Loc);
8661
Douglas Gregor06a9f362010-05-01 20:49:11 +00008662 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008663 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008664 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008665 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008666 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008667}
8668
Richard Smith8c889532012-11-14 00:50:40 +00008669static StmtResult
8670buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8671 Expr *To, Expr *From,
8672 bool CopyingBaseSubobject, bool Copying) {
8673 // Maybe we should use a memcpy?
8674 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8675 T.isTriviallyCopyableType(S.Context))
8676 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8677
8678 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8679 CopyingBaseSubobject,
8680 Copying, 0));
8681
8682 // If we ended up picking a trivial assignment operator for an array of a
8683 // non-trivially-copyable class type, just emit a memcpy.
8684 if (!Result.isInvalid() && !Result.get())
8685 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8686
8687 return Result;
8688}
8689
Richard Smithb9d0b762012-07-27 04:22:15 +00008690Sema::ImplicitExceptionSpecification
8691Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8692 CXXRecordDecl *ClassDecl = MD->getParent();
8693
8694 ImplicitExceptionSpecification ExceptSpec(*this);
8695 if (ClassDecl->isInvalidDecl())
8696 return ExceptSpec;
8697
8698 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8699 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8700 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8701
Douglas Gregorb87786f2010-07-01 17:48:08 +00008702 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008703 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008704 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008705
8706 // It is unspecified whether or not an implicit copy assignment operator
8707 // attempts to deduplicate calls to assignment operators of virtual bases are
8708 // made. As such, this exception specification is effectively unspecified.
8709 // Based on a similar decision made for constness in C++0x, we're erring on
8710 // the side of assuming such calls to be made regardless of whether they
8711 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008712 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8713 BaseEnd = ClassDecl->bases_end();
8714 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008715 if (Base->isVirtual())
8716 continue;
8717
Douglas Gregora376d102010-07-02 21:50:04 +00008718 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008719 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008720 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8721 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008722 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008723 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008724
8725 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8726 BaseEnd = ClassDecl->vbases_end();
8727 Base != BaseEnd; ++Base) {
8728 CXXRecordDecl *BaseClassDecl
8729 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8730 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8731 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008732 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008733 }
8734
Douglas Gregorb87786f2010-07-01 17:48:08 +00008735 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8736 FieldEnd = ClassDecl->field_end();
8737 Field != FieldEnd;
8738 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008739 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008740 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8741 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008742 LookupCopyingAssignment(FieldClassDecl,
8743 ArgQuals | FieldType.getCVRQualifiers(),
8744 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008745 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008746 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008747 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008748
Richard Smithb9d0b762012-07-27 04:22:15 +00008749 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008750}
8751
8752CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8753 // Note: The following rules are largely analoguous to the copy
8754 // constructor rules. Note that virtual bases are not taken into account
8755 // for determining the argument type of the operator. Note also that
8756 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008757 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008758
Richard Smithafb49182012-11-29 01:34:07 +00008759 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8760 if (DSM.isAlreadyBeingDeclared())
8761 return 0;
8762
Sean Hunt30de05c2011-05-14 05:23:20 +00008763 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8764 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008765 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008766 ArgType = ArgType.withConst();
8767 ArgType = Context.getLValueReferenceType(ArgType);
8768
Douglas Gregord3c35902010-07-01 16:36:15 +00008769 // An implicitly-declared copy assignment operator is an inline public
8770 // member of its class.
8771 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008772 SourceLocation ClassLoc = ClassDecl->getLocation();
8773 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008774 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008775 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008776 /*TInfo=*/0,
8777 /*StorageClass=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008778 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008779 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008780 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008781 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008782 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008783
8784 // Build an exception specification pointing back at this member.
8785 FunctionProtoType::ExtProtoInfo EPI;
8786 EPI.ExceptionSpecType = EST_Unevaluated;
8787 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008788 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008789
Douglas Gregord3c35902010-07-01 16:36:15 +00008790 // Add the parameter to the operator.
8791 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008792 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008793 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008794 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008795 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008796
Richard Smithbc2a35d2012-12-08 08:32:28 +00008797 AddOverriddenMethods(ClassDecl, CopyAssignment);
8798
8799 CopyAssignment->setTrivial(
8800 ClassDecl->needsOverloadResolutionForCopyAssignment()
8801 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8802 : ClassDecl->hasTrivialCopyAssignment());
8803
Nico Weberafcc96a2012-01-23 03:19:29 +00008804 // C++0x [class.copy]p19:
8805 // .... If the class definition does not explicitly declare a copy
8806 // assignment operator, there is no user-declared move constructor, and
8807 // there is no user-declared move assignment operator, a copy assignment
8808 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008809 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008810 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008811
Richard Smithbc2a35d2012-12-08 08:32:28 +00008812 // Note that we have added this copy-assignment operator.
8813 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8814
8815 if (Scope *S = getScopeForContext(ClassDecl))
8816 PushOnScopeChains(CopyAssignment, S, false);
8817 ClassDecl->addDecl(CopyAssignment);
8818
Douglas Gregord3c35902010-07-01 16:36:15 +00008819 return CopyAssignment;
8820}
8821
Douglas Gregor06a9f362010-05-01 20:49:11 +00008822void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8823 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008824 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008825 CopyAssignOperator->isOverloadedOperator() &&
8826 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008827 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8828 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008829 "DefineImplicitCopyAssignment called for wrong function");
8830
8831 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8832
8833 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8834 CopyAssignOperator->setInvalidDecl();
8835 return;
8836 }
8837
8838 CopyAssignOperator->setUsed();
8839
Eli Friedman9a14db32012-10-18 20:14:08 +00008840 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008841 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008842
8843 // C++0x [class.copy]p30:
8844 // The implicitly-defined or explicitly-defaulted copy assignment operator
8845 // for a non-union class X performs memberwise copy assignment of its
8846 // subobjects. The direct base classes of X are assigned first, in the
8847 // order of their declaration in the base-specifier-list, and then the
8848 // immediate non-static data members of X are assigned, in the order in
8849 // which they were declared in the class definition.
8850
8851 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008852 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008853
8854 // The parameter for the "other" object, which we are copying from.
8855 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8856 Qualifiers OtherQuals = Other->getType().getQualifiers();
8857 QualType OtherRefType = Other->getType();
8858 if (const LValueReferenceType *OtherRef
8859 = OtherRefType->getAs<LValueReferenceType>()) {
8860 OtherRefType = OtherRef->getPointeeType();
8861 OtherQuals = OtherRefType.getQualifiers();
8862 }
8863
8864 // Our location for everything implicitly-generated.
8865 SourceLocation Loc = CopyAssignOperator->getLocation();
8866
8867 // Construct a reference to the "other" object. We'll be using this
8868 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008869 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008870 assert(OtherRef && "Reference to parameter cannot fail!");
8871
8872 // Construct the "this" pointer. We'll be using this throughout the generated
8873 // ASTs.
8874 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8875 assert(This && "Reference to this cannot fail!");
8876
8877 // Assign base classes.
8878 bool Invalid = false;
8879 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8880 E = ClassDecl->bases_end(); Base != E; ++Base) {
8881 // Form the assignment:
8882 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8883 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008884 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008885 Invalid = true;
8886 continue;
8887 }
8888
John McCallf871d0c2010-08-07 06:22:56 +00008889 CXXCastPath BasePath;
8890 BasePath.push_back(Base);
8891
Douglas Gregor06a9f362010-05-01 20:49:11 +00008892 // Construct the "from" expression, which is an implicit cast to the
8893 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008894 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008895 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8896 CK_UncheckedDerivedToBase,
8897 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008898
8899 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008900 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008901
8902 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008903 To = ImpCastExprToType(To.take(),
8904 Context.getCVRQualifiedType(BaseType,
8905 CopyAssignOperator->getTypeQualifiers()),
8906 CK_UncheckedDerivedToBase,
8907 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008908
8909 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008910 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008911 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008912 /*CopyingBaseSubobject=*/true,
8913 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008914 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008915 Diag(CurrentLocation, diag::note_member_synthesized_at)
8916 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8917 CopyAssignOperator->setInvalidDecl();
8918 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008919 }
8920
8921 // Success! Record the copy.
8922 Statements.push_back(Copy.takeAs<Expr>());
8923 }
8924
Douglas Gregor06a9f362010-05-01 20:49:11 +00008925 // Assign non-static members.
8926 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8927 FieldEnd = ClassDecl->field_end();
8928 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008929 if (Field->isUnnamedBitfield())
8930 continue;
8931
Douglas Gregor06a9f362010-05-01 20:49:11 +00008932 // Check for members of reference type; we can't copy those.
8933 if (Field->getType()->isReferenceType()) {
8934 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8935 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8936 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008937 Diag(CurrentLocation, diag::note_member_synthesized_at)
8938 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008939 Invalid = true;
8940 continue;
8941 }
8942
8943 // Check for members of const-qualified, non-class type.
8944 QualType BaseType = Context.getBaseElementType(Field->getType());
8945 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8946 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8947 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8948 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008949 Diag(CurrentLocation, diag::note_member_synthesized_at)
8950 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008951 Invalid = true;
8952 continue;
8953 }
John McCallb77115d2011-06-17 00:18:42 +00008954
8955 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008956 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8957 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008958
8959 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008960 if (FieldType->isIncompleteArrayType()) {
8961 assert(ClassDecl->hasFlexibleArrayMember() &&
8962 "Incomplete array type is not valid");
8963 continue;
8964 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008965
8966 // Build references to the field in the object we're copying from and to.
8967 CXXScopeSpec SS; // Intentionally empty
8968 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8969 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008970 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008971 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008972 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008973 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008974 SS, SourceLocation(), 0,
8975 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008976 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008977 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008978 SS, SourceLocation(), 0,
8979 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008980 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8981 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008982
Douglas Gregor06a9f362010-05-01 20:49:11 +00008983 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008984 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008985 To.get(), From.get(),
8986 /*CopyingBaseSubobject=*/false,
8987 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008988 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008989 Diag(CurrentLocation, diag::note_member_synthesized_at)
8990 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8991 CopyAssignOperator->setInvalidDecl();
8992 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008993 }
8994
8995 // Success! Record the copy.
8996 Statements.push_back(Copy.takeAs<Stmt>());
8997 }
8998
8999 if (!Invalid) {
9000 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00009001 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009002
John McCall60d7b3a2010-08-24 06:29:42 +00009003 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009004 if (Return.isInvalid())
9005 Invalid = true;
9006 else {
9007 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009008
9009 if (Trap.hasErrorOccurred()) {
9010 Diag(CurrentLocation, diag::note_member_synthesized_at)
9011 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9012 Invalid = true;
9013 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009014 }
9015 }
9016
9017 if (Invalid) {
9018 CopyAssignOperator->setInvalidDecl();
9019 return;
9020 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009021
9022 StmtResult Body;
9023 {
9024 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009025 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009026 /*isStmtExpr=*/false);
9027 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9028 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009029 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009030
9031 if (ASTMutationListener *L = getASTMutationListener()) {
9032 L->CompletedImplicitDefinition(CopyAssignOperator);
9033 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009034}
9035
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009036Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009037Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9038 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009039
Richard Smithb9d0b762012-07-27 04:22:15 +00009040 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009041 if (ClassDecl->isInvalidDecl())
9042 return ExceptSpec;
9043
9044 // C++0x [except.spec]p14:
9045 // An implicitly declared special member function (Clause 12) shall have an
9046 // exception-specification. [...]
9047
9048 // It is unspecified whether or not an implicit move assignment operator
9049 // attempts to deduplicate calls to assignment operators of virtual bases are
9050 // made. As such, this exception specification is effectively unspecified.
9051 // Based on a similar decision made for constness in C++0x, we're erring on
9052 // the side of assuming such calls to be made regardless of whether they
9053 // actually happen.
9054 // Note that a move constructor is not implicitly declared when there are
9055 // virtual bases, but it can still be user-declared and explicitly defaulted.
9056 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9057 BaseEnd = ClassDecl->bases_end();
9058 Base != BaseEnd; ++Base) {
9059 if (Base->isVirtual())
9060 continue;
9061
9062 CXXRecordDecl *BaseClassDecl
9063 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9064 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009065 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009066 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009067 }
9068
9069 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9070 BaseEnd = ClassDecl->vbases_end();
9071 Base != BaseEnd; ++Base) {
9072 CXXRecordDecl *BaseClassDecl
9073 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9074 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009075 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009076 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009077 }
9078
9079 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9080 FieldEnd = ClassDecl->field_end();
9081 Field != FieldEnd;
9082 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009083 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009084 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009085 if (CXXMethodDecl *MoveAssign =
9086 LookupMovingAssignment(FieldClassDecl,
9087 FieldType.getCVRQualifiers(),
9088 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009089 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009090 }
9091 }
9092
9093 return ExceptSpec;
9094}
9095
Richard Smith1c931be2012-04-02 18:40:40 +00009096/// Determine whether the class type has any direct or indirect virtual base
9097/// classes which have a non-trivial move assignment operator.
9098static bool
9099hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9100 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9101 BaseEnd = ClassDecl->vbases_end();
9102 Base != BaseEnd; ++Base) {
9103 CXXRecordDecl *BaseClass =
9104 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9105
9106 // Try to declare the move assignment. If it would be deleted, then the
9107 // class does not have a non-trivial move assignment.
9108 if (BaseClass->needsImplicitMoveAssignment())
9109 S.DeclareImplicitMoveAssignment(BaseClass);
9110
Richard Smith426391c2012-11-16 00:53:38 +00009111 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009112 return true;
9113 }
9114
9115 return false;
9116}
9117
9118/// Determine whether the given type either has a move constructor or is
9119/// trivially copyable.
9120static bool
9121hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9122 Type = S.Context.getBaseElementType(Type);
9123
9124 // FIXME: Technically, non-trivially-copyable non-class types, such as
9125 // reference types, are supposed to return false here, but that appears
9126 // to be a standard defect.
9127 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009128 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009129 return true;
9130
9131 if (Type.isTriviallyCopyableType(S.Context))
9132 return true;
9133
9134 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009135 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9136 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009137 if (ClassDecl->needsImplicitMoveConstructor())
9138 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009139 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009140 }
9141
Richard Smithe5411b72012-12-01 02:35:44 +00009142 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9143 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009144 if (ClassDecl->needsImplicitMoveAssignment())
9145 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009146 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009147}
9148
9149/// Determine whether all non-static data members and direct or virtual bases
9150/// of class \p ClassDecl have either a move operation, or are trivially
9151/// copyable.
9152static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9153 bool IsConstructor) {
9154 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9155 BaseEnd = ClassDecl->bases_end();
9156 Base != BaseEnd; ++Base) {
9157 if (Base->isVirtual())
9158 continue;
9159
9160 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9161 return false;
9162 }
9163
9164 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9165 BaseEnd = ClassDecl->vbases_end();
9166 Base != BaseEnd; ++Base) {
9167 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9168 return false;
9169 }
9170
9171 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9172 FieldEnd = ClassDecl->field_end();
9173 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009174 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009175 return false;
9176 }
9177
9178 return true;
9179}
9180
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009181CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009182 // C++11 [class.copy]p20:
9183 // If the definition of a class X does not explicitly declare a move
9184 // assignment operator, one will be implicitly declared as defaulted
9185 // if and only if:
9186 //
9187 // - [first 4 bullets]
9188 assert(ClassDecl->needsImplicitMoveAssignment());
9189
Richard Smithafb49182012-11-29 01:34:07 +00009190 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9191 if (DSM.isAlreadyBeingDeclared())
9192 return 0;
9193
Richard Smith1c931be2012-04-02 18:40:40 +00009194 // [Checked after we build the declaration]
9195 // - the move assignment operator would not be implicitly defined as
9196 // deleted,
9197
9198 // [DR1402]:
9199 // - X has no direct or indirect virtual base class with a non-trivial
9200 // move assignment operator, and
9201 // - each of X's non-static data members and direct or virtual base classes
9202 // has a type that either has a move assignment operator or is trivially
9203 // copyable.
9204 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9205 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9206 ClassDecl->setFailedImplicitMoveAssignment();
9207 return 0;
9208 }
9209
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009210 // Note: The following rules are largely analoguous to the move
9211 // constructor rules.
9212
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009213 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9214 QualType RetType = Context.getLValueReferenceType(ArgType);
9215 ArgType = Context.getRValueReferenceType(ArgType);
9216
9217 // An implicitly-declared move assignment operator is an inline public
9218 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009219 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9220 SourceLocation ClassLoc = ClassDecl->getLocation();
9221 DeclarationNameInfo NameInfo(Name, ClassLoc);
9222 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00009223 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009224 /*TInfo=*/0,
9225 /*StorageClass=*/SC_None,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009226 /*isInline=*/true,
9227 /*isConstexpr=*/false,
9228 SourceLocation());
9229 MoveAssignment->setAccess(AS_public);
9230 MoveAssignment->setDefaulted();
9231 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009232
Richard Smithb9d0b762012-07-27 04:22:15 +00009233 // Build an exception specification pointing back at this member.
9234 FunctionProtoType::ExtProtoInfo EPI;
9235 EPI.ExceptionSpecType = EST_Unevaluated;
9236 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009237 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009238
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009239 // Add the parameter to the operator.
9240 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9241 ClassLoc, ClassLoc, /*Id=*/0,
9242 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009243 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009244 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009245
Richard Smithbc2a35d2012-12-08 08:32:28 +00009246 AddOverriddenMethods(ClassDecl, MoveAssignment);
9247
9248 MoveAssignment->setTrivial(
9249 ClassDecl->needsOverloadResolutionForMoveAssignment()
9250 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9251 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009252
9253 // C++0x [class.copy]p9:
9254 // If the definition of a class X does not explicitly declare a move
9255 // assignment operator, one will be implicitly declared as defaulted if and
9256 // only if:
9257 // [...]
9258 // - the move assignment operator would not be implicitly defined as
9259 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009260 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009261 // Cache this result so that we don't try to generate this over and over
9262 // on every lookup, leaking memory and wasting time.
9263 ClassDecl->setFailedImplicitMoveAssignment();
9264 return 0;
9265 }
9266
Richard Smithbc2a35d2012-12-08 08:32:28 +00009267 // Note that we have added this copy-assignment operator.
9268 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9269
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009270 if (Scope *S = getScopeForContext(ClassDecl))
9271 PushOnScopeChains(MoveAssignment, S, false);
9272 ClassDecl->addDecl(MoveAssignment);
9273
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009274 return MoveAssignment;
9275}
9276
9277void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9278 CXXMethodDecl *MoveAssignOperator) {
9279 assert((MoveAssignOperator->isDefaulted() &&
9280 MoveAssignOperator->isOverloadedOperator() &&
9281 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009282 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9283 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009284 "DefineImplicitMoveAssignment called for wrong function");
9285
9286 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9287
9288 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9289 MoveAssignOperator->setInvalidDecl();
9290 return;
9291 }
9292
9293 MoveAssignOperator->setUsed();
9294
Eli Friedman9a14db32012-10-18 20:14:08 +00009295 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009296 DiagnosticErrorTrap Trap(Diags);
9297
9298 // C++0x [class.copy]p28:
9299 // The implicitly-defined or move assignment operator for a non-union class
9300 // X performs memberwise move assignment of its subobjects. The direct base
9301 // classes of X are assigned first, in the order of their declaration in the
9302 // base-specifier-list, and then the immediate non-static data members of X
9303 // are assigned, in the order in which they were declared in the class
9304 // definition.
9305
9306 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009307 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009308
9309 // The parameter for the "other" object, which we are move from.
9310 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9311 QualType OtherRefType = Other->getType()->
9312 getAs<RValueReferenceType>()->getPointeeType();
9313 assert(OtherRefType.getQualifiers() == 0 &&
9314 "Bad argument type of defaulted move assignment");
9315
9316 // Our location for everything implicitly-generated.
9317 SourceLocation Loc = MoveAssignOperator->getLocation();
9318
9319 // Construct a reference to the "other" object. We'll be using this
9320 // throughout the generated ASTs.
9321 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9322 assert(OtherRef && "Reference to parameter cannot fail!");
9323 // Cast to rvalue.
9324 OtherRef = CastForMoving(*this, OtherRef);
9325
9326 // Construct the "this" pointer. We'll be using this throughout the generated
9327 // ASTs.
9328 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9329 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009330
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009331 // Assign base classes.
9332 bool Invalid = false;
9333 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9334 E = ClassDecl->bases_end(); Base != E; ++Base) {
9335 // Form the assignment:
9336 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9337 QualType BaseType = Base->getType().getUnqualifiedType();
9338 if (!BaseType->isRecordType()) {
9339 Invalid = true;
9340 continue;
9341 }
9342
9343 CXXCastPath BasePath;
9344 BasePath.push_back(Base);
9345
9346 // Construct the "from" expression, which is an implicit cast to the
9347 // appropriately-qualified base type.
9348 Expr *From = OtherRef;
9349 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009350 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009351
9352 // Dereference "this".
9353 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9354
9355 // Implicitly cast "this" to the appropriately-qualified base type.
9356 To = ImpCastExprToType(To.take(),
9357 Context.getCVRQualifiedType(BaseType,
9358 MoveAssignOperator->getTypeQualifiers()),
9359 CK_UncheckedDerivedToBase,
9360 VK_LValue, &BasePath);
9361
9362 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009363 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009364 To.get(), From,
9365 /*CopyingBaseSubobject=*/true,
9366 /*Copying=*/false);
9367 if (Move.isInvalid()) {
9368 Diag(CurrentLocation, diag::note_member_synthesized_at)
9369 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9370 MoveAssignOperator->setInvalidDecl();
9371 return;
9372 }
9373
9374 // Success! Record the move.
9375 Statements.push_back(Move.takeAs<Expr>());
9376 }
9377
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009378 // Assign non-static members.
9379 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9380 FieldEnd = ClassDecl->field_end();
9381 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009382 if (Field->isUnnamedBitfield())
9383 continue;
9384
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009385 // Check for members of reference type; we can't move those.
9386 if (Field->getType()->isReferenceType()) {
9387 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9388 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9389 Diag(Field->getLocation(), diag::note_declared_at);
9390 Diag(CurrentLocation, diag::note_member_synthesized_at)
9391 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9392 Invalid = true;
9393 continue;
9394 }
9395
9396 // Check for members of const-qualified, non-class type.
9397 QualType BaseType = Context.getBaseElementType(Field->getType());
9398 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9399 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9400 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9401 Diag(Field->getLocation(), diag::note_declared_at);
9402 Diag(CurrentLocation, diag::note_member_synthesized_at)
9403 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9404 Invalid = true;
9405 continue;
9406 }
9407
9408 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009409 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9410 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009411
9412 QualType FieldType = Field->getType().getNonReferenceType();
9413 if (FieldType->isIncompleteArrayType()) {
9414 assert(ClassDecl->hasFlexibleArrayMember() &&
9415 "Incomplete array type is not valid");
9416 continue;
9417 }
9418
9419 // Build references to the field in the object we're copying from and to.
9420 CXXScopeSpec SS; // Intentionally empty
9421 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9422 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009423 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009424 MemberLookup.resolveKind();
9425 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9426 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009427 SS, SourceLocation(), 0,
9428 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009429 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9430 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009431 SS, SourceLocation(), 0,
9432 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009433 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9434 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9435
9436 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9437 "Member reference with rvalue base must be rvalue except for reference "
9438 "members, which aren't allowed for move assignment.");
9439
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009440 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009441 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009442 To.get(), From.get(),
9443 /*CopyingBaseSubobject=*/false,
9444 /*Copying=*/false);
9445 if (Move.isInvalid()) {
9446 Diag(CurrentLocation, diag::note_member_synthesized_at)
9447 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9448 MoveAssignOperator->setInvalidDecl();
9449 return;
9450 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009451
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009452 // Success! Record the copy.
9453 Statements.push_back(Move.takeAs<Stmt>());
9454 }
9455
9456 if (!Invalid) {
9457 // Add a "return *this;"
9458 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9459
9460 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9461 if (Return.isInvalid())
9462 Invalid = true;
9463 else {
9464 Statements.push_back(Return.takeAs<Stmt>());
9465
9466 if (Trap.hasErrorOccurred()) {
9467 Diag(CurrentLocation, diag::note_member_synthesized_at)
9468 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9469 Invalid = true;
9470 }
9471 }
9472 }
9473
9474 if (Invalid) {
9475 MoveAssignOperator->setInvalidDecl();
9476 return;
9477 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009478
9479 StmtResult Body;
9480 {
9481 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009482 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009483 /*isStmtExpr=*/false);
9484 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9485 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009486 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9487
9488 if (ASTMutationListener *L = getASTMutationListener()) {
9489 L->CompletedImplicitDefinition(MoveAssignOperator);
9490 }
9491}
9492
Richard Smithb9d0b762012-07-27 04:22:15 +00009493Sema::ImplicitExceptionSpecification
9494Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9495 CXXRecordDecl *ClassDecl = MD->getParent();
9496
9497 ImplicitExceptionSpecification ExceptSpec(*this);
9498 if (ClassDecl->isInvalidDecl())
9499 return ExceptSpec;
9500
9501 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9502 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9503 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9504
Douglas Gregor0d405db2010-07-01 20:59:04 +00009505 // C++ [except.spec]p14:
9506 // An implicitly declared special member function (Clause 12) shall have an
9507 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009508 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9509 BaseEnd = ClassDecl->bases_end();
9510 Base != BaseEnd;
9511 ++Base) {
9512 // Virtual bases are handled below.
9513 if (Base->isVirtual())
9514 continue;
9515
Douglas Gregor22584312010-07-02 23:41:54 +00009516 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009517 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009518 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009519 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009520 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009521 }
9522 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9523 BaseEnd = ClassDecl->vbases_end();
9524 Base != BaseEnd;
9525 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009526 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009527 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009528 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009529 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009530 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009531 }
9532 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9533 FieldEnd = ClassDecl->field_end();
9534 Field != FieldEnd;
9535 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009536 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009537 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9538 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009539 LookupCopyingConstructor(FieldClassDecl,
9540 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009541 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009542 }
9543 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009544
Richard Smithb9d0b762012-07-27 04:22:15 +00009545 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009546}
9547
9548CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9549 CXXRecordDecl *ClassDecl) {
9550 // C++ [class.copy]p4:
9551 // If the class definition does not explicitly declare a copy
9552 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009553 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009554
Richard Smithafb49182012-11-29 01:34:07 +00009555 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9556 if (DSM.isAlreadyBeingDeclared())
9557 return 0;
9558
Sean Hunt49634cf2011-05-13 06:10:58 +00009559 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9560 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009561 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009562 if (Const)
9563 ArgType = ArgType.withConst();
9564 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009565
Richard Smith7756afa2012-06-10 05:43:50 +00009566 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9567 CXXCopyConstructor,
9568 Const);
9569
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009570 DeclarationName Name
9571 = Context.DeclarationNames.getCXXConstructorName(
9572 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009573 SourceLocation ClassLoc = ClassDecl->getLocation();
9574 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009575
9576 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009577 // member of its class.
9578 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009579 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009580 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009581 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009582 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009583 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009584
Richard Smithb9d0b762012-07-27 04:22:15 +00009585 // Build an exception specification pointing back at this member.
9586 FunctionProtoType::ExtProtoInfo EPI;
9587 EPI.ExceptionSpecType = EST_Unevaluated;
9588 EPI.ExceptionSpecDecl = CopyConstructor;
9589 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009590 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009591
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009592 // Add the parameter to the constructor.
9593 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009594 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009595 /*IdentifierInfo=*/0,
9596 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009597 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009598 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009599
Richard Smithbc2a35d2012-12-08 08:32:28 +00009600 CopyConstructor->setTrivial(
9601 ClassDecl->needsOverloadResolutionForCopyConstructor()
9602 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9603 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009604
Nico Weberafcc96a2012-01-23 03:19:29 +00009605 // C++11 [class.copy]p8:
9606 // ... If the class definition does not explicitly declare a copy
9607 // constructor, there is no user-declared move constructor, and there is no
9608 // user-declared move assignment operator, a copy constructor is implicitly
9609 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009610 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009611 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009612
Richard Smithbc2a35d2012-12-08 08:32:28 +00009613 // Note that we have declared this constructor.
9614 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9615
9616 if (Scope *S = getScopeForContext(ClassDecl))
9617 PushOnScopeChains(CopyConstructor, S, false);
9618 ClassDecl->addDecl(CopyConstructor);
9619
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009620 return CopyConstructor;
9621}
9622
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009623void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009624 CXXConstructorDecl *CopyConstructor) {
9625 assert((CopyConstructor->isDefaulted() &&
9626 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009627 !CopyConstructor->doesThisDeclarationHaveABody() &&
9628 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009629 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009630
Anders Carlsson63010a72010-04-23 16:24:12 +00009631 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009632 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009633
Eli Friedman9a14db32012-10-18 20:14:08 +00009634 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009635 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009636
David Blaikie93c86172013-01-17 05:26:25 +00009637 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009638 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009639 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009640 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009641 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009642 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009643 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009644 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9645 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009646 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009647 /*isStmtExpr=*/false)
9648 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009649 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009650 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009651
9652 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009653 if (ASTMutationListener *L = getASTMutationListener()) {
9654 L->CompletedImplicitDefinition(CopyConstructor);
9655 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009656}
9657
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009658Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009659Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9660 CXXRecordDecl *ClassDecl = MD->getParent();
9661
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009662 // C++ [except.spec]p14:
9663 // An implicitly declared special member function (Clause 12) shall have an
9664 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009665 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009666 if (ClassDecl->isInvalidDecl())
9667 return ExceptSpec;
9668
9669 // Direct base-class constructors.
9670 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9671 BEnd = ClassDecl->bases_end();
9672 B != BEnd; ++B) {
9673 if (B->isVirtual()) // Handled below.
9674 continue;
9675
9676 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9677 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009678 CXXConstructorDecl *Constructor =
9679 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009680 // If this is a deleted function, add it anyway. This might be conformant
9681 // with the standard. This might not. I'm not sure. It might not matter.
9682 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009683 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009684 }
9685 }
9686
9687 // Virtual base-class constructors.
9688 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9689 BEnd = ClassDecl->vbases_end();
9690 B != BEnd; ++B) {
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 // Field constructors.
9703 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9704 FEnd = ClassDecl->field_end();
9705 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009706 QualType FieldType = Context.getBaseElementType(F->getType());
9707 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9708 CXXConstructorDecl *Constructor =
9709 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
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 // In particular, the problem is that this function never gets called. It
9713 // might just be ill-formed because this function attempts to refer to
9714 // a deleted function here.
9715 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009716 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009717 }
9718 }
9719
9720 return ExceptSpec;
9721}
9722
9723CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9724 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009725 // C++11 [class.copy]p9:
9726 // If the definition of a class X does not explicitly declare a move
9727 // constructor, one will be implicitly declared as defaulted if and only if:
9728 //
9729 // - [first 4 bullets]
9730 assert(ClassDecl->needsImplicitMoveConstructor());
9731
Richard Smithafb49182012-11-29 01:34:07 +00009732 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9733 if (DSM.isAlreadyBeingDeclared())
9734 return 0;
9735
Richard Smith1c931be2012-04-02 18:40:40 +00009736 // [Checked after we build the declaration]
9737 // - the move assignment operator would not be implicitly defined as
9738 // deleted,
9739
9740 // [DR1402]:
9741 // - each of X's non-static data members and direct or virtual base classes
9742 // has a type that either has a move constructor or is trivially copyable.
9743 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9744 ClassDecl->setFailedImplicitMoveConstructor();
9745 return 0;
9746 }
9747
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009748 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9749 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009750
Richard Smith7756afa2012-06-10 05:43:50 +00009751 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9752 CXXMoveConstructor,
9753 false);
9754
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009755 DeclarationName Name
9756 = Context.DeclarationNames.getCXXConstructorName(
9757 Context.getCanonicalType(ClassType));
9758 SourceLocation ClassLoc = ClassDecl->getLocation();
9759 DeclarationNameInfo NameInfo(Name, ClassLoc);
9760
9761 // C++0x [class.copy]p11:
9762 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009763 // member of its class.
9764 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009765 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009766 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009767 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009768 MoveConstructor->setAccess(AS_public);
9769 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009770
Richard Smithb9d0b762012-07-27 04:22:15 +00009771 // Build an exception specification pointing back at this member.
9772 FunctionProtoType::ExtProtoInfo EPI;
9773 EPI.ExceptionSpecType = EST_Unevaluated;
9774 EPI.ExceptionSpecDecl = MoveConstructor;
9775 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009776 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009777
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009778 // Add the parameter to the constructor.
9779 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9780 ClassLoc, ClassLoc,
9781 /*IdentifierInfo=*/0,
9782 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009783 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009784 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009785
Richard Smithbc2a35d2012-12-08 08:32:28 +00009786 MoveConstructor->setTrivial(
9787 ClassDecl->needsOverloadResolutionForMoveConstructor()
9788 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9789 : ClassDecl->hasTrivialMoveConstructor());
9790
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009791 // C++0x [class.copy]p9:
9792 // If the definition of a class X does not explicitly declare a move
9793 // constructor, one will be implicitly declared as defaulted if and only if:
9794 // [...]
9795 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009796 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009797 // Cache this result so that we don't try to generate this over and over
9798 // on every lookup, leaking memory and wasting time.
9799 ClassDecl->setFailedImplicitMoveConstructor();
9800 return 0;
9801 }
9802
9803 // Note that we have declared this constructor.
9804 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9805
9806 if (Scope *S = getScopeForContext(ClassDecl))
9807 PushOnScopeChains(MoveConstructor, S, false);
9808 ClassDecl->addDecl(MoveConstructor);
9809
9810 return MoveConstructor;
9811}
9812
9813void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9814 CXXConstructorDecl *MoveConstructor) {
9815 assert((MoveConstructor->isDefaulted() &&
9816 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009817 !MoveConstructor->doesThisDeclarationHaveABody() &&
9818 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009819 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9820
9821 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9822 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9823
Eli Friedman9a14db32012-10-18 20:14:08 +00009824 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009825 DiagnosticErrorTrap Trap(Diags);
9826
David Blaikie93c86172013-01-17 05:26:25 +00009827 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009828 Trap.hasErrorOccurred()) {
9829 Diag(CurrentLocation, diag::note_member_synthesized_at)
9830 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9831 MoveConstructor->setInvalidDecl();
9832 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009833 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009834 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9835 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009836 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009837 /*isStmtExpr=*/false)
9838 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009839 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009840 }
9841
9842 MoveConstructor->setUsed();
9843
9844 if (ASTMutationListener *L = getASTMutationListener()) {
9845 L->CompletedImplicitDefinition(MoveConstructor);
9846 }
9847}
9848
Douglas Gregore4e68d42012-02-15 19:33:52 +00009849bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9850 return FD->isDeleted() &&
9851 (FD->isDefaulted() || FD->isImplicit()) &&
9852 isa<CXXMethodDecl>(FD);
9853}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009854
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009855/// \brief Mark the call operator of the given lambda closure type as "used".
9856static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9857 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009858 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009859 Lambda->lookup(
9860 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009861 CallOperator->setReferenced();
9862 CallOperator->setUsed();
9863}
9864
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009865void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9866 SourceLocation CurrentLocation,
9867 CXXConversionDecl *Conv)
9868{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009869 CXXRecordDecl *Lambda = Conv->getParent();
9870
9871 // Make sure that the lambda call operator is marked used.
9872 markLambdaCallOperatorUsed(*this, Lambda);
9873
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009874 Conv->setUsed();
9875
Eli Friedman9a14db32012-10-18 20:14:08 +00009876 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009877 DiagnosticErrorTrap Trap(Diags);
9878
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009879 // Return the address of the __invoke function.
9880 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9881 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009882 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009883 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9884 VK_LValue, Conv->getLocation()).take();
9885 assert(FunctionRef && "Can't refer to __invoke function?");
9886 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009887 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009888 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009889 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009890
9891 // Fill in the __invoke function with a dummy implementation. IR generation
9892 // will fill in the actual details.
9893 Invoke->setUsed();
9894 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009895 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009896
9897 if (ASTMutationListener *L = getASTMutationListener()) {
9898 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009899 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009900 }
9901}
9902
9903void Sema::DefineImplicitLambdaToBlockPointerConversion(
9904 SourceLocation CurrentLocation,
9905 CXXConversionDecl *Conv)
9906{
9907 Conv->setUsed();
9908
Eli Friedman9a14db32012-10-18 20:14:08 +00009909 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009910 DiagnosticErrorTrap Trap(Diags);
9911
Douglas Gregorac1303e2012-02-22 05:02:47 +00009912 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009913 Expr *This = ActOnCXXThis(CurrentLocation).take();
9914 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009915
Eli Friedman23f02672012-03-01 04:01:32 +00009916 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9917 Conv->getLocation(),
9918 Conv, DerefThis);
9919
9920 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9921 // behavior. Note that only the general conversion function does this
9922 // (since it's unusable otherwise); in the case where we inline the
9923 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009924 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009925 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9926 CK_CopyAndAutoreleaseBlockObject,
9927 BuildBlock.get(), 0, VK_RValue);
9928
9929 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009930 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009931 Conv->setInvalidDecl();
9932 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009933 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009934
Douglas Gregorac1303e2012-02-22 05:02:47 +00009935 // Create the return statement that returns the block from the conversion
9936 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009937 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009938 if (Return.isInvalid()) {
9939 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9940 Conv->setInvalidDecl();
9941 return;
9942 }
9943
9944 // Set the body of the conversion function.
9945 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009946 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009947 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009948 Conv->getLocation()));
9949
Douglas Gregorac1303e2012-02-22 05:02:47 +00009950 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009951 if (ASTMutationListener *L = getASTMutationListener()) {
9952 L->CompletedImplicitDefinition(Conv);
9953 }
9954}
9955
Douglas Gregorf52757d2012-03-10 06:53:13 +00009956/// \brief Determine whether the given list arguments contains exactly one
9957/// "real" (non-default) argument.
9958static bool hasOneRealArgument(MultiExprArg Args) {
9959 switch (Args.size()) {
9960 case 0:
9961 return false;
9962
9963 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009964 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009965 return false;
9966
9967 // fall through
9968 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009969 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009970 }
9971
9972 return false;
9973}
9974
John McCall60d7b3a2010-08-24 06:29:42 +00009975ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009976Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009977 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009978 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009979 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009980 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009981 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009982 unsigned ConstructKind,
9983 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009984 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009985
Douglas Gregor2f599792010-04-02 18:24:57 +00009986 // C++0x [class.copy]p34:
9987 // When certain criteria are met, an implementation is allowed to
9988 // omit the copy/move construction of a class object, even if the
9989 // copy/move constructor and/or destructor for the object have
9990 // side effects. [...]
9991 // - when a temporary class object that has not been bound to a
9992 // reference (12.2) would be copied/moved to a class object
9993 // with the same cv-unqualified type, the copy/move operation
9994 // can be omitted by constructing the temporary object
9995 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009996 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009997 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009998 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009999 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010000 }
Mike Stump1eb44332009-09-09 15:08:12 +000010001
10002 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010003 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010004 IsListInitialization, RequiresZeroInit,
10005 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010006}
10007
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010008/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10009/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010010ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010011Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10012 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010013 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010014 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010015 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010016 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010017 unsigned ConstructKind,
10018 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010019 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010020 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010021 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010022 HadMultipleCandidates,
10023 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010024 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10025 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010026}
10027
John McCall68c6c9a2010-02-02 09:10:11 +000010028void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010029 if (VD->isInvalidDecl()) return;
10030
John McCall68c6c9a2010-02-02 09:10:11 +000010031 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010032 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010033 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010034 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010035
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010036 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010037 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010038 CheckDestructorAccess(VD->getLocation(), Destructor,
10039 PDiag(diag::err_access_dtor_var)
10040 << VD->getDeclName()
10041 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010042 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010043
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010044 if (!VD->hasGlobalStorage()) return;
10045
10046 // Emit warning for non-trivial dtor in global scope (a real global,
10047 // class-static, function-static).
10048 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10049
10050 // TODO: this should be re-enabled for static locals by !CXAAtExit
10051 if (!VD->isStaticLocal())
10052 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010053}
10054
Douglas Gregor39da0b82009-09-09 23:08:42 +000010055/// \brief Given a constructor and the set of arguments provided for the
10056/// constructor, convert the arguments and add any required default arguments
10057/// to form a proper call to this constructor.
10058///
10059/// \returns true if an error occurred, false otherwise.
10060bool
10061Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10062 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010063 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010064 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010065 bool AllowExplicit,
10066 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010067 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10068 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010069 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010070
10071 const FunctionProtoType *Proto
10072 = Constructor->getType()->getAs<FunctionProtoType>();
10073 assert(Proto && "Constructor without a prototype?");
10074 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010075
10076 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010077 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010078 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010079 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010080 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010081
10082 VariadicCallType CallType =
10083 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010084 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010085 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10086 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010087 CallType, AllowExplicit,
10088 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010089 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010090
10091 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
10092
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010093 CheckConstructorCall(Constructor,
10094 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10095 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010096 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010097
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010098 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010099}
10100
Anders Carlsson20d45d22009-12-12 00:32:00 +000010101static inline bool
10102CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10103 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010104 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010105 if (isa<NamespaceDecl>(DC)) {
10106 return SemaRef.Diag(FnDecl->getLocation(),
10107 diag::err_operator_new_delete_declared_in_namespace)
10108 << FnDecl->getDeclName();
10109 }
10110
10111 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010112 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010113 return SemaRef.Diag(FnDecl->getLocation(),
10114 diag::err_operator_new_delete_declared_static)
10115 << FnDecl->getDeclName();
10116 }
10117
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010118 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010119}
10120
Anders Carlsson156c78e2009-12-13 17:53:43 +000010121static inline bool
10122CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10123 CanQualType ExpectedResultType,
10124 CanQualType ExpectedFirstParamType,
10125 unsigned DependentParamTypeDiag,
10126 unsigned InvalidParamTypeDiag) {
10127 QualType ResultType =
10128 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10129
10130 // Check that the result type is not dependent.
10131 if (ResultType->isDependentType())
10132 return SemaRef.Diag(FnDecl->getLocation(),
10133 diag::err_operator_new_delete_dependent_result_type)
10134 << FnDecl->getDeclName() << ExpectedResultType;
10135
10136 // Check that the result type is what we expect.
10137 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10138 return SemaRef.Diag(FnDecl->getLocation(),
10139 diag::err_operator_new_delete_invalid_result_type)
10140 << FnDecl->getDeclName() << ExpectedResultType;
10141
10142 // A function template must have at least 2 parameters.
10143 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10144 return SemaRef.Diag(FnDecl->getLocation(),
10145 diag::err_operator_new_delete_template_too_few_parameters)
10146 << FnDecl->getDeclName();
10147
10148 // The function decl must have at least 1 parameter.
10149 if (FnDecl->getNumParams() == 0)
10150 return SemaRef.Diag(FnDecl->getLocation(),
10151 diag::err_operator_new_delete_too_few_parameters)
10152 << FnDecl->getDeclName();
10153
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010154 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010155 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10156 if (FirstParamType->isDependentType())
10157 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10158 << FnDecl->getDeclName() << ExpectedFirstParamType;
10159
10160 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010161 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010162 ExpectedFirstParamType)
10163 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10164 << FnDecl->getDeclName() << ExpectedFirstParamType;
10165
10166 return false;
10167}
10168
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010169static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010170CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010171 // C++ [basic.stc.dynamic.allocation]p1:
10172 // A program is ill-formed if an allocation function is declared in a
10173 // namespace scope other than global scope or declared static in global
10174 // scope.
10175 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10176 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010177
10178 CanQualType SizeTy =
10179 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10180
10181 // C++ [basic.stc.dynamic.allocation]p1:
10182 // The return type shall be void*. The first parameter shall have type
10183 // std::size_t.
10184 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10185 SizeTy,
10186 diag::err_operator_new_dependent_param_type,
10187 diag::err_operator_new_param_type))
10188 return true;
10189
10190 // C++ [basic.stc.dynamic.allocation]p1:
10191 // The first parameter shall not have an associated default argument.
10192 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010193 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010194 diag::err_operator_new_default_arg)
10195 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10196
10197 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010198}
10199
10200static bool
Richard Smith444d3842012-10-20 08:26:51 +000010201CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010202 // C++ [basic.stc.dynamic.deallocation]p1:
10203 // A program is ill-formed if deallocation functions are declared in a
10204 // namespace scope other than global scope or declared static in global
10205 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010206 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10207 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010208
10209 // C++ [basic.stc.dynamic.deallocation]p2:
10210 // Each deallocation function shall return void and its first parameter
10211 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010212 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10213 SemaRef.Context.VoidPtrTy,
10214 diag::err_operator_delete_dependent_param_type,
10215 diag::err_operator_delete_param_type))
10216 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010217
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010218 return false;
10219}
10220
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010221/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10222/// of this overloaded operator is well-formed. If so, returns false;
10223/// otherwise, emits appropriate diagnostics and returns true.
10224bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010225 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010226 "Expected an overloaded operator declaration");
10227
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010228 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10229
Mike Stump1eb44332009-09-09 15:08:12 +000010230 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010231 // The allocation and deallocation functions, operator new,
10232 // operator new[], operator delete and operator delete[], are
10233 // described completely in 3.7.3. The attributes and restrictions
10234 // found in the rest of this subclause do not apply to them unless
10235 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010236 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010237 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010238
Anders Carlssona3ccda52009-12-12 00:26:23 +000010239 if (Op == OO_New || Op == OO_Array_New)
10240 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010241
10242 // C++ [over.oper]p6:
10243 // An operator function shall either be a non-static member
10244 // function or be a non-member function and have at least one
10245 // parameter whose type is a class, a reference to a class, an
10246 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010247 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10248 if (MethodDecl->isStatic())
10249 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010250 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010251 } else {
10252 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010253 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10254 ParamEnd = FnDecl->param_end();
10255 Param != ParamEnd; ++Param) {
10256 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010257 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10258 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010259 ClassOrEnumParam = true;
10260 break;
10261 }
10262 }
10263
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010264 if (!ClassOrEnumParam)
10265 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010266 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010267 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010268 }
10269
10270 // C++ [over.oper]p8:
10271 // An operator function cannot have default arguments (8.3.6),
10272 // except where explicitly stated below.
10273 //
Mike Stump1eb44332009-09-09 15:08:12 +000010274 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010275 // (C++ [over.call]p1).
10276 if (Op != OO_Call) {
10277 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10278 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010279 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010280 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010281 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010282 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010283 }
10284 }
10285
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010286 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10287 { false, false, false }
10288#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10289 , { Unary, Binary, MemberOnly }
10290#include "clang/Basic/OperatorKinds.def"
10291 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010292
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010293 bool CanBeUnaryOperator = OperatorUses[Op][0];
10294 bool CanBeBinaryOperator = OperatorUses[Op][1];
10295 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010296
10297 // C++ [over.oper]p8:
10298 // [...] Operator functions cannot have more or fewer parameters
10299 // than the number required for the corresponding operator, as
10300 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010301 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010302 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010303 if (Op != OO_Call &&
10304 ((NumParams == 1 && !CanBeUnaryOperator) ||
10305 (NumParams == 2 && !CanBeBinaryOperator) ||
10306 (NumParams < 1) || (NumParams > 2))) {
10307 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010308 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010309 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010310 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010311 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010312 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010313 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010314 assert(CanBeBinaryOperator &&
10315 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010316 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010317 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010318
Chris Lattner416e46f2008-11-21 07:57:12 +000010319 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010320 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010321 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010322
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010323 // Overloaded operators other than operator() cannot be variadic.
10324 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010325 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010326 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010327 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010328 }
10329
10330 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010331 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10332 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010333 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010334 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010335 }
10336
10337 // C++ [over.inc]p1:
10338 // The user-defined function called operator++ implements the
10339 // prefix and postfix ++ operator. If this function is a member
10340 // function with no parameters, or a non-member function with one
10341 // parameter of class or enumeration type, it defines the prefix
10342 // increment operator ++ for objects of that type. If the function
10343 // is a member function with one parameter (which shall be of type
10344 // int) or a non-member function with two parameters (the second
10345 // of which shall be of type int), it defines the postfix
10346 // increment operator ++ for objects of that type.
10347 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10348 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10349 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010350 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010351 ParamIsInt = BT->getKind() == BuiltinType::Int;
10352
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010353 if (!ParamIsInt)
10354 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010355 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010356 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010357 }
10358
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010359 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010360}
Chris Lattner5a003a42008-12-17 07:09:26 +000010361
Sean Hunta6c058d2010-01-13 09:01:02 +000010362/// CheckLiteralOperatorDeclaration - Check whether the declaration
10363/// of this literal operator function is well-formed. If so, returns
10364/// false; otherwise, emits appropriate diagnostics and returns true.
10365bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010366 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010367 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10368 << FnDecl->getDeclName();
10369 return true;
10370 }
10371
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010372 if (FnDecl->isExternC()) {
10373 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10374 return true;
10375 }
10376
Sean Hunta6c058d2010-01-13 09:01:02 +000010377 bool Valid = false;
10378
Richard Smith36f5cfe2012-03-09 08:00:36 +000010379 // This might be the definition of a literal operator template.
10380 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10381 // This might be a specialization of a literal operator template.
10382 if (!TpDecl)
10383 TpDecl = FnDecl->getPrimaryTemplate();
10384
Sean Hunt216c2782010-04-07 23:11:06 +000010385 // template <char...> type operator "" name() is the only valid template
10386 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010387 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010388 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010389 // Must have only one template parameter
10390 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10391 if (Params->size() == 1) {
10392 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010393 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010394
Sean Hunt216c2782010-04-07 23:11:06 +000010395 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010396 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10397 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10398 Valid = true;
10399 }
10400 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010401 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010402 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010403 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10404
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010405 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010406
Sean Hunt30019c02010-04-07 22:57:35 +000010407 // unsigned long long int, long double, and any character type are allowed
10408 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010409 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10410 Context.hasSameType(T, Context.LongDoubleTy) ||
10411 Context.hasSameType(T, Context.CharTy) ||
10412 Context.hasSameType(T, Context.WCharTy) ||
10413 Context.hasSameType(T, Context.Char16Ty) ||
10414 Context.hasSameType(T, Context.Char32Ty)) {
10415 if (++Param == FnDecl->param_end())
10416 Valid = true;
10417 goto FinishedParams;
10418 }
10419
Sean Hunt30019c02010-04-07 22:57:35 +000010420 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010421 const PointerType *PT = T->getAs<PointerType>();
10422 if (!PT)
10423 goto FinishedParams;
10424 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010425 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010426 goto FinishedParams;
10427 T = T.getUnqualifiedType();
10428
10429 // Move on to the second parameter;
10430 ++Param;
10431
10432 // If there is no second parameter, the first must be a const char *
10433 if (Param == FnDecl->param_end()) {
10434 if (Context.hasSameType(T, Context.CharTy))
10435 Valid = true;
10436 goto FinishedParams;
10437 }
10438
10439 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10440 // are allowed as the first parameter to a two-parameter function
10441 if (!(Context.hasSameType(T, Context.CharTy) ||
10442 Context.hasSameType(T, Context.WCharTy) ||
10443 Context.hasSameType(T, Context.Char16Ty) ||
10444 Context.hasSameType(T, Context.Char32Ty)))
10445 goto FinishedParams;
10446
10447 // The second and final parameter must be an std::size_t
10448 T = (*Param)->getType().getUnqualifiedType();
10449 if (Context.hasSameType(T, Context.getSizeType()) &&
10450 ++Param == FnDecl->param_end())
10451 Valid = true;
10452 }
10453
10454 // FIXME: This diagnostic is absolutely terrible.
10455FinishedParams:
10456 if (!Valid) {
10457 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10458 << FnDecl->getDeclName();
10459 return true;
10460 }
10461
Richard Smitha9e88b22012-03-09 08:16:22 +000010462 // A parameter-declaration-clause containing a default argument is not
10463 // equivalent to any of the permitted forms.
10464 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10465 ParamEnd = FnDecl->param_end();
10466 Param != ParamEnd; ++Param) {
10467 if ((*Param)->hasDefaultArg()) {
10468 Diag((*Param)->getDefaultArgRange().getBegin(),
10469 diag::err_literal_operator_default_argument)
10470 << (*Param)->getDefaultArgRange();
10471 break;
10472 }
10473 }
10474
Richard Smith2fb4ae32012-03-08 02:39:21 +000010475 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010476 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10477 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010478 // C++11 [usrlit.suffix]p1:
10479 // Literal suffix identifiers that do not start with an underscore
10480 // are reserved for future standardization.
10481 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010482 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010483
Sean Hunta6c058d2010-01-13 09:01:02 +000010484 return false;
10485}
10486
Douglas Gregor074149e2009-01-05 19:45:36 +000010487/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10488/// linkage specification, including the language and (if present)
10489/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10490/// the location of the language string literal, which is provided
10491/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10492/// the '{' brace. Otherwise, this linkage specification does not
10493/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010494Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10495 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010496 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010497 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010498 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010499 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010500 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010501 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010502 Language = LinkageSpecDecl::lang_cxx;
10503 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010504 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010505 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010506 }
Mike Stump1eb44332009-09-09 15:08:12 +000010507
Chris Lattnercc98eac2008-12-17 07:13:27 +000010508 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010509
Douglas Gregor074149e2009-01-05 19:45:36 +000010510 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010511 ExternLoc, LangLoc, Language,
10512 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010513 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010514 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010515 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010516}
10517
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010518/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010519/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10520/// valid, it's the position of the closing '}' brace in a linkage
10521/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010522Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010523 Decl *LinkageSpec,
10524 SourceLocation RBraceLoc) {
10525 if (LinkageSpec) {
10526 if (RBraceLoc.isValid()) {
10527 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10528 LSDecl->setRBraceLoc(RBraceLoc);
10529 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010530 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010531 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010532 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010533}
10534
Michael Han684aa732013-02-22 17:15:32 +000010535Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10536 AttributeList *AttrList,
10537 SourceLocation SemiLoc) {
10538 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10539 // Attribute declarations appertain to empty declaration so we handle
10540 // them here.
10541 if (AttrList)
10542 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010543
Michael Han684aa732013-02-22 17:15:32 +000010544 CurContext->addDecl(ED);
10545 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010546}
10547
Douglas Gregord308e622009-05-18 20:51:54 +000010548/// \brief Perform semantic analysis for the variable declaration that
10549/// occurs within a C++ catch clause, returning the newly-created
10550/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010551VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010552 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010553 SourceLocation StartLoc,
10554 SourceLocation Loc,
10555 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010556 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010557 QualType ExDeclType = TInfo->getType();
10558
Sebastian Redl4b07b292008-12-22 19:15:10 +000010559 // Arrays and functions decay.
10560 if (ExDeclType->isArrayType())
10561 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10562 else if (ExDeclType->isFunctionType())
10563 ExDeclType = Context.getPointerType(ExDeclType);
10564
10565 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10566 // The exception-declaration shall not denote a pointer or reference to an
10567 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010568 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010569 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010570 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010571 Invalid = true;
10572 }
Douglas Gregord308e622009-05-18 20:51:54 +000010573
Sebastian Redl4b07b292008-12-22 19:15:10 +000010574 QualType BaseType = ExDeclType;
10575 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010576 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010577 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010578 BaseType = Ptr->getPointeeType();
10579 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010580 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010581 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010582 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010583 BaseType = Ref->getPointeeType();
10584 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010585 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010586 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010587 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010588 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010589 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010590
Mike Stump1eb44332009-09-09 15:08:12 +000010591 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010592 RequireNonAbstractType(Loc, ExDeclType,
10593 diag::err_abstract_type_in_decl,
10594 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010595 Invalid = true;
10596
John McCall5a180392010-07-24 00:37:23 +000010597 // Only the non-fragile NeXT runtime currently supports C++ catches
10598 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010599 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010600 QualType T = ExDeclType;
10601 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10602 T = RT->getPointeeType();
10603
10604 if (T->isObjCObjectType()) {
10605 Diag(Loc, diag::err_objc_object_catch);
10606 Invalid = true;
10607 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010608 // FIXME: should this be a test for macosx-fragile specifically?
10609 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010610 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010611 }
10612 }
10613
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010614 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010615 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010616 ExDecl->setExceptionVariable(true);
10617
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010618 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010619 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010620 Invalid = true;
10621
Douglas Gregorc41b8782011-07-06 18:14:43 +000010622 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010623 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010624 // Insulate this from anything else we might currently be parsing.
10625 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10626
Douglas Gregor6d182892010-03-05 23:38:39 +000010627 // C++ [except.handle]p16:
10628 // The object declared in an exception-declaration or, if the
10629 // exception-declaration does not specify a name, a temporary (12.2) is
10630 // copy-initialized (8.5) from the exception object. [...]
10631 // The object is destroyed when the handler exits, after the destruction
10632 // of any automatic objects initialized within the handler.
10633 //
10634 // We just pretend to initialize the object with itself, then make sure
10635 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010636 QualType initType = ExDeclType;
10637
10638 InitializedEntity entity =
10639 InitializedEntity::InitializeVariable(ExDecl);
10640 InitializationKind initKind =
10641 InitializationKind::CreateCopy(Loc, SourceLocation());
10642
10643 Expr *opaqueValue =
10644 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10645 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10646 ExprResult result = sequence.Perform(*this, entity, initKind,
10647 MultiExprArg(&opaqueValue, 1));
10648 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010649 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010650 else {
10651 // If the constructor used was non-trivial, set this as the
10652 // "initializer".
10653 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10654 if (!construct->getConstructor()->isTrivial()) {
10655 Expr *init = MaybeCreateExprWithCleanups(construct);
10656 ExDecl->setInit(init);
10657 }
10658
10659 // And make sure it's destructable.
10660 FinalizeVarWithDestructor(ExDecl, recordType);
10661 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010662 }
10663 }
10664
Douglas Gregord308e622009-05-18 20:51:54 +000010665 if (Invalid)
10666 ExDecl->setInvalidDecl();
10667
10668 return ExDecl;
10669}
10670
10671/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10672/// handler.
John McCalld226f652010-08-21 09:40:31 +000010673Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010674 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010675 bool Invalid = D.isInvalidType();
10676
10677 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010678 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10679 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010680 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10681 D.getIdentifierLoc());
10682 Invalid = true;
10683 }
10684
Sebastian Redl4b07b292008-12-22 19:15:10 +000010685 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010686 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010687 LookupOrdinaryName,
10688 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010689 // The scope should be freshly made just for us. There is just no way
10690 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010691 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010692 if (PrevDecl->isTemplateParameter()) {
10693 // Maybe we will complain about the shadowed template parameter.
10694 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010695 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010696 }
10697 }
10698
Chris Lattnereaaebc72009-04-25 08:06:05 +000010699 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010700 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10701 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010702 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010703 }
10704
Douglas Gregor83cb9422010-09-09 17:09:21 +000010705 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010706 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010707 D.getIdentifierLoc(),
10708 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010709 if (Invalid)
10710 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010711
Sebastian Redl4b07b292008-12-22 19:15:10 +000010712 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010713 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010714 PushOnScopeChains(ExDecl, S);
10715 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010716 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010717
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010718 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010719 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010720}
Anders Carlssonfb311762009-03-14 00:25:26 +000010721
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010722Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010723 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010724 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010725 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010726 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010727
Richard Smithe3f470a2012-07-11 22:37:56 +000010728 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10729 return 0;
10730
10731 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10732 AssertMessage, RParenLoc, false);
10733}
10734
10735Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10736 Expr *AssertExpr,
10737 StringLiteral *AssertMessage,
10738 SourceLocation RParenLoc,
10739 bool Failed) {
10740 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10741 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010742 // In a static_assert-declaration, the constant-expression shall be a
10743 // constant expression that can be contextually converted to bool.
10744 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10745 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010746 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010747
Richard Smithdaaefc52011-12-14 23:32:26 +000010748 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010749 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010750 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010751 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010752 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010753
Richard Smithe3f470a2012-07-11 22:37:56 +000010754 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010755 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010756 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010757 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010758 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010759 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010760 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010761 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010762 }
Mike Stump1eb44332009-09-09 15:08:12 +000010763
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010764 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010765 AssertExpr, AssertMessage, RParenLoc,
10766 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010767
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010768 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010769 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010770}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010771
Douglas Gregor1d869352010-04-07 16:53:43 +000010772/// \brief Perform semantic analysis of the given friend type declaration.
10773///
10774/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010775FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010776 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010777 TypeSourceInfo *TSInfo) {
10778 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10779
10780 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010781 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010782
Richard Smith6b130222011-10-18 21:39:00 +000010783 // C++03 [class.friend]p2:
10784 // An elaborated-type-specifier shall be used in a friend declaration
10785 // for a class.*
10786 //
10787 // * The class-key of the elaborated-type-specifier is required.
10788 if (!ActiveTemplateInstantiations.empty()) {
10789 // Do not complain about the form of friend template types during
10790 // template instantiation; we will already have complained when the
10791 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010792 } else {
10793 if (!T->isElaboratedTypeSpecifier()) {
10794 // If we evaluated the type to a record type, suggest putting
10795 // a tag in front.
10796 if (const RecordType *RT = T->getAs<RecordType>()) {
10797 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010798
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010799 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010800
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010801 Diag(TypeRange.getBegin(),
10802 getLangOpts().CPlusPlus11 ?
10803 diag::warn_cxx98_compat_unelaborated_friend_type :
10804 diag::ext_unelaborated_friend_type)
10805 << (unsigned) RD->getTagKind()
10806 << T
10807 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10808 InsertionText);
10809 } else {
10810 Diag(FriendLoc,
10811 getLangOpts().CPlusPlus11 ?
10812 diag::warn_cxx98_compat_nonclass_type_friend :
10813 diag::ext_nonclass_type_friend)
10814 << T
10815 << TypeRange;
10816 }
10817 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010818 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010819 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010820 diag::warn_cxx98_compat_enum_friend :
10821 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010822 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010823 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010824 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010825
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010826 // C++11 [class.friend]p3:
10827 // A friend declaration that does not declare a function shall have one
10828 // of the following forms:
10829 // friend elaborated-type-specifier ;
10830 // friend simple-type-specifier ;
10831 // friend typename-specifier ;
10832 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10833 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10834 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010835
Douglas Gregor06245bf2010-04-07 17:57:12 +000010836 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010837 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010838 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010839 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010840}
10841
John McCall9a34edb2010-10-19 01:40:49 +000010842/// Handle a friend tag declaration where the scope specifier was
10843/// templated.
10844Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10845 unsigned TagSpec, SourceLocation TagLoc,
10846 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010847 IdentifierInfo *Name,
10848 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010849 AttributeList *Attr,
10850 MultiTemplateParamsArg TempParamLists) {
10851 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10852
10853 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010854 bool Invalid = false;
10855
10856 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010857 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010858 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010859 TempParamLists.size(),
10860 /*friend*/ true,
10861 isExplicitSpecialization,
10862 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010863 if (TemplateParams->size() > 0) {
10864 // This is a declaration of a class template.
10865 if (Invalid)
10866 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010867
Eric Christopher4110e132011-07-21 05:34:24 +000010868 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10869 SS, Name, NameLoc, Attr,
10870 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010871 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010872 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010873 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010874 } else {
10875 // The "template<>" header is extraneous.
10876 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10877 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10878 isExplicitSpecialization = true;
10879 }
10880 }
10881
10882 if (Invalid) return 0;
10883
John McCall9a34edb2010-10-19 01:40:49 +000010884 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010885 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010886 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010887 isAllExplicitSpecializations = false;
10888 break;
10889 }
10890 }
10891
10892 // FIXME: don't ignore attributes.
10893
10894 // If it's explicit specializations all the way down, just forget
10895 // about the template header and build an appropriate non-templated
10896 // friend. TODO: for source fidelity, remember the headers.
10897 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010898 if (SS.isEmpty()) {
10899 bool Owned = false;
10900 bool IsDependent = false;
10901 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10902 Attr, AS_public,
10903 /*ModulePrivateLoc=*/SourceLocation(),
10904 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010905 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010906 /*ScopedEnumUsesClassTag=*/false,
10907 /*UnderlyingType=*/TypeResult());
10908 }
10909
Douglas Gregor2494dd02011-03-01 01:34:45 +000010910 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010911 ElaboratedTypeKeyword Keyword
10912 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010913 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010914 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010915 if (T.isNull())
10916 return 0;
10917
10918 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10919 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010920 DependentNameTypeLoc TL =
10921 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010922 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010923 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010924 TL.setNameLoc(NameLoc);
10925 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010926 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010927 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010928 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010929 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010930 }
10931
10932 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010933 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010934 Friend->setAccess(AS_public);
10935 CurContext->addDecl(Friend);
10936 return Friend;
10937 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010938
10939 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10940
10941
John McCall9a34edb2010-10-19 01:40:49 +000010942
10943 // Handle the case of a templated-scope friend class. e.g.
10944 // template <class T> class A<T>::B;
10945 // FIXME: we don't support these right now.
10946 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10947 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10948 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010949 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010950 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010951 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010952 TL.setNameLoc(NameLoc);
10953
10954 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010955 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010956 Friend->setAccess(AS_public);
10957 Friend->setUnsupportedFriend(true);
10958 CurContext->addDecl(Friend);
10959 return Friend;
10960}
10961
10962
John McCalldd4a3b02009-09-16 22:47:08 +000010963/// Handle a friend type declaration. This works in tandem with
10964/// ActOnTag.
10965///
10966/// Notes on friend class templates:
10967///
10968/// We generally treat friend class declarations as if they were
10969/// declaring a class. So, for example, the elaborated type specifier
10970/// in a friend declaration is required to obey the restrictions of a
10971/// class-head (i.e. no typedefs in the scope chain), template
10972/// parameters are required to match up with simple template-ids, &c.
10973/// However, unlike when declaring a template specialization, it's
10974/// okay to refer to a template specialization without an empty
10975/// template parameter declaration, e.g.
10976/// friend class A<T>::B<unsigned>;
10977/// We permit this as a special case; if there are any template
10978/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010979/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010980Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010981 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010982 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010983
10984 assert(DS.isFriendSpecified());
10985 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10986
John McCalldd4a3b02009-09-16 22:47:08 +000010987 // Try to convert the decl specifier to a type. This works for
10988 // friend templates because ActOnTag never produces a ClassTemplateDecl
10989 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010990 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010991 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10992 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010993 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010994 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010995
Douglas Gregor6ccab972010-12-16 01:14:37 +000010996 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10997 return 0;
10998
John McCalldd4a3b02009-09-16 22:47:08 +000010999 // This is definitely an error in C++98. It's probably meant to
11000 // be forbidden in C++0x, too, but the specification is just
11001 // poorly written.
11002 //
11003 // The problem is with declarations like the following:
11004 // template <T> friend A<T>::foo;
11005 // where deciding whether a class C is a friend or not now hinges
11006 // on whether there exists an instantiation of A that causes
11007 // 'foo' to equal C. There are restrictions on class-heads
11008 // (which we declare (by fiat) elaborated friend declarations to
11009 // be) that makes this tractable.
11010 //
11011 // FIXME: handle "template <> friend class A<T>;", which
11012 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011013 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011014 Diag(Loc, diag::err_tagless_friend_type_template)
11015 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011016 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011017 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011018
John McCall02cace72009-08-28 07:59:38 +000011019 // C++98 [class.friend]p1: A friend of a class is a function
11020 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011021 // This is fixed in DR77, which just barely didn't make the C++03
11022 // deadline. It's also a very silly restriction that seriously
11023 // affects inner classes and which nobody else seems to implement;
11024 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011025 //
11026 // But note that we could warn about it: it's always useless to
11027 // friend one of your own members (it's not, however, worthless to
11028 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011029
John McCalldd4a3b02009-09-16 22:47:08 +000011030 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011031 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011032 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011033 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011034 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011035 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011036 DS.getFriendSpecLoc());
11037 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011038 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011039
11040 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011041 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011042
John McCalldd4a3b02009-09-16 22:47:08 +000011043 D->setAccess(AS_public);
11044 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011045
John McCalld226f652010-08-21 09:40:31 +000011046 return D;
John McCall02cace72009-08-28 07:59:38 +000011047}
11048
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011049NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11050 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011051 const DeclSpec &DS = D.getDeclSpec();
11052
11053 assert(DS.isFriendSpecified());
11054 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11055
11056 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011057 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011058
11059 // C++ [class.friend]p1
11060 // A friend of a class is a function or class....
11061 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011062 // It *doesn't* see through dependent types, which is correct
11063 // according to [temp.arg.type]p3:
11064 // If a declaration acquires a function type through a
11065 // type dependent on a template-parameter and this causes
11066 // a declaration that does not use the syntactic form of a
11067 // function declarator to have a function type, the program
11068 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011069 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011070 Diag(Loc, diag::err_unexpected_friend);
11071
11072 // It might be worthwhile to try to recover by creating an
11073 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011074 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011075 }
11076
11077 // C++ [namespace.memdef]p3
11078 // - If a friend declaration in a non-local class first declares a
11079 // class or function, the friend class or function is a member
11080 // of the innermost enclosing namespace.
11081 // - The name of the friend is not found by simple name lookup
11082 // until a matching declaration is provided in that namespace
11083 // scope (either before or after the class declaration granting
11084 // friendship).
11085 // - If a friend function is called, its name may be found by the
11086 // name lookup that considers functions from namespaces and
11087 // classes associated with the types of the function arguments.
11088 // - When looking for a prior declaration of a class or a function
11089 // declared as a friend, scopes outside the innermost enclosing
11090 // namespace scope are not considered.
11091
John McCall337ec3d2010-10-12 23:13:28 +000011092 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011093 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11094 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011095 assert(Name);
11096
Douglas Gregor6ccab972010-12-16 01:14:37 +000011097 // Check for unexpanded parameter packs.
11098 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11099 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11100 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11101 return 0;
11102
John McCall67d1a672009-08-06 02:15:43 +000011103 // The context we found the declaration in, or in which we should
11104 // create the declaration.
11105 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011106 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011107 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011108 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011109
John McCall337ec3d2010-10-12 23:13:28 +000011110 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000011111
John McCall337ec3d2010-10-12 23:13:28 +000011112 // There are four cases here.
11113 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000011114 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000011115 // there as appropriate.
11116 // Recover from invalid scope qualifiers as if they just weren't there.
11117 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000011118 // C++0x [namespace.memdef]p3:
11119 // If the name in a friend declaration is neither qualified nor
11120 // a template-id and the declaration is a function or an
11121 // elaborated-type-specifier, the lookup to determine whether
11122 // the entity has been previously declared shall not consider
11123 // any scopes outside the innermost enclosing namespace.
11124 // C++0x [class.friend]p11:
11125 // If a friend declaration appears in a local class and the name
11126 // specified is an unqualified name, a prior declaration is
11127 // looked up without considering scopes that are outside the
11128 // innermost enclosing non-class scope. For a friend function
11129 // declaration, if there is no prior declaration, the program is
11130 // ill-formed.
11131 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000011132 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011133
John McCall29ae6e52010-10-13 05:45:15 +000011134 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011135 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011136
Rafael Espindola11dc6342013-04-25 20:12:36 +000011137 // Skip class contexts. If someone can cite chapter and verse
11138 // for this behavior, that would be nice --- it's what GCC and
11139 // EDG do, and it seems like a reasonable intent, but the spec
11140 // really only says that checks for unqualified existing
11141 // declarations should stop at the nearest enclosing namespace,
11142 // not that they should only consider the nearest enclosing
11143 // namespace.
11144 while (DC->isRecord())
11145 DC = DC->getParent();
11146
11147 DeclContext *LookupDC = DC;
11148 while (LookupDC->isTransparentContext())
11149 LookupDC = LookupDC->getParent();
11150
11151 while (true) {
11152 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011153
11154 // TODO: decide what we think about using declarations.
Rafael Espindola11dc6342013-04-25 20:12:36 +000011155 if (isLocal)
John McCall67d1a672009-08-06 02:15:43 +000011156 break;
John McCall29ae6e52010-10-13 05:45:15 +000011157
Rafael Espindola11dc6342013-04-25 20:12:36 +000011158 if (!Previous.empty()) {
11159 DC = LookupDC;
11160 break;
John McCall8a407372010-10-14 22:22:28 +000011161 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011162
11163 if (isTemplateId) {
11164 if (isa<TranslationUnitDecl>(LookupDC)) break;
11165 } else {
11166 if (LookupDC->isFileContext()) break;
11167 }
11168 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011169 }
11170
John McCall380aaa42010-10-13 06:22:15 +000011171 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011172
Douglas Gregor883af832011-10-10 01:11:59 +000011173 // C++ [class.friend]p6:
11174 // A function can be defined in a friend declaration of a class if and
11175 // only if the class is a non-local class (9.8), the function name is
11176 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011177 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011178 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11179 }
11180
John McCall337ec3d2010-10-12 23:13:28 +000011181 // - There's a non-dependent scope specifier, in which case we
11182 // compute it and do a previous lookup there for a function
11183 // or function template.
11184 } else if (!SS.getScopeRep()->isDependent()) {
11185 DC = computeDeclContext(SS);
11186 if (!DC) return 0;
11187
11188 if (RequireCompleteDeclContext(SS, DC)) return 0;
11189
11190 LookupQualifiedName(Previous, DC);
11191
11192 // Ignore things found implicitly in the wrong scope.
11193 // TODO: better diagnostics for this case. Suggesting the right
11194 // qualified scope would be nice...
11195 LookupResult::Filter F = Previous.makeFilter();
11196 while (F.hasNext()) {
11197 NamedDecl *D = F.next();
11198 if (!DC->InEnclosingNamespaceSetOf(
11199 D->getDeclContext()->getRedeclContext()))
11200 F.erase();
11201 }
11202 F.done();
11203
11204 if (Previous.empty()) {
11205 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011206 Diag(Loc, diag::err_qualified_friend_not_found)
11207 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011208 return 0;
11209 }
11210
11211 // C++ [class.friend]p1: A friend of a class is a function or
11212 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011213 if (DC->Equals(CurContext))
11214 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011215 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011216 diag::warn_cxx98_compat_friend_is_member :
11217 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011218
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011219 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011220 // C++ [class.friend]p6:
11221 // A function can be defined in a friend declaration of a class if and
11222 // only if the class is a non-local class (9.8), the function name is
11223 // unqualified, and the function has namespace scope.
11224 SemaDiagnosticBuilder DB
11225 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11226
11227 DB << SS.getScopeRep();
11228 if (DC->isFileContext())
11229 DB << FixItHint::CreateRemoval(SS.getRange());
11230 SS.clear();
11231 }
John McCall337ec3d2010-10-12 23:13:28 +000011232
11233 // - There's a scope specifier that does not match any template
11234 // parameter lists, in which case we use some arbitrary context,
11235 // create a method or method template, and wait for instantiation.
11236 // - There's a scope specifier that does match some template
11237 // parameter lists, which we don't handle right now.
11238 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011239 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011240 // C++ [class.friend]p6:
11241 // A function can be defined in a friend declaration of a class if and
11242 // only if the class is a non-local class (9.8), the function name is
11243 // unqualified, and the function has namespace scope.
11244 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11245 << SS.getScopeRep();
11246 }
11247
John McCall337ec3d2010-10-12 23:13:28 +000011248 DC = CurContext;
11249 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011250 }
Douglas Gregor883af832011-10-10 01:11:59 +000011251
John McCall29ae6e52010-10-13 05:45:15 +000011252 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011253 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011254 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11255 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11256 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011257 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011258 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11259 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011260 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011261 }
John McCall67d1a672009-08-06 02:15:43 +000011262 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011263
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011264 // FIXME: This is an egregious hack to cope with cases where the scope stack
11265 // does not contain the declaration context, i.e., in an out-of-line
11266 // definition of a class.
11267 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11268 if (!DCScope) {
11269 FakeDCScope.setEntity(DC);
11270 DCScope = &FakeDCScope;
11271 }
11272
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011273 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011274 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011275 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011276 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011277
Douglas Gregor182ddf02009-09-28 00:08:27 +000011278 assert(ND->getDeclContext() == DC);
11279 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011280
John McCallab88d972009-08-31 22:39:49 +000011281 // Add the function declaration to the appropriate lookup tables,
11282 // adjusting the redeclarations list as necessary. We don't
11283 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011284 //
John McCallab88d972009-08-31 22:39:49 +000011285 // Also update the scope-based lookup if the target context's
11286 // lookup context is in lexical scope.
11287 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011288 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011289 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011290 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011291 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011292 }
John McCall02cace72009-08-28 07:59:38 +000011293
11294 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011295 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011296 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011297 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011298 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011299
John McCall1f2e1a92012-08-10 03:15:35 +000011300 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011301 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011302 } else {
11303 if (DC->isRecord()) CheckFriendAccess(ND);
11304
John McCall6102ca12010-10-16 06:59:13 +000011305 FunctionDecl *FD;
11306 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11307 FD = FTD->getTemplatedDecl();
11308 else
11309 FD = cast<FunctionDecl>(ND);
11310
11311 // Mark templated-scope function declarations as unsupported.
11312 if (FD->getNumTemplateParameterLists())
11313 FrD->setUnsupportedFriend(true);
11314 }
John McCall337ec3d2010-10-12 23:13:28 +000011315
John McCalld226f652010-08-21 09:40:31 +000011316 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011317}
11318
John McCalld226f652010-08-21 09:40:31 +000011319void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11320 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011321
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011322 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011323 if (!Fn) {
11324 Diag(DelLoc, diag::err_deleted_non_function);
11325 return;
11326 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011327
Douglas Gregoref96ee02012-01-14 16:38:05 +000011328 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011329 // Don't consider the implicit declaration we generate for explicit
11330 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011331 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11332 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011333 Diag(DelLoc, diag::err_deleted_decl_not_first);
11334 Diag(Prev->getLocation(), diag::note_previous_declaration);
11335 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011336 // If the declaration wasn't the first, we delete the function anyway for
11337 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011338 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011339 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011340
11341 if (Fn->isDeleted())
11342 return;
11343
11344 // See if we're deleting a function which is already known to override a
11345 // non-deleted virtual function.
11346 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11347 bool IssuedDiagnostic = false;
11348 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11349 E = MD->end_overridden_methods();
11350 I != E; ++I) {
11351 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11352 if (!IssuedDiagnostic) {
11353 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11354 IssuedDiagnostic = true;
11355 }
11356 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11357 }
11358 }
11359 }
11360
Sean Hunt10620eb2011-05-06 20:44:56 +000011361 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011362}
Sebastian Redl13e88542009-04-27 21:33:24 +000011363
Sean Hunte4246a62011-05-12 06:15:49 +000011364void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011365 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011366
11367 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011368 if (MD->getParent()->isDependentType()) {
11369 MD->setDefaulted();
11370 MD->setExplicitlyDefaulted();
11371 return;
11372 }
11373
Sean Hunte4246a62011-05-12 06:15:49 +000011374 CXXSpecialMember Member = getSpecialMember(MD);
11375 if (Member == CXXInvalid) {
11376 Diag(DefaultLoc, diag::err_default_special_members);
11377 return;
11378 }
11379
11380 MD->setDefaulted();
11381 MD->setExplicitlyDefaulted();
11382
Sean Huntcd10dec2011-05-23 23:14:04 +000011383 // If this definition appears within the record, do the checking when
11384 // the record is complete.
11385 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011386 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011387 // Find the uninstantiated declaration that actually had the '= default'
11388 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011389 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011390
Richard Smith12fef492013-03-27 00:22:47 +000011391 // If the method was defaulted on its first declaration, we will have
11392 // already performed the checking in CheckCompletedCXXClass. Such a
11393 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011394 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011395 return;
11396
Richard Smithb9d0b762012-07-27 04:22:15 +000011397 CheckExplicitlyDefaultedSpecialMember(MD);
11398
Richard Smith1d28caf2012-12-11 01:14:52 +000011399 // The exception specification is needed because we are defining the
11400 // function.
11401 ResolveExceptionSpec(DefaultLoc,
11402 MD->getType()->castAs<FunctionProtoType>());
11403
Sean Hunte4246a62011-05-12 06:15:49 +000011404 switch (Member) {
11405 case CXXDefaultConstructor: {
11406 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011407 if (!CD->isInvalidDecl())
11408 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11409 break;
11410 }
11411
11412 case CXXCopyConstructor: {
11413 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011414 if (!CD->isInvalidDecl())
11415 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011416 break;
11417 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011418
Sean Hunt2b188082011-05-14 05:23:28 +000011419 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011420 if (!MD->isInvalidDecl())
11421 DefineImplicitCopyAssignment(DefaultLoc, MD);
11422 break;
11423 }
11424
Sean Huntcb45a0f2011-05-12 22:46:25 +000011425 case CXXDestructor: {
11426 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011427 if (!DD->isInvalidDecl())
11428 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011429 break;
11430 }
11431
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011432 case CXXMoveConstructor: {
11433 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011434 if (!CD->isInvalidDecl())
11435 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011436 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011437 }
Sean Hunt82713172011-05-25 23:16:36 +000011438
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011439 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011440 if (!MD->isInvalidDecl())
11441 DefineImplicitMoveAssignment(DefaultLoc, MD);
11442 break;
11443 }
11444
11445 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011446 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011447 }
11448 } else {
11449 Diag(DefaultLoc, diag::err_default_special_members);
11450 }
11451}
11452
Sebastian Redl13e88542009-04-27 21:33:24 +000011453static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011454 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011455 Stmt *SubStmt = *CI;
11456 if (!SubStmt)
11457 continue;
11458 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011459 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011460 diag::err_return_in_constructor_handler);
11461 if (!isa<Expr>(SubStmt))
11462 SearchForReturnInStmt(Self, SubStmt);
11463 }
11464}
11465
11466void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11467 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11468 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11469 SearchForReturnInStmt(*this, Handler);
11470 }
11471}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011472
David Blaikie299adab2013-01-18 23:03:15 +000011473bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011474 const CXXMethodDecl *Old) {
11475 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11476 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11477
11478 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11479
11480 // If the calling conventions match, everything is fine
11481 if (NewCC == OldCC)
11482 return false;
11483
11484 // If either of the calling conventions are set to "default", we need to pick
11485 // something more sensible based on the target. This supports code where the
11486 // one method explicitly sets thiscall, and another has no explicit calling
11487 // convention.
11488 CallingConv Default =
11489 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11490 if (NewCC == CC_Default)
11491 NewCC = Default;
11492 if (OldCC == CC_Default)
11493 OldCC = Default;
11494
11495 // If the calling conventions still don't match, then report the error
11496 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011497 Diag(New->getLocation(),
11498 diag::err_conflicting_overriding_cc_attributes)
11499 << New->getDeclName() << New->getType() << Old->getType();
11500 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11501 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011502 }
11503
11504 return false;
11505}
11506
Mike Stump1eb44332009-09-09 15:08:12 +000011507bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011508 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011509 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11510 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011511
Chandler Carruth73857792010-02-15 11:53:20 +000011512 if (Context.hasSameType(NewTy, OldTy) ||
11513 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011514 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011515
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011516 // Check if the return types are covariant
11517 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011518
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011519 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011520 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11521 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011522 NewClassTy = NewPT->getPointeeType();
11523 OldClassTy = OldPT->getPointeeType();
11524 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011525 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11526 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11527 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11528 NewClassTy = NewRT->getPointeeType();
11529 OldClassTy = OldRT->getPointeeType();
11530 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011531 }
11532 }
Mike Stump1eb44332009-09-09 15:08:12 +000011533
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011534 // The return types aren't either both pointers or references to a class type.
11535 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011536 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011537 diag::err_different_return_type_for_overriding_virtual_function)
11538 << New->getDeclName() << NewTy << OldTy;
11539 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011540
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011541 return true;
11542 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011543
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011544 // C++ [class.virtual]p6:
11545 // If the return type of D::f differs from the return type of B::f, the
11546 // class type in the return type of D::f shall be complete at the point of
11547 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011548 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11549 if (!RT->isBeingDefined() &&
11550 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011551 diag::err_covariant_return_incomplete,
11552 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011553 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011554 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011555
Douglas Gregora4923eb2009-11-16 21:35:15 +000011556 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011557 // Check if the new class derives from the old class.
11558 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11559 Diag(New->getLocation(),
11560 diag::err_covariant_return_not_derived)
11561 << New->getDeclName() << NewTy << OldTy;
11562 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11563 return true;
11564 }
Mike Stump1eb44332009-09-09 15:08:12 +000011565
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011566 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011567 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011568 diag::err_covariant_return_inaccessible_base,
11569 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11570 // FIXME: Should this point to the return type?
11571 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011572 // FIXME: this note won't trigger for delayed access control
11573 // diagnostics, and it's impossible to get an undelayed error
11574 // here from access control during the original parse because
11575 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011576 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11577 return true;
11578 }
11579 }
Mike Stump1eb44332009-09-09 15:08:12 +000011580
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011581 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011582 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011583 Diag(New->getLocation(),
11584 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011585 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011586 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11587 return true;
11588 };
Mike Stump1eb44332009-09-09 15:08:12 +000011589
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011590
11591 // The new class type must have the same or less qualifiers as the old type.
11592 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11593 Diag(New->getLocation(),
11594 diag::err_covariant_return_type_class_type_more_qualified)
11595 << New->getDeclName() << NewTy << OldTy;
11596 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11597 return true;
11598 };
Mike Stump1eb44332009-09-09 15:08:12 +000011599
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011600 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011601}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011602
Douglas Gregor4ba31362009-12-01 17:24:26 +000011603/// \brief Mark the given method pure.
11604///
11605/// \param Method the method to be marked pure.
11606///
11607/// \param InitRange the source range that covers the "0" initializer.
11608bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011609 SourceLocation EndLoc = InitRange.getEnd();
11610 if (EndLoc.isValid())
11611 Method->setRangeEnd(EndLoc);
11612
Douglas Gregor4ba31362009-12-01 17:24:26 +000011613 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11614 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011615 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011616 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011617
11618 if (!Method->isInvalidDecl())
11619 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11620 << Method->getDeclName() << InitRange;
11621 return true;
11622}
11623
Douglas Gregor552e2992012-02-21 02:22:07 +000011624/// \brief Determine whether the given declaration is a static data member.
11625static bool isStaticDataMember(Decl *D) {
11626 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11627 if (!Var)
11628 return false;
11629
11630 return Var->isStaticDataMember();
11631}
John McCall731ad842009-12-19 09:28:58 +000011632/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11633/// an initializer for the out-of-line declaration 'Dcl'. The scope
11634/// is a fresh scope pushed for just this purpose.
11635///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011636/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11637/// static data member of class X, names should be looked up in the scope of
11638/// class X.
John McCalld226f652010-08-21 09:40:31 +000011639void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011640 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011641 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011642
John McCall731ad842009-12-19 09:28:58 +000011643 // We should only get called for declarations with scope specifiers, like:
11644 // int foo::bar;
11645 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011646 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011647
11648 // If we are parsing the initializer for a static data member, push a
11649 // new expression evaluation context that is associated with this static
11650 // data member.
11651 if (isStaticDataMember(D))
11652 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011653}
11654
11655/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011656/// initializer for the out-of-line declaration 'D'.
11657void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011658 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011659 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011660
Douglas Gregor552e2992012-02-21 02:22:07 +000011661 if (isStaticDataMember(D))
11662 PopExpressionEvaluationContext();
11663
John McCall731ad842009-12-19 09:28:58 +000011664 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011665 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011666}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011667
11668/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11669/// C++ if/switch/while/for statement.
11670/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011671DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011672 // C++ 6.4p2:
11673 // The declarator shall not specify a function or an array.
11674 // The type-specifier-seq shall not contain typedef and shall not declare a
11675 // new class or enumeration.
11676 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11677 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011678
11679 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011680 if (!Dcl)
11681 return true;
11682
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011683 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11684 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011685 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011686 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011687 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011688
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011689 return Dcl;
11690}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011691
Douglas Gregordfe65432011-07-28 19:11:31 +000011692void Sema::LoadExternalVTableUses() {
11693 if (!ExternalSource)
11694 return;
11695
11696 SmallVector<ExternalVTableUse, 4> VTables;
11697 ExternalSource->ReadUsedVTables(VTables);
11698 SmallVector<VTableUse, 4> NewUses;
11699 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11700 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11701 = VTablesUsed.find(VTables[I].Record);
11702 // Even if a definition wasn't required before, it may be required now.
11703 if (Pos != VTablesUsed.end()) {
11704 if (!Pos->second && VTables[I].DefinitionRequired)
11705 Pos->second = true;
11706 continue;
11707 }
11708
11709 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11710 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11711 }
11712
11713 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11714}
11715
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011716void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11717 bool DefinitionRequired) {
11718 // Ignore any vtable uses in unevaluated operands or for classes that do
11719 // not have a vtable.
11720 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011721 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011722 return;
11723
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011724 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011725 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011726 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11727 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11728 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11729 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011730 // If we already had an entry, check to see if we are promoting this vtable
11731 // to required a definition. If so, we need to reappend to the VTableUses
11732 // list, since we may have already processed the first entry.
11733 if (DefinitionRequired && !Pos.first->second) {
11734 Pos.first->second = true;
11735 } else {
11736 // Otherwise, we can early exit.
11737 return;
11738 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011739 }
11740
11741 // Local classes need to have their virtual members marked
11742 // immediately. For all other classes, we mark their virtual members
11743 // at the end of the translation unit.
11744 if (Class->isLocalClass())
11745 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011746 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011747 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011748}
11749
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011750bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011751 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011752 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011753 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011754
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011755 // Note: The VTableUses vector could grow as a result of marking
11756 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011757 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011758 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011759 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011760 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011761 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011762 if (!Class)
11763 continue;
11764
11765 SourceLocation Loc = VTableUses[I].second;
11766
Richard Smithb9d0b762012-07-27 04:22:15 +000011767 bool DefineVTable = true;
11768
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011769 // If this class has a key function, but that key function is
11770 // defined in another translation unit, we don't need to emit the
11771 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011772 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011773 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011774 switch (KeyFunction->getTemplateSpecializationKind()) {
11775 case TSK_Undeclared:
11776 case TSK_ExplicitSpecialization:
11777 case TSK_ExplicitInstantiationDeclaration:
11778 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011779 DefineVTable = false;
11780 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011781
11782 case TSK_ExplicitInstantiationDefinition:
11783 case TSK_ImplicitInstantiation:
11784 // We will be instantiating the key function.
11785 break;
11786 }
11787 } else if (!KeyFunction) {
11788 // If we have a class with no key function that is the subject
11789 // of an explicit instantiation declaration, suppress the
11790 // vtable; it will live with the explicit instantiation
11791 // definition.
11792 bool IsExplicitInstantiationDeclaration
11793 = Class->getTemplateSpecializationKind()
11794 == TSK_ExplicitInstantiationDeclaration;
11795 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11796 REnd = Class->redecls_end();
11797 R != REnd; ++R) {
11798 TemplateSpecializationKind TSK
11799 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11800 if (TSK == TSK_ExplicitInstantiationDeclaration)
11801 IsExplicitInstantiationDeclaration = true;
11802 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11803 IsExplicitInstantiationDeclaration = false;
11804 break;
11805 }
11806 }
11807
11808 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011809 DefineVTable = false;
11810 }
11811
11812 // The exception specifications for all virtual members may be needed even
11813 // if we are not providing an authoritative form of the vtable in this TU.
11814 // We may choose to emit it available_externally anyway.
11815 if (!DefineVTable) {
11816 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11817 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011818 }
11819
11820 // Mark all of the virtual members of this class as referenced, so
11821 // that we can build a vtable. Then, tell the AST consumer that a
11822 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011823 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011824 MarkVirtualMembersReferenced(Loc, Class);
11825 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11826 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11827
11828 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola531db822013-03-07 02:00:27 +000011829 if (Class->hasExternalLinkage() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011830 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011831 const FunctionDecl *KeyFunctionDef = 0;
11832 if (!KeyFunction ||
11833 (KeyFunction->hasBody(KeyFunctionDef) &&
11834 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011835 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11836 TSK_ExplicitInstantiationDefinition
11837 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11838 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011839 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011840 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011841 VTableUses.clear();
11842
Douglas Gregor78844032011-04-22 22:25:37 +000011843 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011844}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011845
Richard Smithb9d0b762012-07-27 04:22:15 +000011846void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11847 const CXXRecordDecl *RD) {
11848 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11849 E = RD->method_end(); I != E; ++I)
11850 if ((*I)->isVirtual() && !(*I)->isPure())
11851 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11852}
11853
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011854void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11855 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011856 // Mark all functions which will appear in RD's vtable as used.
11857 CXXFinalOverriderMap FinalOverriders;
11858 RD->getFinalOverriders(FinalOverriders);
11859 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11860 E = FinalOverriders.end();
11861 I != E; ++I) {
11862 for (OverridingMethods::const_iterator OI = I->second.begin(),
11863 OE = I->second.end();
11864 OI != OE; ++OI) {
11865 assert(OI->second.size() > 0 && "no final overrider");
11866 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011867
Richard Smithff817f72012-07-07 06:59:51 +000011868 // C++ [basic.def.odr]p2:
11869 // [...] A virtual member function is used if it is not pure. [...]
11870 if (!Overrider->isPure())
11871 MarkFunctionReferenced(Loc, Overrider);
11872 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011873 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011874
11875 // Only classes that have virtual bases need a VTT.
11876 if (RD->getNumVBases() == 0)
11877 return;
11878
11879 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11880 e = RD->bases_end(); i != e; ++i) {
11881 const CXXRecordDecl *Base =
11882 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011883 if (Base->getNumVBases() == 0)
11884 continue;
11885 MarkVirtualMembersReferenced(Loc, Base);
11886 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011887}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011888
11889/// SetIvarInitializers - This routine builds initialization ASTs for the
11890/// Objective-C implementation whose ivars need be initialized.
11891void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011892 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011893 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011894 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011895 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011896 CollectIvarsToConstructOrDestruct(OID, ivars);
11897 if (ivars.empty())
11898 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011899 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011900 for (unsigned i = 0; i < ivars.size(); i++) {
11901 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011902 if (Field->isInvalidDecl())
11903 continue;
11904
Sean Huntcbb67482011-01-08 20:30:50 +000011905 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011906 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11907 InitializationKind InitKind =
11908 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11909
11910 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011911 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011912 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011913 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011914 // Note, MemberInit could actually come back empty if no initialization
11915 // is required (e.g., because it would call a trivial default constructor)
11916 if (!MemberInit.get() || MemberInit.isInvalid())
11917 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011918
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011919 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011920 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11921 SourceLocation(),
11922 MemberInit.takeAs<Expr>(),
11923 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011924 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011925
11926 // Be sure that the destructor is accessible and is marked as referenced.
11927 if (const RecordType *RecordTy
11928 = Context.getBaseElementType(Field->getType())
11929 ->getAs<RecordType>()) {
11930 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011931 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011932 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011933 CheckDestructorAccess(Field->getLocation(), Destructor,
11934 PDiag(diag::err_access_dtor_ivar)
11935 << Context.getBaseElementType(Field->getType()));
11936 }
11937 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011938 }
11939 ObjCImplementation->setIvarInitializers(Context,
11940 AllToInit.data(), AllToInit.size());
11941 }
11942}
Sean Huntfe57eef2011-05-04 05:57:24 +000011943
Sean Huntebcbe1d2011-05-04 23:29:54 +000011944static
11945void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11946 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11947 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11948 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11949 Sema &S) {
11950 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11951 CE = Current.end();
11952 if (Ctor->isInvalidDecl())
11953 return;
11954
Richard Smitha8eaf002012-08-23 06:16:52 +000011955 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11956
11957 // Target may not be determinable yet, for instance if this is a dependent
11958 // call in an uninstantiated template.
11959 if (Target) {
11960 const FunctionDecl *FNTarget = 0;
11961 (void)Target->hasBody(FNTarget);
11962 Target = const_cast<CXXConstructorDecl*>(
11963 cast_or_null<CXXConstructorDecl>(FNTarget));
11964 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011965
11966 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11967 // Avoid dereferencing a null pointer here.
11968 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11969
11970 if (!Current.insert(Canonical))
11971 return;
11972
11973 // We know that beyond here, we aren't chaining into a cycle.
11974 if (!Target || !Target->isDelegatingConstructor() ||
11975 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11976 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11977 Valid.insert(*CI);
11978 Current.clear();
11979 // We've hit a cycle.
11980 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11981 Current.count(TCanonical)) {
11982 // If we haven't diagnosed this cycle yet, do so now.
11983 if (!Invalid.count(TCanonical)) {
11984 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011985 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011986 << Ctor;
11987
Richard Smitha8eaf002012-08-23 06:16:52 +000011988 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011989 if (TCanonical != Canonical)
11990 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11991
11992 CXXConstructorDecl *C = Target;
11993 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011994 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011995 (void)C->getTargetConstructor()->hasBody(FNTarget);
11996 assert(FNTarget && "Ctor cycle through bodiless function");
11997
Richard Smitha8eaf002012-08-23 06:16:52 +000011998 C = const_cast<CXXConstructorDecl*>(
11999 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012000 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12001 }
12002 }
12003
12004 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12005 Invalid.insert(*CI);
12006 Current.clear();
12007 } else {
12008 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12009 }
12010}
12011
12012
Sean Huntfe57eef2011-05-04 05:57:24 +000012013void Sema::CheckDelegatingCtorCycles() {
12014 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12015
Sean Huntebcbe1d2011-05-04 23:29:54 +000012016 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12017 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000012018
Douglas Gregor0129b562011-07-27 21:57:17 +000012019 for (DelegatingCtorDeclsType::iterator
12020 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012021 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012022 I != E; ++I)
12023 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012024
12025 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12026 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012027}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012028
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012029namespace {
12030 /// \brief AST visitor that finds references to the 'this' expression.
12031 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12032 Sema &S;
12033
12034 public:
12035 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12036
12037 bool VisitCXXThisExpr(CXXThisExpr *E) {
12038 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12039 << E->isImplicit();
12040 return false;
12041 }
12042 };
12043}
12044
12045bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12046 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12047 if (!TSInfo)
12048 return false;
12049
12050 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012051 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012052 if (!ProtoTL)
12053 return false;
12054
12055 // C++11 [expr.prim.general]p3:
12056 // [The expression this] shall not appear before the optional
12057 // cv-qualifier-seq and it shall not appear within the declaration of a
12058 // static member function (although its type and value category are defined
12059 // within a static member function as they are within a non-static member
12060 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012061 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012062 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012063 FindCXXThisExpr Finder(*this);
12064
12065 // If the return type came after the cv-qualifier-seq, check it now.
12066 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012067 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012068 return true;
12069
12070 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012071 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12072 return true;
12073
12074 return checkThisInStaticMemberFunctionAttributes(Method);
12075}
12076
12077bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12078 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12079 if (!TSInfo)
12080 return false;
12081
12082 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012083 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012084 if (!ProtoTL)
12085 return false;
12086
David Blaikie39e6ab42013-02-18 22:06:02 +000012087 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012088 FindCXXThisExpr Finder(*this);
12089
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012090 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012091 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012092 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012093 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012094 case EST_DynamicNone:
12095 case EST_MSAny:
12096 case EST_None:
12097 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012098
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012099 case EST_ComputedNoexcept:
12100 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12101 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012102
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012103 case EST_Dynamic:
12104 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012105 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012106 E != EEnd; ++E) {
12107 if (!Finder.TraverseType(*E))
12108 return true;
12109 }
12110 break;
12111 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012112
12113 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012114}
12115
12116bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12117 FindCXXThisExpr Finder(*this);
12118
12119 // Check attributes.
12120 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12121 A != AEnd; ++A) {
12122 // FIXME: This should be emitted by tblgen.
12123 Expr *Arg = 0;
12124 ArrayRef<Expr *> Args;
12125 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12126 Arg = G->getArg();
12127 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12128 Arg = G->getArg();
12129 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12130 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12131 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12132 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12133 else if (ExclusiveLockFunctionAttr *ELF
12134 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12135 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12136 else if (SharedLockFunctionAttr *SLF
12137 = dyn_cast<SharedLockFunctionAttr>(*A))
12138 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12139 else if (ExclusiveTrylockFunctionAttr *ETLF
12140 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12141 Arg = ETLF->getSuccessValue();
12142 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12143 } else if (SharedTrylockFunctionAttr *STLF
12144 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12145 Arg = STLF->getSuccessValue();
12146 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12147 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12148 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12149 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12150 Arg = LR->getArg();
12151 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12152 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12153 else if (ExclusiveLocksRequiredAttr *ELR
12154 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12155 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12156 else if (SharedLocksRequiredAttr *SLR
12157 = dyn_cast<SharedLocksRequiredAttr>(*A))
12158 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12159
12160 if (Arg && !Finder.TraverseStmt(Arg))
12161 return true;
12162
12163 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12164 if (!Finder.TraverseStmt(Args[I]))
12165 return true;
12166 }
12167 }
12168
12169 return false;
12170}
12171
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012172void
12173Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12174 ArrayRef<ParsedType> DynamicExceptions,
12175 ArrayRef<SourceRange> DynamicExceptionRanges,
12176 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012177 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012178 FunctionProtoType::ExtProtoInfo &EPI) {
12179 Exceptions.clear();
12180 EPI.ExceptionSpecType = EST;
12181 if (EST == EST_Dynamic) {
12182 Exceptions.reserve(DynamicExceptions.size());
12183 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12184 // FIXME: Preserve type source info.
12185 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12186
12187 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12188 collectUnexpandedParameterPacks(ET, Unexpanded);
12189 if (!Unexpanded.empty()) {
12190 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12191 UPPC_ExceptionType,
12192 Unexpanded);
12193 continue;
12194 }
12195
12196 // Check that the type is valid for an exception spec, and
12197 // drop it if not.
12198 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12199 Exceptions.push_back(ET);
12200 }
12201 EPI.NumExceptions = Exceptions.size();
12202 EPI.Exceptions = Exceptions.data();
12203 return;
12204 }
12205
12206 if (EST == EST_ComputedNoexcept) {
12207 // If an error occurred, there's no expression here.
12208 if (NoexceptExpr) {
12209 assert((NoexceptExpr->isTypeDependent() ||
12210 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12211 Context.BoolTy) &&
12212 "Parser should have made sure that the expression is boolean");
12213 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12214 EPI.ExceptionSpecType = EST_BasicNoexcept;
12215 return;
12216 }
12217
12218 if (!NoexceptExpr->isValueDependent())
12219 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012220 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012221 /*AllowFold*/ false).take();
12222 EPI.NoexceptExpr = NoexceptExpr;
12223 }
12224 return;
12225 }
12226}
12227
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012228/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12229Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12230 // Implicitly declared functions (e.g. copy constructors) are
12231 // __host__ __device__
12232 if (D->isImplicit())
12233 return CFT_HostDevice;
12234
12235 if (D->hasAttr<CUDAGlobalAttr>())
12236 return CFT_Global;
12237
12238 if (D->hasAttr<CUDADeviceAttr>()) {
12239 if (D->hasAttr<CUDAHostAttr>())
12240 return CFT_HostDevice;
12241 else
12242 return CFT_Device;
12243 }
12244
12245 return CFT_Host;
12246}
12247
12248bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12249 CUDAFunctionTarget CalleeTarget) {
12250 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12251 // Callable from the device only."
12252 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12253 return true;
12254
12255 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12256 // Callable from the host only."
12257 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12258 // Callable from the host only."
12259 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12260 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12261 return true;
12262
12263 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12264 return true;
12265
12266 return false;
12267}
John McCall76da55d2013-04-16 07:28:30 +000012268
12269/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12270///
12271MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12272 SourceLocation DeclStart,
12273 Declarator &D, Expr *BitWidth,
12274 InClassInitStyle InitStyle,
12275 AccessSpecifier AS,
12276 AttributeList *MSPropertyAttr) {
12277 IdentifierInfo *II = D.getIdentifier();
12278 if (!II) {
12279 Diag(DeclStart, diag::err_anonymous_property);
12280 return NULL;
12281 }
12282 SourceLocation Loc = D.getIdentifierLoc();
12283
12284 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12285 QualType T = TInfo->getType();
12286 if (getLangOpts().CPlusPlus) {
12287 CheckExtraCXXDefaultArguments(D);
12288
12289 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12290 UPPC_DataMemberType)) {
12291 D.setInvalidType();
12292 T = Context.IntTy;
12293 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12294 }
12295 }
12296
12297 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12298
12299 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12300 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12301 diag::err_invalid_thread)
12302 << DeclSpec::getSpecifierName(TSCS);
12303
12304 // Check to see if this name was declared as a member previously
12305 NamedDecl *PrevDecl = 0;
12306 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12307 LookupName(Previous, S);
12308 switch (Previous.getResultKind()) {
12309 case LookupResult::Found:
12310 case LookupResult::FoundUnresolvedValue:
12311 PrevDecl = Previous.getAsSingle<NamedDecl>();
12312 break;
12313
12314 case LookupResult::FoundOverloaded:
12315 PrevDecl = Previous.getRepresentativeDecl();
12316 break;
12317
12318 case LookupResult::NotFound:
12319 case LookupResult::NotFoundInCurrentInstantiation:
12320 case LookupResult::Ambiguous:
12321 break;
12322 }
12323
12324 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12325 // Maybe we will complain about the shadowed template parameter.
12326 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12327 // Just pretend that we didn't see the previous declaration.
12328 PrevDecl = 0;
12329 }
12330
12331 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12332 PrevDecl = 0;
12333
12334 SourceLocation TSSL = D.getLocStart();
12335 MSPropertyDecl *NewPD;
12336 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12337 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12338 II, T, TInfo, TSSL,
12339 Data.GetterId, Data.SetterId);
12340 ProcessDeclAttributes(TUScope, NewPD, D);
12341 NewPD->setAccess(AS);
12342
12343 if (NewPD->isInvalidDecl())
12344 Record->setInvalidDecl();
12345
12346 if (D.getDeclSpec().isModulePrivateSpecified())
12347 NewPD->setModulePrivate();
12348
12349 if (NewPD->isInvalidDecl() && PrevDecl) {
12350 // Don't introduce NewFD into scope; there's already something
12351 // with the same name in the same scope.
12352 } else if (II) {
12353 PushOnScopeChains(NewPD, S);
12354 } else
12355 Record->addDecl(NewPD);
12356
12357 return NewPD;
12358}