blob: d6d6ca7e88714238b8ddc564560740a84bef7e28 [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);
Chris Lattner9e979552008-04-12 23:52:44 +000068 };
Chris Lattner8123a952008-04-10 02:22:51 +000069
Chris Lattner9e979552008-04-12 23:52:44 +000070 /// VisitExpr - Visit all of the children of this expression.
71 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
72 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000073 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000074 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000075 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000076 }
77
Chris Lattner9e979552008-04-12 23:52:44 +000078 /// VisitDeclRefExpr - Visit a reference to a declaration, to
79 /// determine whether this declaration can be used in the default
80 /// argument expression.
81 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000082 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000083 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
84 // C++ [dcl.fct.default]p9
85 // Default arguments are evaluated each time the function is
86 // called. The order of evaluation of function arguments is
87 // unspecified. Consequently, parameters of a function shall not
88 // be used in default argument expressions, even if they are not
89 // evaluated. Parameters of a function declared before a default
90 // argument expression are in scope and can hide namespace and
91 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000092 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000093 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000094 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000095 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000096 // C++ [dcl.fct.default]p7
97 // Local variables shall not be used in default argument
98 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000099 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000100 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000101 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000102 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000103 }
Chris Lattner8123a952008-04-10 02:22:51 +0000104
Douglas Gregor3996f232008-11-04 13:41:56 +0000105 return false;
106 }
Chris Lattner9e979552008-04-12 23:52:44 +0000107
Douglas Gregor796da182008-11-04 14:32:21 +0000108 /// VisitCXXThisExpr - Visit a C++ "this" expression.
109 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
110 // C++ [dcl.fct.default]p8:
111 // The keyword this shall not be used in a default argument of a
112 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000113 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000114 diag::err_param_default_argument_references_this)
115 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000116 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000117
118 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
119 // C++11 [expr.lambda.prim]p13:
120 // A lambda-expression appearing in a default argument shall not
121 // implicitly or explicitly capture any entity.
122 if (Lambda->capture_begin() == Lambda->capture_end())
123 return false;
124
125 return S->Diag(Lambda->getLocStart(),
126 diag::err_lambda_capture_default_arg);
127 }
Chris Lattner8123a952008-04-10 02:22:51 +0000128}
129
Richard Smithe6975e92012-04-17 00:58:00 +0000130void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
131 CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000132 // If we have an MSAny spec already, don't bother.
133 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000134 return;
135
136 const FunctionProtoType *Proto
137 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000138 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
139 if (!Proto)
140 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000141
142 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
143
144 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000145 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000146 ClearExceptions();
147 ComputedEST = EST;
148 return;
149 }
150
Richard Smith7a614d82011-06-11 17:19:42 +0000151 // FIXME: If the call to this decl is using any of its default arguments, we
152 // need to search them for potentially-throwing calls.
153
Sean Hunt001cad92011-05-10 00:49:42 +0000154 // If this function has a basic noexcept, it doesn't affect the outcome.
155 if (EST == EST_BasicNoexcept)
156 return;
157
158 // If we have a throw-all spec at this point, ignore the function.
159 if (ComputedEST == EST_None)
160 return;
161
162 // If we're still at noexcept(true) and there's a nothrow() callee,
163 // change to that specification.
164 if (EST == EST_DynamicNone) {
165 if (ComputedEST == EST_BasicNoexcept)
166 ComputedEST = EST_DynamicNone;
167 return;
168 }
169
170 // Check out noexcept specs.
171 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000172 FunctionProtoType::NoexceptResult NR =
173 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000174 assert(NR != FunctionProtoType::NR_NoNoexcept &&
175 "Must have noexcept result for EST_ComputedNoexcept.");
176 assert(NR != FunctionProtoType::NR_Dependent &&
177 "Should not generate implicit declarations for dependent cases, "
178 "and don't know how to handle them anyway.");
179
180 // noexcept(false) -> no spec on the new function
181 if (NR == FunctionProtoType::NR_Throw) {
182 ClearExceptions();
183 ComputedEST = EST_None;
184 }
185 // noexcept(true) won't change anything either.
186 return;
187 }
188
189 assert(EST == EST_Dynamic && "EST case not considered earlier.");
190 assert(ComputedEST != EST_None &&
191 "Shouldn't collect exceptions when throw-all is guaranteed.");
192 ComputedEST = EST_Dynamic;
193 // Record the exceptions in this function's exception specification.
194 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
195 EEnd = Proto->exception_end();
196 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000197 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000198 Exceptions.push_back(*E);
199}
200
Richard Smith7a614d82011-06-11 17:19:42 +0000201void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000202 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000203 return;
204
205 // FIXME:
206 //
207 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000208 // [An] implicit exception-specification specifies the type-id T if and
209 // only if T is allowed by the exception-specification of a function directly
210 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000211 // function it directly invokes allows all exceptions, and f shall allow no
212 // exceptions if every function it directly invokes allows no exceptions.
213 //
214 // Note in particular that if an implicit exception-specification is generated
215 // for a function containing a throw-expression, that specification can still
216 // be noexcept(true).
217 //
218 // Note also that 'directly invoked' is not defined in the standard, and there
219 // is no indication that we should only consider potentially-evaluated calls.
220 //
221 // Ultimately we should implement the intent of the standard: the exception
222 // specification should be the set of exceptions which can be thrown by the
223 // implicit definition. For now, we assume that any non-nothrow expression can
224 // throw any exception.
225
Richard Smithe6975e92012-04-17 00:58:00 +0000226 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000227 ComputedEST = EST_None;
228}
229
Anders Carlssoned961f92009-08-25 02:29:20 +0000230bool
John McCall9ae2f072010-08-23 23:25:46 +0000231Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000232 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000233 if (RequireCompleteType(Param->getLocation(), Param->getType(),
234 diag::err_typecheck_decl_incomplete_type)) {
235 Param->setInvalidDecl();
236 return true;
237 }
238
Anders Carlssoned961f92009-08-25 02:29:20 +0000239 // C++ [dcl.fct.default]p5
240 // A default argument expression is implicitly converted (clause
241 // 4) to the parameter type. The default argument expression has
242 // the same semantic constraints as the initializer expression in
243 // a declaration of a variable of the parameter type, using the
244 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000245 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
246 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000247 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
248 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000249 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000250 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000251 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000252 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000253 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000254
John McCallb4eb64d2010-10-08 02:01:28 +0000255 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000256 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // Okay: add the default argument to the parameter
259 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000261 // We have already instantiated this parameter; provide each of the
262 // instantiations with the uninstantiated default argument.
263 UnparsedDefaultArgInstantiationsMap::iterator InstPos
264 = UnparsedDefaultArgInstantiations.find(Param);
265 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
266 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
267 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
268
269 // We're done tracking this parameter's instantiations.
270 UnparsedDefaultArgInstantiations.erase(InstPos);
271 }
272
Anders Carlsson9351c172009-08-25 03:18:48 +0000273 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000274}
275
Chris Lattner8123a952008-04-10 02:22:51 +0000276/// ActOnParamDefaultArgument - Check whether the default argument
277/// provided for a function parameter is well-formed. If so, attach it
278/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000279void
John McCalld226f652010-08-21 09:40:31 +0000280Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000281 Expr *DefaultArg) {
282 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000283 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
John McCalld226f652010-08-21 09:40:31 +0000285 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000286 UnparsedDefaultArgLocs.erase(Param);
287
Chris Lattner3d1cee32008-04-08 05:04:30 +0000288 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000289 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000290 Diag(EqualLoc, diag::err_param_default_argument)
291 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000292 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000293 return;
294 }
295
Douglas Gregor6f526752010-12-16 08:48:57 +0000296 // Check for unexpanded parameter packs.
297 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
298 Param->setInvalidDecl();
299 return;
300 }
301
Anders Carlsson66e30672009-08-25 01:02:06 +0000302 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000303 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
304 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000305 Param->setInvalidDecl();
306 return;
307 }
Mike Stump1eb44332009-09-09 15:08:12 +0000308
John McCall9ae2f072010-08-23 23:25:46 +0000309 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000310}
311
Douglas Gregor61366e92008-12-24 00:01:03 +0000312/// ActOnParamUnparsedDefaultArgument - We've seen a default
313/// argument for a function parameter, but we can't parse it yet
314/// because we're inside a class definition. Note that this default
315/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000316void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000317 SourceLocation EqualLoc,
318 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000319 if (!param)
320 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000321
John McCalld226f652010-08-21 09:40:31 +0000322 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000323 if (Param)
324 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Anders Carlsson5e300d12009-06-12 16:51:40 +0000326 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000327}
328
Douglas Gregor72b505b2008-12-16 21:30:33 +0000329/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
330/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000331void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000332 if (!param)
333 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000334
John McCalld226f652010-08-21 09:40:31 +0000335 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Anders Carlsson5e300d12009-06-12 16:51:40 +0000337 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Anders Carlsson5e300d12009-06-12 16:51:40 +0000339 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000340}
341
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000342/// CheckExtraCXXDefaultArguments - Check for any extra default
343/// arguments in the declarator, which is not a function declaration
344/// or definition and therefore is not permitted to have default
345/// arguments. This routine should be invoked for every declarator
346/// that is not a function declaration or definition.
347void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
348 // C++ [dcl.fct.default]p3
349 // A default argument expression shall be specified only in the
350 // parameter-declaration-clause of a function declaration or in a
351 // template-parameter (14.1). It shall not be specified for a
352 // parameter pack. If it is specified in a
353 // parameter-declaration-clause, it shall not occur within a
354 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000355 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000356 DeclaratorChunk &chunk = D.getTypeObject(i);
357 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000358 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
359 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000360 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000361 if (Param->hasUnparsedDefaultArg()) {
362 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
365 delete Toks;
366 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000367 } else if (Param->getDefaultArg()) {
368 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
369 << Param->getDefaultArg()->getSourceRange();
370 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000371 }
372 }
373 }
374 }
375}
376
Craig Topper1a6eac82012-09-21 04:33:26 +0000377/// MergeCXXFunctionDecl - Merge two declarations of the same C++
378/// function, once we already know that they have the same
379/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
380/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000381bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
382 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000383 bool Invalid = false;
384
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000386 // For non-template functions, default arguments can be added in
387 // later declarations of a function in the same
388 // scope. Declarations in different scopes have completely
389 // distinct sets of default arguments. That is, declarations in
390 // inner scopes do not acquire default arguments from
391 // declarations in outer scopes, and vice versa. In a given
392 // function declaration, all parameters subsequent to a
393 // parameter with a default argument shall have default
394 // arguments supplied in this or previous declarations. A
395 // default argument shall not be redefined by a later
396 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000397 //
398 // C++ [dcl.fct.default]p6:
399 // Except for member functions of class templates, the default arguments
400 // in a member function definition that appears outside of the class
401 // definition are added to the set of default arguments provided by the
402 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000403 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
404 ParmVarDecl *OldParam = Old->getParamDecl(p);
405 ParmVarDecl *NewParam = New->getParamDecl(p);
406
James Molloy9cda03f2012-03-13 08:55:35 +0000407 bool OldParamHasDfl = OldParam->hasDefaultArg();
408 bool NewParamHasDfl = NewParam->hasDefaultArg();
409
410 NamedDecl *ND = Old;
411 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
412 // Ignore default parameters of old decl if they are not in
413 // the same scope.
414 OldParamHasDfl = false;
415
416 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000417
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 unsigned DiagDefaultParamID =
419 diag::err_param_default_argument_redefinition;
420
421 // MSVC accepts that default parameters be redefined for member functions
422 // of template class. The new default parameter's value is ignored.
423 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000424 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000425 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
426 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000427 // Merge the old default argument into the new parameter.
428 NewParam->setHasInheritedDefaultArg();
429 if (OldParam->hasUninstantiatedDefaultArg())
430 NewParam->setUninstantiatedDefaultArg(
431 OldParam->getUninstantiatedDefaultArg());
432 else
433 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000434 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000435 Invalid = false;
436 }
437 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000438
Francois Pichet8cf90492011-04-10 04:58:30 +0000439 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
440 // hint here. Alternatively, we could walk the type-source information
441 // for NewParam to find the last source location in the type... but it
442 // isn't worth the effort right now. This is the kind of test case that
443 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000444 // int f(int);
445 // void g(int (*fp)(int) = f);
446 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000447 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000448 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000449
450 // Look for the function declaration where the default argument was
451 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000452 for (FunctionDecl *Older = Old->getPreviousDecl();
453 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000454 if (!Older->getParamDecl(p)->hasDefaultArg())
455 break;
456
457 OldParam = Older->getParamDecl(p);
458 }
459
460 Diag(OldParam->getLocation(), diag::note_previous_definition)
461 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000462 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000463 // Merge the old default argument into the new parameter.
464 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000465 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000466 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000467 if (OldParam->hasUninstantiatedDefaultArg())
468 NewParam->setUninstantiatedDefaultArg(
469 OldParam->getUninstantiatedDefaultArg());
470 else
John McCall3d6c1782010-05-04 01:53:42 +0000471 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000472 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000473 if (New->getDescribedFunctionTemplate()) {
474 // Paragraph 4, quoted above, only applies to non-template functions.
475 Diag(NewParam->getLocation(),
476 diag::err_param_default_argument_template_redecl)
477 << NewParam->getDefaultArgRange();
478 Diag(Old->getLocation(), diag::note_template_prev_declaration)
479 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000480 } else if (New->getTemplateSpecializationKind()
481 != TSK_ImplicitInstantiation &&
482 New->getTemplateSpecializationKind() != TSK_Undeclared) {
483 // C++ [temp.expr.spec]p21:
484 // Default function arguments shall not be specified in a declaration
485 // or a definition for one of the following explicit specializations:
486 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000487 // - the explicit specialization of a member function template;
488 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000489 // template where the class template specialization to which the
490 // member function specialization belongs is implicitly
491 // instantiated.
492 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
493 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
494 << New->getDeclName()
495 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000496 } else if (New->getDeclContext()->isDependentContext()) {
497 // C++ [dcl.fct.default]p6 (DR217):
498 // Default arguments for a member function of a class template shall
499 // be specified on the initial declaration of the member function
500 // within the class template.
501 //
502 // Reading the tea leaves a bit in DR217 and its reference to DR205
503 // leads me to the conclusion that one cannot add default function
504 // arguments for an out-of-line definition of a member function of a
505 // dependent type.
506 int WhichKind = 2;
507 if (CXXRecordDecl *Record
508 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
509 if (Record->getDescribedClassTemplate())
510 WhichKind = 0;
511 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
512 WhichKind = 1;
513 else
514 WhichKind = 2;
515 }
516
517 Diag(NewParam->getLocation(),
518 diag::err_param_default_argument_member_template_redecl)
519 << WhichKind
520 << NewParam->getDefaultArgRange();
521 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000522 }
523 }
524
Richard Smithb8abff62012-11-28 03:45:24 +0000525 // DR1344: If a default argument is added outside a class definition and that
526 // default argument makes the function a special member function, the program
527 // is ill-formed. This can only happen for constructors.
528 if (isa<CXXConstructorDecl>(New) &&
529 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
530 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
531 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
532 if (NewSM != OldSM) {
533 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
534 assert(NewParam->hasDefaultArg());
535 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
536 << NewParam->getDefaultArgRange() << NewSM;
537 Diag(Old->getLocation(), diag::note_previous_declaration);
538 }
539 }
540
Richard Smithff234882012-02-20 23:28:05 +0000541 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000542 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000543 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000544 if (New->isConstexpr() != Old->isConstexpr()) {
545 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
546 << New << New->isConstexpr();
547 Diag(Old->getLocation(), diag::note_previous_declaration);
548 Invalid = true;
549 }
550
Douglas Gregore13ad832010-02-12 07:32:17 +0000551 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000552 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000553
Douglas Gregorcda9c672009-02-16 17:45:42 +0000554 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000555}
556
Sebastian Redl60618fa2011-03-12 11:50:43 +0000557/// \brief Merge the exception specifications of two variable declarations.
558///
559/// This is called when there's a redeclaration of a VarDecl. The function
560/// checks if the redeclaration might have an exception specification and
561/// validates compatibility and merges the specs if necessary.
562void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
563 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000564 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000565 return;
566
567 assert(Context.hasSameType(New->getType(), Old->getType()) &&
568 "Should only be called if types are otherwise the same.");
569
570 QualType NewType = New->getType();
571 QualType OldType = Old->getType();
572
573 // We're only interested in pointers and references to functions, as well
574 // as pointers to member functions.
575 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
576 NewType = R->getPointeeType();
577 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
578 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
579 NewType = P->getPointeeType();
580 OldType = OldType->getAs<PointerType>()->getPointeeType();
581 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
582 NewType = M->getPointeeType();
583 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
584 }
585
586 if (!NewType->isFunctionProtoType())
587 return;
588
589 // There's lots of special cases for functions. For function pointers, system
590 // libraries are hopefully not as broken so that we don't need these
591 // workarounds.
592 if (CheckEquivalentExceptionSpec(
593 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
594 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
595 New->setInvalidDecl();
596 }
597}
598
Chris Lattner3d1cee32008-04-08 05:04:30 +0000599/// CheckCXXDefaultArguments - Verify that the default arguments for a
600/// function declaration are well-formed according to C++
601/// [dcl.fct.default].
602void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
603 unsigned NumParams = FD->getNumParams();
604 unsigned p;
605
Douglas Gregorc6889e72012-02-14 22:28:59 +0000606 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
607 isa<CXXMethodDecl>(FD) &&
608 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
609
Chris Lattner3d1cee32008-04-08 05:04:30 +0000610 // Find first parameter with a default argument
611 for (p = 0; p < NumParams; ++p) {
612 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000613 if (Param->hasDefaultArg()) {
614 // C++11 [expr.prim.lambda]p5:
615 // [...] Default arguments (8.3.6) shall not be specified in the
616 // parameter-declaration-clause of a lambda-declarator.
617 //
618 // FIXME: Core issue 974 strikes this sentence, we only provide an
619 // extension warning.
620 if (IsLambda)
621 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
622 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000623 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000624 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000625 }
626
627 // C++ [dcl.fct.default]p4:
628 // In a given function declaration, all parameters
629 // subsequent to a parameter with a default argument shall
630 // have default arguments supplied in this or previous
631 // declarations. A default argument shall not be redefined
632 // by a later declaration (not even to the same value).
633 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000634 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000635 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000636 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000637 if (Param->isInvalidDecl())
638 /* We already complained about this parameter. */;
639 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000640 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000641 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000642 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000643 else
Mike Stump1eb44332009-09-09 15:08:12 +0000644 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000645 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattner3d1cee32008-04-08 05:04:30 +0000647 LastMissingDefaultArg = p;
648 }
649 }
650
651 if (LastMissingDefaultArg > 0) {
652 // Some default arguments were missing. Clear out all of the
653 // default arguments up to (and including) the last missing
654 // default argument, so that we leave the function parameters
655 // in a semantically valid state.
656 for (p = 0; p <= LastMissingDefaultArg; ++p) {
657 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000658 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000659 Param->setDefaultArg(0);
660 }
661 }
662 }
663}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000664
Richard Smith9f569cc2011-10-01 02:31:28 +0000665// CheckConstexprParameterTypes - Check whether a function's parameter types
666// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000667// diagnostic and return false.
668static bool CheckConstexprParameterTypes(Sema &SemaRef,
669 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000670 unsigned ArgIndex = 0;
671 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
672 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
673 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
674 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
675 SourceLocation ParamLoc = PD->getLocation();
676 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000677 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000678 diag::err_constexpr_non_literal_param,
679 ArgIndex+1, PD->getSourceRange(),
680 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000681 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000682 }
Joao Matos17d35c32012-08-31 22:18:20 +0000683 return true;
684}
685
686/// \brief Get diagnostic %select index for tag kind for
687/// record diagnostic message.
688/// WARNING: Indexes apply to particular diagnostics only!
689///
690/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000691static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000692 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000693 case TTK_Struct: return 0;
694 case TTK_Interface: return 1;
695 case TTK_Class: return 2;
696 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000697 }
Joao Matos17d35c32012-08-31 22:18:20 +0000698}
699
700// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
701// the requirements of a constexpr function definition or a constexpr
702// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000703// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000704//
Richard Smith86c3ae42012-02-13 03:54:03 +0000705// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
706bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000707 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
708 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000709 // C++11 [dcl.constexpr]p4:
710 // The definition of a constexpr constructor shall satisfy the following
711 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000712 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000713 const CXXRecordDecl *RD = MD->getParent();
714 if (RD->getNumVBases()) {
715 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
716 << isa<CXXConstructorDecl>(NewFD)
717 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
718 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
719 E = RD->vbases_end(); I != E; ++I)
720 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000721 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000722 return false;
723 }
Richard Smith35340502012-01-13 04:54:00 +0000724 }
725
726 if (!isa<CXXConstructorDecl>(NewFD)) {
727 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 // The definition of a constexpr function shall satisfy the following
729 // constraints:
730 // - it shall not be virtual;
731 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
732 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000733 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000734
Richard Smith86c3ae42012-02-13 03:54:03 +0000735 // If it's not obvious why this function is virtual, find an overridden
736 // function which uses the 'virtual' keyword.
737 const CXXMethodDecl *WrittenVirtual = Method;
738 while (!WrittenVirtual->isVirtualAsWritten())
739 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
740 if (WrittenVirtual != Method)
741 Diag(WrittenVirtual->getLocation(),
742 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000743 return false;
744 }
745
746 // - its return type shall be a literal type;
747 QualType RT = NewFD->getResultType();
748 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000750 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000751 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000752 }
753
Richard Smith35340502012-01-13 04:54:00 +0000754 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000755 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000756 return false;
757
Richard Smith9f569cc2011-10-01 02:31:28 +0000758 return true;
759}
760
761/// Check the given declaration statement is legal within a constexpr function
762/// body. C++0x [dcl.constexpr]p3,p4.
763///
764/// \return true if the body is OK, false if we have diagnosed a problem.
765static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
766 DeclStmt *DS) {
767 // C++0x [dcl.constexpr]p3 and p4:
768 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
769 // contain only
770 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
771 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
772 switch ((*DclIt)->getKind()) {
773 case Decl::StaticAssert:
774 case Decl::Using:
775 case Decl::UsingShadow:
776 case Decl::UsingDirective:
777 case Decl::UnresolvedUsingTypename:
778 // - static_assert-declarations
779 // - using-declarations,
780 // - using-directives,
781 continue;
782
783 case Decl::Typedef:
784 case Decl::TypeAlias: {
785 // - typedef declarations and alias-declarations that do not define
786 // classes or enumerations,
787 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
788 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
789 // Don't allow variably-modified types in constexpr functions.
790 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
791 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
792 << TL.getSourceRange() << TL.getType()
793 << isa<CXXConstructorDecl>(Dcl);
794 return false;
795 }
796 continue;
797 }
798
799 case Decl::Enum:
800 case Decl::CXXRecord:
801 // As an extension, we allow the declaration (but not the definition) of
802 // classes and enumerations in all declarations, not just in typedef and
803 // alias declarations.
804 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
805 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
806 << isa<CXXConstructorDecl>(Dcl);
807 return false;
808 }
809 continue;
810
811 case Decl::Var:
812 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
813 << isa<CXXConstructorDecl>(Dcl);
814 return false;
815
816 default:
817 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
818 << isa<CXXConstructorDecl>(Dcl);
819 return false;
820 }
821 }
822
823 return true;
824}
825
826/// Check that the given field is initialized within a constexpr constructor.
827///
828/// \param Dcl The constexpr constructor being checked.
829/// \param Field The field being checked. This may be a member of an anonymous
830/// struct or union nested within the class being checked.
831/// \param Inits All declarations, including anonymous struct/union members and
832/// indirect members, for which any initialization was provided.
833/// \param Diagnosed Set to true if an error is produced.
834static void CheckConstexprCtorInitializer(Sema &SemaRef,
835 const FunctionDecl *Dcl,
836 FieldDecl *Field,
837 llvm::SmallSet<Decl*, 16> &Inits,
838 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000839 if (Field->isUnnamedBitfield())
840 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000841
842 if (Field->isAnonymousStructOrUnion() &&
843 Field->getType()->getAsCXXRecordDecl()->isEmpty())
844 return;
845
Richard Smith9f569cc2011-10-01 02:31:28 +0000846 if (!Inits.count(Field)) {
847 if (!Diagnosed) {
848 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
849 Diagnosed = true;
850 }
851 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
852 } else if (Field->isAnonymousStructOrUnion()) {
853 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
854 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
855 I != E; ++I)
856 // If an anonymous union contains an anonymous struct of which any member
857 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000858 if (!RD->isUnion() || Inits.count(*I))
859 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000860 }
861}
862
863/// Check the body for the given constexpr function declaration only contains
864/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
865///
866/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000867bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000868 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000869 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000870 // The definition of a constexpr function shall satisfy the following
871 // constraints: [...]
872 // - its function-body shall be = delete, = default, or a
873 // compound-statement
874 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000875 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000876 // In the definition of a constexpr constructor, [...]
877 // - its function-body shall not be a function-try-block;
878 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882
883 // - its function-body shall be [...] a compound-statement that contains only
884 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
885
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000886 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smith9f569cc2011-10-01 02:31:28 +0000887 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
888 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
889 switch ((*BodyIt)->getStmtClass()) {
890 case Stmt::NullStmtClass:
891 // - null statements,
892 continue;
893
894 case Stmt::DeclStmtClass:
895 // - static_assert-declarations
896 // - using-declarations,
897 // - using-directives,
898 // - typedef declarations and alias-declarations that do not define
899 // classes or enumerations,
900 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
901 return false;
902 continue;
903
904 case Stmt::ReturnStmtClass:
905 // - and exactly one return statement;
906 if (isa<CXXConstructorDecl>(Dcl))
907 break;
908
909 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000910 continue;
911
912 default:
913 break;
914 }
915
916 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
917 << isa<CXXConstructorDecl>(Dcl);
918 return false;
919 }
920
921 if (const CXXConstructorDecl *Constructor
922 = dyn_cast<CXXConstructorDecl>(Dcl)) {
923 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000924 // DR1359:
925 // - every non-variant non-static data member and base class sub-object
926 // shall be initialized;
927 // - if the class is a non-empty union, or for each non-empty anonymous
928 // union member of a non-union class, exactly one non-static data member
929 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000930 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000931 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000932 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
933 return false;
934 }
Richard Smith6e433752011-10-10 16:38:04 +0000935 } else if (!Constructor->isDependentContext() &&
936 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000937 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
938
939 // Skip detailed checking if we have enough initializers, and we would
940 // allow at most one initializer per member.
941 bool AnyAnonStructUnionMembers = false;
942 unsigned Fields = 0;
943 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
944 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000945 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000946 AnyAnonStructUnionMembers = true;
947 break;
948 }
949 }
950 if (AnyAnonStructUnionMembers ||
951 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
952 // Check initialization of non-static data members. Base classes are
953 // always initialized so do not need to be checked. Dependent bases
954 // might not have initializers in the member initializer list.
955 llvm::SmallSet<Decl*, 16> Inits;
956 for (CXXConstructorDecl::init_const_iterator
957 I = Constructor->init_begin(), E = Constructor->init_end();
958 I != E; ++I) {
959 if (FieldDecl *FD = (*I)->getMember())
960 Inits.insert(FD);
961 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
962 Inits.insert(ID->chain_begin(), ID->chain_end());
963 }
964
965 bool Diagnosed = false;
966 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
967 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000968 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000969 if (Diagnosed)
970 return false;
971 }
972 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000973 } else {
974 if (ReturnStmts.empty()) {
975 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
976 return false;
977 }
978 if (ReturnStmts.size() > 1) {
979 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
980 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
981 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
982 return false;
983 }
984 }
985
Richard Smith5ba73e12012-02-04 00:33:54 +0000986 // C++11 [dcl.constexpr]p5:
987 // if no function argument values exist such that the function invocation
988 // substitution would produce a constant expression, the program is
989 // ill-formed; no diagnostic required.
990 // C++11 [dcl.constexpr]p3:
991 // - every constructor call and implicit conversion used in initializing the
992 // return value shall be one of those allowed in a constant expression.
993 // C++11 [dcl.constexpr]p4:
994 // - every constructor involved in initializing non-static data members and
995 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000996 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000997 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +0000998 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +0000999 << isa<CXXConstructorDecl>(Dcl);
1000 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1001 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001002 // Don't return false here: we allow this for compatibility in
1003 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001004 }
1005
Richard Smith9f569cc2011-10-01 02:31:28 +00001006 return true;
1007}
1008
Douglas Gregorb48fe382008-10-31 09:07:45 +00001009/// isCurrentClassName - Determine whether the identifier II is the
1010/// name of the class type currently being defined. In the case of
1011/// nested classes, this will only return true if II is the name of
1012/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001013bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1014 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001015 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001016
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001017 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001018 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001019 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001020 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1021 } else
1022 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1023
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001024 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001025 return &II == CurDecl->getIdentifier();
1026 else
1027 return false;
1028}
1029
Douglas Gregor229d47a2012-11-10 07:24:09 +00001030/// \brief Determine whether the given class is a base class of the given
1031/// class, including looking at dependent bases.
1032static bool findCircularInheritance(const CXXRecordDecl *Class,
1033 const CXXRecordDecl *Current) {
1034 SmallVector<const CXXRecordDecl*, 8> Queue;
1035
1036 Class = Class->getCanonicalDecl();
1037 while (true) {
1038 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1039 E = Current->bases_end();
1040 I != E; ++I) {
1041 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1042 if (!Base)
1043 continue;
1044
1045 Base = Base->getDefinition();
1046 if (!Base)
1047 continue;
1048
1049 if (Base->getCanonicalDecl() == Class)
1050 return true;
1051
1052 Queue.push_back(Base);
1053 }
1054
1055 if (Queue.empty())
1056 return false;
1057
1058 Current = Queue.back();
1059 Queue.pop_back();
1060 }
1061
1062 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001063}
1064
Mike Stump1eb44332009-09-09 15:08:12 +00001065/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001066///
1067/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1068/// and returns NULL otherwise.
1069CXXBaseSpecifier *
1070Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1071 SourceRange SpecifierRange,
1072 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001073 TypeSourceInfo *TInfo,
1074 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001075 QualType BaseType = TInfo->getType();
1076
Douglas Gregor2943aed2009-03-03 04:44:36 +00001077 // C++ [class.union]p1:
1078 // A union shall not have base classes.
1079 if (Class->isUnion()) {
1080 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1081 << SpecifierRange;
1082 return 0;
1083 }
1084
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001085 if (EllipsisLoc.isValid() &&
1086 !TInfo->getType()->containsUnexpandedParameterPack()) {
1087 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1088 << TInfo->getTypeLoc().getSourceRange();
1089 EllipsisLoc = SourceLocation();
1090 }
Douglas Gregord777e282012-11-10 01:18:17 +00001091
1092 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1093
1094 if (BaseType->isDependentType()) {
1095 // Make sure that we don't have circular inheritance among our dependent
1096 // bases. For non-dependent bases, the check for completeness below handles
1097 // this.
1098 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1099 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1100 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001101 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001102 Diag(BaseLoc, diag::err_circular_inheritance)
1103 << BaseType << Context.getTypeDeclType(Class);
1104
1105 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1106 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1107 << BaseType;
1108
1109 return 0;
1110 }
1111 }
1112
Mike Stump1eb44332009-09-09 15:08:12 +00001113 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001114 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001115 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001116 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001117
1118 // Base specifiers must be record types.
1119 if (!BaseType->isRecordType()) {
1120 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1121 return 0;
1122 }
1123
1124 // C++ [class.union]p1:
1125 // A union shall not be used as a base class.
1126 if (BaseType->isUnionType()) {
1127 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1128 return 0;
1129 }
1130
1131 // C++ [class.derived]p2:
1132 // The class-name in a base-specifier shall not be an incompletely
1133 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001134 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001135 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001136 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001137 return 0;
John McCall572fc622010-08-17 07:23:57 +00001138 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001139
Eli Friedman1d954f62009-08-15 21:55:26 +00001140 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001141 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001142 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001143 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001144 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001145 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1146 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001147
Anders Carlsson1d209272011-03-25 14:55:14 +00001148 // C++ [class]p3:
1149 // If a class is marked final and it appears as a base-type-specifier in
1150 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001151 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001152 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1153 << CXXBaseDecl->getDeclName();
1154 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1155 << CXXBaseDecl->getDeclName();
1156 return 0;
1157 }
1158
John McCall572fc622010-08-17 07:23:57 +00001159 if (BaseDecl->isInvalidDecl())
1160 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001161
1162 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001163 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001164 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001165 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001166}
1167
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001168/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1169/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001170/// example:
1171/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001172/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001173BaseResult
John McCalld226f652010-08-21 09:40:31 +00001174Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001175 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001176 ParsedType basetype, SourceLocation BaseLoc,
1177 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001178 if (!classdecl)
1179 return true;
1180
Douglas Gregor40808ce2009-03-09 23:48:35 +00001181 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001182 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001183 if (!Class)
1184 return true;
1185
Nick Lewycky56062202010-07-26 16:56:01 +00001186 TypeSourceInfo *TInfo = 0;
1187 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001188
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001189 if (EllipsisLoc.isInvalid() &&
1190 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001191 UPPC_BaseType))
1192 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001193
Douglas Gregor2943aed2009-03-03 04:44:36 +00001194 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001195 Virtual, Access, TInfo,
1196 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001197 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001198 else
1199 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Douglas Gregor2943aed2009-03-03 04:44:36 +00001201 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001202}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001203
Douglas Gregor2943aed2009-03-03 04:44:36 +00001204/// \brief Performs the actual work of attaching the given base class
1205/// specifiers to a C++ class.
1206bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1207 unsigned NumBases) {
1208 if (NumBases == 0)
1209 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001210
1211 // Used to keep track of which base types we have already seen, so
1212 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001213 // that the key is always the unqualified canonical type of the base
1214 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001215 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1216
1217 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001218 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001219 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001220 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001221 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001222 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001223 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001224
1225 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1226 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001227 // C++ [class.mi]p3:
1228 // A class shall not be specified as a direct base class of a
1229 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001230 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001231 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001232 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001233 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001234
1235 // Delete the duplicate base class specifier; we're going to
1236 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001237 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001238
1239 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001240 } else {
1241 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001242 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001243 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001244 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1245 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1246 if (Class->isInterface() &&
1247 (!RD->isInterface() ||
1248 KnownBase->getAccessSpecifier() != AS_public)) {
1249 // The Microsoft extension __interface does not permit bases that
1250 // are not themselves public interfaces.
1251 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1252 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1253 << RD->getSourceRange();
1254 Invalid = true;
1255 }
1256 if (RD->hasAttr<WeakAttr>())
1257 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1258 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001259 }
1260 }
1261
1262 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001263 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001264
1265 // Delete the remaining (good) base class specifiers, since their
1266 // data has been copied into the CXXRecordDecl.
1267 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001268 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001269
1270 return Invalid;
1271}
1272
1273/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1274/// class, after checking whether there are any duplicate base
1275/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001276void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001277 unsigned NumBases) {
1278 if (!ClassDecl || !Bases || !NumBases)
1279 return;
1280
1281 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001282 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001283 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001284}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001285
John McCall3cb0ebd2010-03-10 03:28:59 +00001286static CXXRecordDecl *GetClassForType(QualType T) {
1287 if (const RecordType *RT = T->getAs<RecordType>())
1288 return cast<CXXRecordDecl>(RT->getDecl());
1289 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1290 return ICT->getDecl();
1291 else
1292 return 0;
1293}
1294
Douglas Gregora8f32e02009-10-06 17:59:45 +00001295/// \brief Determine whether the type \p Derived is a C++ class that is
1296/// derived from the type \p Base.
1297bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001298 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001299 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001300
1301 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1302 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001303 return false;
1304
John McCall3cb0ebd2010-03-10 03:28:59 +00001305 CXXRecordDecl *BaseRD = GetClassForType(Base);
1306 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001307 return false;
1308
John McCall86ff3082010-02-04 22:26:26 +00001309 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1310 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001311}
1312
1313/// \brief Determine whether the type \p Derived is a C++ class that is
1314/// derived from the type \p Base.
1315bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001316 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001317 return false;
1318
John McCall3cb0ebd2010-03-10 03:28:59 +00001319 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1320 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001321 return false;
1322
John McCall3cb0ebd2010-03-10 03:28:59 +00001323 CXXRecordDecl *BaseRD = GetClassForType(Base);
1324 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001325 return false;
1326
Douglas Gregora8f32e02009-10-06 17:59:45 +00001327 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1328}
1329
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001330void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001331 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001332 assert(BasePathArray.empty() && "Base path array must be empty!");
1333 assert(Paths.isRecordingPaths() && "Must record paths!");
1334
1335 const CXXBasePath &Path = Paths.front();
1336
1337 // We first go backward and check if we have a virtual base.
1338 // FIXME: It would be better if CXXBasePath had the base specifier for
1339 // the nearest virtual base.
1340 unsigned Start = 0;
1341 for (unsigned I = Path.size(); I != 0; --I) {
1342 if (Path[I - 1].Base->isVirtual()) {
1343 Start = I - 1;
1344 break;
1345 }
1346 }
1347
1348 // Now add all bases.
1349 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001350 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001351}
1352
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001353/// \brief Determine whether the given base path includes a virtual
1354/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001355bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1356 for (CXXCastPath::const_iterator B = BasePath.begin(),
1357 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001358 B != BEnd; ++B)
1359 if ((*B)->isVirtual())
1360 return true;
1361
1362 return false;
1363}
1364
Douglas Gregora8f32e02009-10-06 17:59:45 +00001365/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1366/// conversion (where Derived and Base are class types) is
1367/// well-formed, meaning that the conversion is unambiguous (and
1368/// that all of the base classes are accessible). Returns true
1369/// and emits a diagnostic if the code is ill-formed, returns false
1370/// otherwise. Loc is the location where this routine should point to
1371/// if there is an error, and Range is the source range to highlight
1372/// if there is an error.
1373bool
1374Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001375 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001376 unsigned AmbigiousBaseConvID,
1377 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001378 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001379 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001380 // First, determine whether the path from Derived to Base is
1381 // ambiguous. This is slightly more expensive than checking whether
1382 // the Derived to Base conversion exists, because here we need to
1383 // explore multiple paths to determine if there is an ambiguity.
1384 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1385 /*DetectVirtual=*/false);
1386 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1387 assert(DerivationOkay &&
1388 "Can only be used with a derived-to-base conversion");
1389 (void)DerivationOkay;
1390
1391 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001392 if (InaccessibleBaseID) {
1393 // Check that the base class can be accessed.
1394 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1395 InaccessibleBaseID)) {
1396 case AR_inaccessible:
1397 return true;
1398 case AR_accessible:
1399 case AR_dependent:
1400 case AR_delayed:
1401 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001402 }
John McCall6b2accb2010-02-10 09:31:12 +00001403 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001404
1405 // Build a base path if necessary.
1406 if (BasePath)
1407 BuildBasePathArray(Paths, *BasePath);
1408 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001409 }
1410
1411 // We know that the derived-to-base conversion is ambiguous, and
1412 // we're going to produce a diagnostic. Perform the derived-to-base
1413 // search just one more time to compute all of the possible paths so
1414 // that we can print them out. This is more expensive than any of
1415 // the previous derived-to-base checks we've done, but at this point
1416 // performance isn't as much of an issue.
1417 Paths.clear();
1418 Paths.setRecordingPaths(true);
1419 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1420 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1421 (void)StillOkay;
1422
1423 // Build up a textual representation of the ambiguous paths, e.g.,
1424 // D -> B -> A, that will be used to illustrate the ambiguous
1425 // conversions in the diagnostic. We only print one of the paths
1426 // to each base class subobject.
1427 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1428
1429 Diag(Loc, AmbigiousBaseConvID)
1430 << Derived << Base << PathDisplayStr << Range << Name;
1431 return true;
1432}
1433
1434bool
1435Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001436 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001437 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001438 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001439 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001440 IgnoreAccess ? 0
1441 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001442 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001443 Loc, Range, DeclarationName(),
1444 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001445}
1446
1447
1448/// @brief Builds a string representing ambiguous paths from a
1449/// specific derived class to different subobjects of the same base
1450/// class.
1451///
1452/// This function builds a string that can be used in error messages
1453/// to show the different paths that one can take through the
1454/// inheritance hierarchy to go from the derived class to different
1455/// subobjects of a base class. The result looks something like this:
1456/// @code
1457/// struct D -> struct B -> struct A
1458/// struct D -> struct C -> struct A
1459/// @endcode
1460std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1461 std::string PathDisplayStr;
1462 std::set<unsigned> DisplayedPaths;
1463 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1464 Path != Paths.end(); ++Path) {
1465 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1466 // We haven't displayed a path to this particular base
1467 // class subobject yet.
1468 PathDisplayStr += "\n ";
1469 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1470 for (CXXBasePath::const_iterator Element = Path->begin();
1471 Element != Path->end(); ++Element)
1472 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1473 }
1474 }
1475
1476 return PathDisplayStr;
1477}
1478
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001479//===----------------------------------------------------------------------===//
1480// C++ class member Handling
1481//===----------------------------------------------------------------------===//
1482
Abramo Bagnara6206d532010-06-05 05:09:32 +00001483/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001484bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1485 SourceLocation ASLoc,
1486 SourceLocation ColonLoc,
1487 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001488 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001489 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001490 ASLoc, ColonLoc);
1491 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001492 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001493}
1494
Richard Smitha4b39652012-08-06 03:25:17 +00001495/// CheckOverrideControl - Check C++11 override control semantics.
1496void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001497 if (D->isInvalidDecl())
1498 return;
1499
Chris Lattner5f9e2722011-07-23 10:55:15 +00001500 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001501
Richard Smitha4b39652012-08-06 03:25:17 +00001502 // Do we know which functions this declaration might be overriding?
1503 bool OverridesAreKnown = !MD ||
1504 (!MD->getParent()->hasAnyDependentBases() &&
1505 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001506
Richard Smitha4b39652012-08-06 03:25:17 +00001507 if (!MD || !MD->isVirtual()) {
1508 if (OverridesAreKnown) {
1509 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1510 Diag(OA->getLocation(),
1511 diag::override_keyword_only_allowed_on_virtual_member_functions)
1512 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1513 D->dropAttr<OverrideAttr>();
1514 }
1515 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1516 Diag(FA->getLocation(),
1517 diag::override_keyword_only_allowed_on_virtual_member_functions)
1518 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1519 D->dropAttr<FinalAttr>();
1520 }
1521 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001522 return;
1523 }
Richard Smitha4b39652012-08-06 03:25:17 +00001524
1525 if (!OverridesAreKnown)
1526 return;
1527
1528 // C++11 [class.virtual]p5:
1529 // If a virtual function is marked with the virt-specifier override and
1530 // does not override a member function of a base class, the program is
1531 // ill-formed.
1532 bool HasOverriddenMethods =
1533 MD->begin_overridden_methods() != MD->end_overridden_methods();
1534 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1535 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1536 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001537}
1538
Richard Smitha4b39652012-08-06 03:25:17 +00001539/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001540/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001541/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001542bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1543 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001544 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001545 return false;
1546
1547 Diag(New->getLocation(), diag::err_final_function_overridden)
1548 << New->getDeclName();
1549 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1550 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001551}
1552
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001553static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001554 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1555 // FIXME: Destruction of ObjC lifetime types has side-effects.
1556 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1557 return !RD->isCompleteDefinition() ||
1558 !RD->hasTrivialDefaultConstructor() ||
1559 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001560 return false;
1561}
1562
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001563/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1564/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001565/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001566/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1567/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001568NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001569Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001570 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001571 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001572 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001573 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001574 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1575 DeclarationName Name = NameInfo.getName();
1576 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001577
1578 // For anonymous bitfields, the location should point to the type.
1579 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001580 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001581
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001582 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001583
John McCall4bde1e12010-06-04 08:34:12 +00001584 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001585 assert(!DS.isFriendSpecified());
1586
Richard Smith1ab0d902011-06-25 02:28:38 +00001587 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001588
John McCalle402e722012-09-25 07:32:39 +00001589 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1590 // The Microsoft extension __interface only permits public member functions
1591 // and prohibits constructors, destructors, operators, non-public member
1592 // functions, static methods and data members.
1593 unsigned InvalidDecl;
1594 bool ShowDeclName = true;
1595 if (!isFunc)
1596 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1597 else if (AS != AS_public)
1598 InvalidDecl = 2;
1599 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1600 InvalidDecl = 3;
1601 else switch (Name.getNameKind()) {
1602 case DeclarationName::CXXConstructorName:
1603 InvalidDecl = 4;
1604 ShowDeclName = false;
1605 break;
1606
1607 case DeclarationName::CXXDestructorName:
1608 InvalidDecl = 5;
1609 ShowDeclName = false;
1610 break;
1611
1612 case DeclarationName::CXXOperatorName:
1613 case DeclarationName::CXXConversionFunctionName:
1614 InvalidDecl = 6;
1615 break;
1616
1617 default:
1618 InvalidDecl = 0;
1619 break;
1620 }
1621
1622 if (InvalidDecl) {
1623 if (ShowDeclName)
1624 Diag(Loc, diag::err_invalid_member_in_interface)
1625 << (InvalidDecl-1) << Name;
1626 else
1627 Diag(Loc, diag::err_invalid_member_in_interface)
1628 << (InvalidDecl-1) << "";
1629 return 0;
1630 }
1631 }
1632
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001633 // C++ 9.2p6: A member shall not be declared to have automatic storage
1634 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001635 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1636 // data members and cannot be applied to names declared const or static,
1637 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001638 switch (DS.getStorageClassSpec()) {
1639 case DeclSpec::SCS_unspecified:
1640 case DeclSpec::SCS_typedef:
1641 case DeclSpec::SCS_static:
1642 // FALL THROUGH.
1643 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001644 case DeclSpec::SCS_mutable:
1645 if (isFunc) {
1646 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001647 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001648 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001649 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Sebastian Redla11f42f2008-11-17 23:24:37 +00001651 // FIXME: It would be nicer if the keyword was ignored only for this
1652 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001653 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001654 }
1655 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001656 default:
1657 if (DS.getStorageClassSpecLoc().isValid())
1658 Diag(DS.getStorageClassSpecLoc(),
1659 diag::err_storageclass_invalid_for_member);
1660 else
1661 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1662 D.getMutableDeclSpec().ClearStorageClassSpecs();
1663 }
1664
Sebastian Redl669d5d72008-11-14 23:42:31 +00001665 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1666 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001667 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001668
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001669 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001670 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001671 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001672
1673 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001674 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001675 Diag(Loc, diag::err_bad_variable_name)
1676 << Name;
1677 return 0;
1678 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001679
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001680 IdentifierInfo *II = Name.getAsIdentifierInfo();
1681
Douglas Gregorf2503652011-09-21 14:40:46 +00001682 // Member field could not be with "template" keyword.
1683 // So TemplateParameterLists should be empty in this case.
1684 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001685 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001686 if (TemplateParams->size()) {
1687 // There is no such thing as a member field template.
1688 Diag(D.getIdentifierLoc(), diag::err_template_member)
1689 << II
1690 << SourceRange(TemplateParams->getTemplateLoc(),
1691 TemplateParams->getRAngleLoc());
1692 } else {
1693 // There is an extraneous 'template<>' for this member.
1694 Diag(TemplateParams->getTemplateLoc(),
1695 diag::err_template_member_noparams)
1696 << II
1697 << SourceRange(TemplateParams->getTemplateLoc(),
1698 TemplateParams->getRAngleLoc());
1699 }
1700 return 0;
1701 }
1702
Douglas Gregor922fff22010-10-13 22:19:53 +00001703 if (SS.isSet() && !SS.isInvalid()) {
1704 // The user provided a superfluous scope specifier inside a class
1705 // definition:
1706 //
1707 // class X {
1708 // int X::member;
1709 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001710 if (DeclContext *DC = computeDeclContext(SS, false))
1711 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001712 else
1713 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1714 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001715
Douglas Gregor922fff22010-10-13 22:19:53 +00001716 SS.clear();
1717 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001718
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001719 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001720 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001721 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001722 } else {
Richard Smithca523302012-06-10 03:12:00 +00001723 assert(InitStyle == ICIS_NoInit);
Richard Smith7a614d82011-06-11 17:19:42 +00001724
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001725 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001726 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001727 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001728 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001729
1730 // Non-instance-fields can't have a bitfield.
1731 if (BitWidth) {
1732 if (Member->isInvalidDecl()) {
1733 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001734 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001735 // C++ 9.6p3: A bit-field shall not be a static member.
1736 // "static member 'A' cannot be a bit-field"
1737 Diag(Loc, diag::err_static_not_bitfield)
1738 << Name << BitWidth->getSourceRange();
1739 } else if (isa<TypedefDecl>(Member)) {
1740 // "typedef member 'x' cannot be a bit-field"
1741 Diag(Loc, diag::err_typedef_not_bitfield)
1742 << Name << BitWidth->getSourceRange();
1743 } else {
1744 // A function typedef ("typedef int f(); f a;").
1745 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1746 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001747 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001748 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001749 }
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Chris Lattner8b963ef2009-03-05 23:01:03 +00001751 BitWidth = 0;
1752 Member->setInvalidDecl();
1753 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001754
1755 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Douglas Gregor37b372b2009-08-20 22:52:58 +00001757 // If we have declared a member function template, set the access of the
1758 // templated declaration as well.
1759 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1760 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001761 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001762
Richard Smitha4b39652012-08-06 03:25:17 +00001763 if (VS.isOverrideSpecified())
1764 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1765 if (VS.isFinalSpecified())
1766 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001767
Douglas Gregorf5251602011-03-08 17:10:18 +00001768 if (VS.getLastLocation().isValid()) {
1769 // Update the end location of a method that has a virt-specifiers.
1770 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1771 MD->setRangeEnd(VS.getLastLocation());
1772 }
Richard Smitha4b39652012-08-06 03:25:17 +00001773
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001774 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001775
Douglas Gregor10bd3682008-11-17 22:58:34 +00001776 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001777
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001778 if (isInstField) {
1779 FieldDecl *FD = cast<FieldDecl>(Member);
1780 FieldCollector->Add(FD);
1781
1782 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1783 FD->getLocation())
1784 != DiagnosticsEngine::Ignored) {
1785 // Remember all explicit private FieldDecls that have a name, no side
1786 // effects and are not part of a dependent type declaration.
1787 if (!FD->isImplicit() && FD->getDeclName() &&
1788 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001789 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001790 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001791 !InitializationHasSideEffects(*FD))
1792 UnusedPrivateFields.insert(FD);
1793 }
1794 }
1795
John McCalld226f652010-08-21 09:40:31 +00001796 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001797}
1798
Hans Wennborg471f9852012-09-18 15:58:06 +00001799namespace {
1800 class UninitializedFieldVisitor
1801 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1802 Sema &S;
1803 ValueDecl *VD;
1804 public:
1805 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1806 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001807 S(S) {
1808 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1809 this->VD = IFD->getAnonField();
1810 else
1811 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001812 }
1813
1814 void HandleExpr(Expr *E) {
1815 if (!E) return;
1816
1817 // Expressions like x(x) sometimes lack the surrounding expressions
1818 // but need to be checked anyways.
1819 HandleValue(E);
1820 Visit(E);
1821 }
1822
1823 void HandleValue(Expr *E) {
1824 E = E->IgnoreParens();
1825
1826 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1827 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001828 return;
1829
1830 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1831 // or union.
1832 MemberExpr *FieldME = ME;
1833
Hans Wennborg471f9852012-09-18 15:58:06 +00001834 Expr *Base = E;
1835 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001836 ME = cast<MemberExpr>(Base);
1837
1838 if (isa<VarDecl>(ME->getMemberDecl()))
1839 return;
1840
1841 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1842 if (!FD->isAnonymousStructOrUnion())
1843 FieldME = ME;
1844
Hans Wennborg471f9852012-09-18 15:58:06 +00001845 Base = ME->getBase();
1846 }
1847
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001848 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001849 unsigned diag = VD->getType()->isReferenceType()
1850 ? diag::warn_reference_field_is_uninit
1851 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001852 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001853 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001854 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001855 }
1856
1857 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1858 HandleValue(CO->getTrueExpr());
1859 HandleValue(CO->getFalseExpr());
1860 return;
1861 }
1862
1863 if (BinaryConditionalOperator *BCO =
1864 dyn_cast<BinaryConditionalOperator>(E)) {
1865 HandleValue(BCO->getCommon());
1866 HandleValue(BCO->getFalseExpr());
1867 return;
1868 }
1869
1870 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1871 switch (BO->getOpcode()) {
1872 default:
1873 return;
1874 case(BO_PtrMemD):
1875 case(BO_PtrMemI):
1876 HandleValue(BO->getLHS());
1877 return;
1878 case(BO_Comma):
1879 HandleValue(BO->getRHS());
1880 return;
1881 }
1882 }
1883 }
1884
1885 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1886 if (E->getCastKind() == CK_LValueToRValue)
1887 HandleValue(E->getSubExpr());
1888
1889 Inherited::VisitImplicitCastExpr(E);
1890 }
1891
1892 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1893 Expr *Callee = E->getCallee();
1894 if (isa<MemberExpr>(Callee))
1895 HandleValue(Callee);
1896
1897 Inherited::VisitCXXMemberCallExpr(E);
1898 }
1899 };
1900 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1901 ValueDecl *VD) {
1902 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1903 }
1904} // namespace
1905
Richard Smith7a614d82011-06-11 17:19:42 +00001906/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001907/// in-class initializer for a non-static C++ class member, and after
1908/// instantiating an in-class initializer in a class template. Such actions
1909/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001910void
Richard Smithca523302012-06-10 03:12:00 +00001911Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001912 Expr *InitExpr) {
1913 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001914 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1915 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001916
1917 if (!InitExpr) {
1918 FD->setInvalidDecl();
1919 FD->removeInClassInitializer();
1920 return;
1921 }
1922
Peter Collingbournefef21892011-10-23 18:59:44 +00001923 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1924 FD->setInvalidDecl();
1925 FD->removeInClassInitializer();
1926 return;
1927 }
1928
Hans Wennborg471f9852012-09-18 15:58:06 +00001929 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1930 != DiagnosticsEngine::Ignored) {
1931 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1932 }
1933
Richard Smith7a614d82011-06-11 17:19:42 +00001934 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00001935 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001936 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001937 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001938 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1939 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001940 Expr **Inits = &InitExpr;
1941 unsigned NumInits = 1;
1942 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001943 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001944 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001945 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001946 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1947 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001948 if (Init.isInvalid()) {
1949 FD->setInvalidDecl();
1950 return;
1951 }
1952
Richard Smithca523302012-06-10 03:12:00 +00001953 CheckImplicitConversions(Init.get(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001954 }
1955
1956 // C++0x [class.base.init]p7:
1957 // The initialization of each base and member constitutes a
1958 // full-expression.
1959 Init = MaybeCreateExprWithCleanups(Init);
1960 if (Init.isInvalid()) {
1961 FD->setInvalidDecl();
1962 return;
1963 }
1964
1965 InitExpr = Init.release();
1966
1967 FD->setInClassInitializer(InitExpr);
1968}
1969
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001970/// \brief Find the direct and/or virtual base specifiers that
1971/// correspond to the given base type, for use in base initialization
1972/// within a constructor.
1973static bool FindBaseInitializer(Sema &SemaRef,
1974 CXXRecordDecl *ClassDecl,
1975 QualType BaseType,
1976 const CXXBaseSpecifier *&DirectBaseSpec,
1977 const CXXBaseSpecifier *&VirtualBaseSpec) {
1978 // First, check for a direct base class.
1979 DirectBaseSpec = 0;
1980 for (CXXRecordDecl::base_class_const_iterator Base
1981 = ClassDecl->bases_begin();
1982 Base != ClassDecl->bases_end(); ++Base) {
1983 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1984 // We found a direct base of this type. That's what we're
1985 // initializing.
1986 DirectBaseSpec = &*Base;
1987 break;
1988 }
1989 }
1990
1991 // Check for a virtual base class.
1992 // FIXME: We might be able to short-circuit this if we know in advance that
1993 // there are no virtual bases.
1994 VirtualBaseSpec = 0;
1995 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1996 // We haven't found a base yet; search the class hierarchy for a
1997 // virtual base class.
1998 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1999 /*DetectVirtual=*/false);
2000 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2001 BaseType, Paths)) {
2002 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2003 Path != Paths.end(); ++Path) {
2004 if (Path->back().Base->isVirtual()) {
2005 VirtualBaseSpec = Path->back().Base;
2006 break;
2007 }
2008 }
2009 }
2010 }
2011
2012 return DirectBaseSpec || VirtualBaseSpec;
2013}
2014
Sebastian Redl6df65482011-09-24 17:48:25 +00002015/// \brief Handle a C++ member initializer using braced-init-list syntax.
2016MemInitResult
2017Sema::ActOnMemInitializer(Decl *ConstructorD,
2018 Scope *S,
2019 CXXScopeSpec &SS,
2020 IdentifierInfo *MemberOrBase,
2021 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002022 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002023 SourceLocation IdLoc,
2024 Expr *InitList,
2025 SourceLocation EllipsisLoc) {
2026 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002027 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002028 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002029}
2030
2031/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002032MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002033Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002034 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002035 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002036 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002037 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002038 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002039 SourceLocation IdLoc,
2040 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002041 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002042 SourceLocation RParenLoc,
2043 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002044 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2045 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002046 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002047 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002048 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002049}
2050
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002051namespace {
2052
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002053// Callback to only accept typo corrections that can be a valid C++ member
2054// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002055class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2056 public:
2057 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2058 : ClassDecl(ClassDecl) {}
2059
2060 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2061 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2062 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2063 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2064 else
2065 return isa<TypeDecl>(ND);
2066 }
2067 return false;
2068 }
2069
2070 private:
2071 CXXRecordDecl *ClassDecl;
2072};
2073
2074}
2075
Sebastian Redl6df65482011-09-24 17:48:25 +00002076/// \brief Handle a C++ member initializer.
2077MemInitResult
2078Sema::BuildMemInitializer(Decl *ConstructorD,
2079 Scope *S,
2080 CXXScopeSpec &SS,
2081 IdentifierInfo *MemberOrBase,
2082 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002083 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002084 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002085 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002086 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002087 if (!ConstructorD)
2088 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002090 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002091
2092 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002093 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002094 if (!Constructor) {
2095 // The user wrote a constructor initializer on a function that is
2096 // not a C++ constructor. Ignore the error for now, because we may
2097 // have more member initializers coming; we'll diagnose it just
2098 // once in ActOnMemInitializers.
2099 return true;
2100 }
2101
2102 CXXRecordDecl *ClassDecl = Constructor->getParent();
2103
2104 // C++ [class.base.init]p2:
2105 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002106 // constructor's class and, if not found in that scope, are looked
2107 // up in the scope containing the constructor's definition.
2108 // [Note: if the constructor's class contains a member with the
2109 // same name as a direct or virtual base class of the class, a
2110 // mem-initializer-id naming the member or base class and composed
2111 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002112 // mem-initializer-id for the hidden base class may be specified
2113 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002114 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002115 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002116 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002117 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002118 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002119 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002120 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2121 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002122 if (EllipsisLoc.isValid())
2123 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002124 << MemberOrBase
2125 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002126
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002127 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002128 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002129 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002130 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002131 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002132 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002133 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002134
2135 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002136 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002137 } else if (DS.getTypeSpecType() == TST_decltype) {
2138 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002139 } else {
2140 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2141 LookupParsedName(R, S, &SS);
2142
2143 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2144 if (!TyD) {
2145 if (R.isAmbiguous()) return true;
2146
John McCallfd225442010-04-09 19:01:14 +00002147 // We don't want access-control diagnostics here.
2148 R.suppressDiagnostics();
2149
Douglas Gregor7a886e12010-01-19 06:46:48 +00002150 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2151 bool NotUnknownSpecialization = false;
2152 DeclContext *DC = computeDeclContext(SS, false);
2153 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2154 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2155
2156 if (!NotUnknownSpecialization) {
2157 // When the scope specifier can refer to a member of an unknown
2158 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002159 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2160 SS.getWithLocInContext(Context),
2161 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002162 if (BaseType.isNull())
2163 return true;
2164
Douglas Gregor7a886e12010-01-19 06:46:48 +00002165 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002166 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002167 }
2168 }
2169
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002170 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002171 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002172 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002173 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002174 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002175 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002176 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2177 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002178 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002179 // We have found a non-static data member with a similar
2180 // name to what was typed; complain and initialize that
2181 // member.
2182 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2183 << MemberOrBase << true << CorrectedQuotedStr
2184 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2185 Diag(Member->getLocation(), diag::note_previous_decl)
2186 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002187
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002188 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002189 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002190 const CXXBaseSpecifier *DirectBaseSpec;
2191 const CXXBaseSpecifier *VirtualBaseSpec;
2192 if (FindBaseInitializer(*this, ClassDecl,
2193 Context.getTypeDeclType(Type),
2194 DirectBaseSpec, VirtualBaseSpec)) {
2195 // We have found a direct or virtual base class with a
2196 // similar name to what was typed; complain and initialize
2197 // that base class.
2198 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002199 << MemberOrBase << false << CorrectedQuotedStr
2200 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002201
2202 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2203 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002204 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002205 diag::note_base_class_specified_here)
2206 << BaseSpec->getType()
2207 << BaseSpec->getSourceRange();
2208
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002209 TyD = Type;
2210 }
2211 }
2212 }
2213
Douglas Gregor7a886e12010-01-19 06:46:48 +00002214 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002215 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002216 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002217 return true;
2218 }
John McCall2b194412009-12-21 10:41:20 +00002219 }
2220
Douglas Gregor7a886e12010-01-19 06:46:48 +00002221 if (BaseType.isNull()) {
2222 BaseType = Context.getTypeDeclType(TyD);
2223 if (SS.isSet()) {
2224 NestedNameSpecifier *Qualifier =
2225 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002226
Douglas Gregor7a886e12010-01-19 06:46:48 +00002227 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002228 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002229 }
John McCall2b194412009-12-21 10:41:20 +00002230 }
2231 }
Mike Stump1eb44332009-09-09 15:08:12 +00002232
John McCalla93c9342009-12-07 02:54:59 +00002233 if (!TInfo)
2234 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002235
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002236 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002237}
2238
Chandler Carruth81c64772011-09-03 01:14:15 +00002239/// Checks a member initializer expression for cases where reference (or
2240/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002241static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2242 Expr *Init,
2243 SourceLocation IdLoc) {
2244 QualType MemberTy = Member->getType();
2245
2246 // We only handle pointers and references currently.
2247 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2248 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2249 return;
2250
2251 const bool IsPointer = MemberTy->isPointerType();
2252 if (IsPointer) {
2253 if (const UnaryOperator *Op
2254 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2255 // The only case we're worried about with pointers requires taking the
2256 // address.
2257 if (Op->getOpcode() != UO_AddrOf)
2258 return;
2259
2260 Init = Op->getSubExpr();
2261 } else {
2262 // We only handle address-of expression initializers for pointers.
2263 return;
2264 }
2265 }
2266
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002267 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2268 // Taking the address of a temporary will be diagnosed as a hard error.
2269 if (IsPointer)
2270 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002271
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002272 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2273 << Member << Init->getSourceRange();
2274 } else if (const DeclRefExpr *DRE
2275 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2276 // We only warn when referring to a non-reference parameter declaration.
2277 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2278 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002279 return;
2280
2281 S.Diag(Init->getExprLoc(),
2282 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2283 : diag::warn_bind_ref_member_to_parameter)
2284 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002285 } else {
2286 // Other initializers are fine.
2287 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002288 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002289
2290 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2291 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002292}
2293
John McCallf312b1e2010-08-26 23:41:50 +00002294MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002295Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002296 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002297 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2298 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2299 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002300 "Member must be a FieldDecl or IndirectFieldDecl");
2301
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002302 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002303 return true;
2304
Douglas Gregor464b2f02010-11-05 22:21:31 +00002305 if (Member->isInvalidDecl())
2306 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002307
John McCallb4190042009-11-04 23:02:40 +00002308 // Diagnose value-uses of fields to initialize themselves, e.g.
2309 // foo(foo)
2310 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002311 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002312 Expr **Args;
2313 unsigned NumArgs;
2314 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2315 Args = ParenList->getExprs();
2316 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002317 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002318 Args = InitList->getInits();
2319 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002320 } else {
2321 // Template instantiation doesn't reconstruct ParenListExprs for us.
2322 Args = &Init;
2323 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002324 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002325
Richard Trieude5e75c2012-06-14 23:11:34 +00002326 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2327 != DiagnosticsEngine::Ignored)
2328 for (unsigned i = 0; i < NumArgs; ++i)
2329 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002330 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002331 // initializing the i'th field, throw a warning if any of the >= i'th
2332 // fields are used, as they are not yet initialized.
2333 // Right now we are only handling the case where the i'th field uses
2334 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002335 // Also need to take into account that some fields may be initialized by
2336 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002337 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002338
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002339 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002340
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002341 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002342 // Can't check initialization for a member of dependent type or when
2343 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002344 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002345 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002346 bool InitList = false;
2347 if (isa<InitListExpr>(Init)) {
2348 InitList = true;
2349 Args = &Init;
2350 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002351
2352 if (isStdInitializerList(Member->getType(), 0)) {
2353 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2354 << /*at end of ctor*/1 << InitRange;
2355 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002356 }
2357
Chandler Carruth894aed92010-12-06 09:23:57 +00002358 // Initialize the member.
2359 InitializedEntity MemberEntity =
2360 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2361 : InitializedEntity::InitializeMember(IndirectMember, 0);
2362 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002363 InitList ? InitializationKind::CreateDirectList(IdLoc)
2364 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2365 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002366
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002367 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2368 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002369 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002370 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002371 if (MemberInit.isInvalid())
2372 return true;
2373
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002374 CheckImplicitConversions(MemberInit.get(),
2375 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002376
2377 // C++0x [class.base.init]p7:
2378 // The initialization of each base and member constitutes a
2379 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002380 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002381 if (MemberInit.isInvalid())
2382 return true;
2383
Richard Smithc83c2302012-12-19 01:39:02 +00002384 Init = MemberInit.get();
2385 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002386 }
2387
Chandler Carruth894aed92010-12-06 09:23:57 +00002388 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002389 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2390 InitRange.getBegin(), Init,
2391 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002392 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002393 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2394 InitRange.getBegin(), Init,
2395 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002396 }
Eli Friedman59c04372009-07-29 19:44:27 +00002397}
2398
John McCallf312b1e2010-08-26 23:41:50 +00002399MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002400Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002401 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002402 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002403 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002404 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002405 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002406 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002407
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002408 bool InitList = true;
2409 Expr **Args = &Init;
2410 unsigned NumArgs = 1;
2411 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2412 InitList = false;
2413 Args = ParenList->getExprs();
2414 NumArgs = ParenList->getNumExprs();
2415 }
2416
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002417 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002418 // Initialize the object.
2419 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2420 QualType(ClassDecl->getTypeForDecl(), 0));
2421 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002422 InitList ? InitializationKind::CreateDirectList(NameLoc)
2423 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2424 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002425 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2426 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002427 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002428 0);
Sean Hunt41717662011-02-26 19:13:13 +00002429 if (DelegationInit.isInvalid())
2430 return true;
2431
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002432 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2433 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002434
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002435 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002436
2437 // C++0x [class.base.init]p7:
2438 // The initialization of each base and member constitutes a
2439 // full-expression.
2440 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2441 if (DelegationInit.isInvalid())
2442 return true;
2443
Eli Friedmand21016f2012-05-19 23:35:23 +00002444 // If we are in a dependent context, template instantiation will
2445 // perform this type-checking again. Just save the arguments that we
2446 // received in a ParenListExpr.
2447 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2448 // of the information that we have about the base
2449 // initializer. However, deconstructing the ASTs is a dicey process,
2450 // and this approach is far more likely to get the corner cases right.
2451 if (CurContext->isDependentContext())
2452 DelegationInit = Owned(Init);
2453
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002454 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002455 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002456 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002457}
2458
2459MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002460Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002461 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002462 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002463 SourceLocation BaseLoc
2464 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002465
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002466 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2467 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2468 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2469
2470 // C++ [class.base.init]p2:
2471 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002472 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002473 // of that class, the mem-initializer is ill-formed. A
2474 // mem-initializer-list can initialize a base class using any
2475 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002476 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002477
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002478 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002479 if (EllipsisLoc.isValid()) {
2480 // This is a pack expansion.
2481 if (!BaseType->containsUnexpandedParameterPack()) {
2482 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002483 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002484
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002485 EllipsisLoc = SourceLocation();
2486 }
2487 } else {
2488 // Check for any unexpanded parameter packs.
2489 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2490 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002491
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002492 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002493 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002494 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002495
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002496 // Check for direct and virtual base classes.
2497 const CXXBaseSpecifier *DirectBaseSpec = 0;
2498 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2499 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002500 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2501 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002502 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002503
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002504 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2505 VirtualBaseSpec);
2506
2507 // C++ [base.class.init]p2:
2508 // Unless the mem-initializer-id names a nonstatic data member of the
2509 // constructor's class or a direct or virtual base of that class, the
2510 // mem-initializer is ill-formed.
2511 if (!DirectBaseSpec && !VirtualBaseSpec) {
2512 // If the class has any dependent bases, then it's possible that
2513 // one of those types will resolve to the same type as
2514 // BaseType. Therefore, just treat this as a dependent base
2515 // class initialization. FIXME: Should we try to check the
2516 // initialization anyway? It seems odd.
2517 if (ClassDecl->hasAnyDependentBases())
2518 Dependent = true;
2519 else
2520 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2521 << BaseType << Context.getTypeDeclType(ClassDecl)
2522 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2523 }
2524 }
2525
2526 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002527 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002528
Sebastian Redl6df65482011-09-24 17:48:25 +00002529 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2530 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002531 InitRange.getBegin(), Init,
2532 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002533 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002534
2535 // C++ [base.class.init]p2:
2536 // If a mem-initializer-id is ambiguous because it designates both
2537 // a direct non-virtual base class and an inherited virtual base
2538 // class, the mem-initializer is ill-formed.
2539 if (DirectBaseSpec && VirtualBaseSpec)
2540 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002541 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002542
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002543 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002544 if (!BaseSpec)
2545 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2546
2547 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002548 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002549 Expr **Args = &Init;
2550 unsigned NumArgs = 1;
2551 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002552 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002553 Args = ParenList->getExprs();
2554 NumArgs = ParenList->getNumExprs();
2555 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002556
2557 InitializedEntity BaseEntity =
2558 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2559 InitializationKind Kind =
2560 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2561 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2562 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002563 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2564 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002565 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002566 if (BaseInit.isInvalid())
2567 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002568
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002569 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002570
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002571 // C++0x [class.base.init]p7:
2572 // The initialization of each base and member constitutes a
2573 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002574 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002575 if (BaseInit.isInvalid())
2576 return true;
2577
2578 // If we are in a dependent context, template instantiation will
2579 // perform this type-checking again. Just save the arguments that we
2580 // received in a ParenListExpr.
2581 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2582 // of the information that we have about the base
2583 // initializer. However, deconstructing the ASTs is a dicey process,
2584 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002585 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002586 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002587
Sean Huntcbb67482011-01-08 20:30:50 +00002588 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002589 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002590 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002591 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002592 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002593}
2594
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002595// Create a static_cast\<T&&>(expr).
2596static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2597 QualType ExprType = E->getType();
2598 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2599 SourceLocation ExprLoc = E->getLocStart();
2600 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2601 TargetType, ExprLoc);
2602
2603 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2604 SourceRange(ExprLoc, ExprLoc),
2605 E->getSourceRange()).take();
2606}
2607
Anders Carlssone5ef7402010-04-23 03:10:23 +00002608/// ImplicitInitializerKind - How an implicit base or member initializer should
2609/// initialize its base or member.
2610enum ImplicitInitializerKind {
2611 IIK_Default,
2612 IIK_Copy,
2613 IIK_Move
2614};
2615
Anders Carlssondefefd22010-04-23 02:00:02 +00002616static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002617BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002618 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002619 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002620 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002621 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002622 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002623 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2624 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002625
John McCall60d7b3a2010-08-24 06:29:42 +00002626 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002627
2628 switch (ImplicitInitKind) {
2629 case IIK_Default: {
2630 InitializationKind InitKind
2631 = InitializationKind::CreateDefault(Constructor->getLocation());
2632 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002633 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002634 break;
2635 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002636
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002637 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002638 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002639 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002640 ParmVarDecl *Param = Constructor->getParamDecl(0);
2641 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002642
Anders Carlssone5ef7402010-04-23 03:10:23 +00002643 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002644 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002645 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002646 Constructor->getLocation(), ParamType,
2647 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002648
Eli Friedman5f2987c2012-02-02 03:46:19 +00002649 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2650
Anders Carlssonc7957502010-04-24 22:02:54 +00002651 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002652 QualType ArgTy =
2653 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2654 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002655
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002656 if (Moving) {
2657 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2658 }
2659
John McCallf871d0c2010-08-07 06:22:56 +00002660 CXXCastPath BasePath;
2661 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002662 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2663 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002664 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002665 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002666
Anders Carlssone5ef7402010-04-23 03:10:23 +00002667 InitializationKind InitKind
2668 = InitializationKind::CreateDirect(Constructor->getLocation(),
2669 SourceLocation(), SourceLocation());
2670 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2671 &CopyCtorArg, 1);
2672 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002673 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002674 break;
2675 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002676 }
John McCall9ae2f072010-08-23 23:25:46 +00002677
Douglas Gregor53c374f2010-12-07 00:41:46 +00002678 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002679 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002680 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002681
Anders Carlssondefefd22010-04-23 02:00:02 +00002682 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002683 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002684 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2685 SourceLocation()),
2686 BaseSpec->isVirtual(),
2687 SourceLocation(),
2688 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002689 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002690 SourceLocation());
2691
Anders Carlssondefefd22010-04-23 02:00:02 +00002692 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002693}
2694
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002695static bool RefersToRValueRef(Expr *MemRef) {
2696 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2697 return Referenced->getType()->isRValueReferenceType();
2698}
2699
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002700static bool
2701BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002702 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002703 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002704 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002705 if (Field->isInvalidDecl())
2706 return true;
2707
Chandler Carruthf186b542010-06-29 23:50:44 +00002708 SourceLocation Loc = Constructor->getLocation();
2709
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002710 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2711 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002712 ParmVarDecl *Param = Constructor->getParamDecl(0);
2713 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002714
2715 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002716 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2717 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002718
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002719 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002720 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002721 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002722 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002723
Eli Friedman5f2987c2012-02-02 03:46:19 +00002724 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2725
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002726 if (Moving) {
2727 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2728 }
2729
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002730 // Build a reference to this field within the parameter.
2731 CXXScopeSpec SS;
2732 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2733 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002734 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2735 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002736 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002737 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002738 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002739 ParamType, Loc,
2740 /*IsArrow=*/false,
2741 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002742 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002743 /*FirstQualifierInScope=*/0,
2744 MemberLookup,
2745 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002746 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002747 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002748
2749 // C++11 [class.copy]p15:
2750 // - if a member m has rvalue reference type T&&, it is direct-initialized
2751 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002752 if (RefersToRValueRef(CtorArg.get())) {
2753 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002754 }
2755
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002756 // When the field we are copying is an array, create index variables for
2757 // each dimension of the array. We use these index variables to subscript
2758 // the source array, and other clients (e.g., CodeGen) will perform the
2759 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002760 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002761 QualType BaseType = Field->getType();
2762 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002763 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002764 while (const ConstantArrayType *Array
2765 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002766 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002767 // Create the iteration variable for this array index.
2768 IdentifierInfo *IterationVarName = 0;
2769 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002770 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002771 llvm::raw_svector_ostream OS(Str);
2772 OS << "__i" << IndexVariables.size();
2773 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2774 }
2775 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002776 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002777 IterationVarName, SizeType,
2778 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002779 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002780 IndexVariables.push_back(IterationVar);
2781
2782 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002783 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002784 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002785 assert(!IterationVarRef.isInvalid() &&
2786 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002787 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2788 assert(!IterationVarRef.isInvalid() &&
2789 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002790
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002791 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002792 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002793 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002794 Loc);
2795 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002796 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002797
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002798 BaseType = Array->getElementType();
2799 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002800
2801 // The array subscript expression is an lvalue, which is wrong for moving.
2802 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002803 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002804
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002805 // Construct the entity that we will be initializing. For an array, this
2806 // will be first element in the array, which may require several levels
2807 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002808 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002809 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002810 if (Indirect)
2811 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2812 else
2813 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002814 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2815 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2816 0,
2817 Entities.back()));
2818
2819 // Direct-initialize to use the copy constructor.
2820 InitializationKind InitKind =
2821 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2822
Sebastian Redl74e611a2011-09-04 18:14:28 +00002823 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002824 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002825 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002826
John McCall60d7b3a2010-08-24 06:29:42 +00002827 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002828 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002829 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002830 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002831 if (MemberInit.isInvalid())
2832 return true;
2833
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002834 if (Indirect) {
2835 assert(IndexVariables.size() == 0 &&
2836 "Indirect field improperly initialized");
2837 CXXMemberInit
2838 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2839 Loc, Loc,
2840 MemberInit.takeAs<Expr>(),
2841 Loc);
2842 } else
2843 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2844 Loc, MemberInit.takeAs<Expr>(),
2845 Loc,
2846 IndexVariables.data(),
2847 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002848 return false;
2849 }
2850
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002851 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2852
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002853 QualType FieldBaseElementType =
2854 SemaRef.Context.getBaseElementType(Field->getType());
2855
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002856 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002857 InitializedEntity InitEntity
2858 = Indirect? InitializedEntity::InitializeMember(Indirect)
2859 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002860 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002861 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002862
2863 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002864 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002865 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002866
Douglas Gregor53c374f2010-12-07 00:41:46 +00002867 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002868 if (MemberInit.isInvalid())
2869 return true;
2870
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002871 if (Indirect)
2872 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2873 Indirect, Loc,
2874 Loc,
2875 MemberInit.get(),
2876 Loc);
2877 else
2878 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2879 Field, Loc, Loc,
2880 MemberInit.get(),
2881 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002882 return false;
2883 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002884
Sean Hunt1f2f3842011-05-17 00:19:05 +00002885 if (!Field->getParent()->isUnion()) {
2886 if (FieldBaseElementType->isReferenceType()) {
2887 SemaRef.Diag(Constructor->getLocation(),
2888 diag::err_uninitialized_member_in_ctor)
2889 << (int)Constructor->isImplicit()
2890 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2891 << 0 << Field->getDeclName();
2892 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2893 return true;
2894 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002895
Sean Hunt1f2f3842011-05-17 00:19:05 +00002896 if (FieldBaseElementType.isConstQualified()) {
2897 SemaRef.Diag(Constructor->getLocation(),
2898 diag::err_uninitialized_member_in_ctor)
2899 << (int)Constructor->isImplicit()
2900 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2901 << 1 << Field->getDeclName();
2902 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2903 return true;
2904 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002905 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002906
David Blaikie4e4d0842012-03-11 07:00:24 +00002907 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002908 FieldBaseElementType->isObjCRetainableType() &&
2909 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2910 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002911 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002912 // Default-initialize Objective-C pointers to NULL.
2913 CXXMemberInit
2914 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2915 Loc, Loc,
2916 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2917 Loc);
2918 return false;
2919 }
2920
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002921 // Nothing to initialize.
2922 CXXMemberInit = 0;
2923 return false;
2924}
John McCallf1860e52010-05-20 23:23:51 +00002925
2926namespace {
2927struct BaseAndFieldInfo {
2928 Sema &S;
2929 CXXConstructorDecl *Ctor;
2930 bool AnyErrorsInInits;
2931 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002932 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002933 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002934
2935 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2936 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002937 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2938 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002939 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002940 else if (Generated && Ctor->isMoveConstructor())
2941 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002942 else
2943 IIK = IIK_Default;
2944 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002945
2946 bool isImplicitCopyOrMove() const {
2947 switch (IIK) {
2948 case IIK_Copy:
2949 case IIK_Move:
2950 return true;
2951
2952 case IIK_Default:
2953 return false;
2954 }
David Blaikie30263482012-01-20 21:50:17 +00002955
2956 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002957 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002958
2959 bool addFieldInitializer(CXXCtorInitializer *Init) {
2960 AllToInit.push_back(Init);
2961
2962 // Check whether this initializer makes the field "used".
2963 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2964 S.UnusedPrivateFields.remove(Init->getAnyMember());
2965
2966 return false;
2967 }
John McCallf1860e52010-05-20 23:23:51 +00002968};
2969}
2970
Richard Smitha4950662011-09-19 13:34:43 +00002971/// \brief Determine whether the given indirect field declaration is somewhere
2972/// within an anonymous union.
2973static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2974 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2975 CEnd = F->chain_end();
2976 C != CEnd; ++C)
2977 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2978 if (Record->isUnion())
2979 return true;
2980
2981 return false;
2982}
2983
Douglas Gregorddb21472011-11-02 23:04:16 +00002984/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2985/// array type.
2986static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2987 if (T->isIncompleteArrayType())
2988 return true;
2989
2990 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2991 if (!ArrayT->getSize())
2992 return true;
2993
2994 T = ArrayT->getElementType();
2995 }
2996
2997 return false;
2998}
2999
Richard Smith7a614d82011-06-11 17:19:42 +00003000static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003001 FieldDecl *Field,
3002 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003003
Chandler Carruthe861c602010-06-30 02:59:29 +00003004 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003005 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3006 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003007
Richard Smith0b8220a2012-08-07 21:30:42 +00003008 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003009 // has a brace-or-equal-initializer, the entity is initialized as specified
3010 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003011 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003012 CXXCtorInitializer *Init;
3013 if (Indirect)
3014 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3015 SourceLocation(),
3016 SourceLocation(), 0,
3017 SourceLocation());
3018 else
3019 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3020 SourceLocation(),
3021 SourceLocation(), 0,
3022 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003023 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003024 }
3025
Richard Smithc115f632011-09-18 11:14:50 +00003026 // Don't build an implicit initializer for union members if none was
3027 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003028 if (Field->getParent()->isUnion() ||
3029 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003030 return false;
3031
Douglas Gregorddb21472011-11-02 23:04:16 +00003032 // Don't initialize incomplete or zero-length arrays.
3033 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3034 return false;
3035
John McCallf1860e52010-05-20 23:23:51 +00003036 // Don't try to build an implicit initializer if there were semantic
3037 // errors in any of the initializers (and therefore we might be
3038 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003039 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003040 return false;
3041
Sean Huntcbb67482011-01-08 20:30:50 +00003042 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003043 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3044 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003045 return true;
John McCallf1860e52010-05-20 23:23:51 +00003046
Richard Smith0b8220a2012-08-07 21:30:42 +00003047 if (!Init)
3048 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003049
Richard Smith0b8220a2012-08-07 21:30:42 +00003050 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003051}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003052
3053bool
3054Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3055 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003056 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003057 Constructor->setNumCtorInitializers(1);
3058 CXXCtorInitializer **initializer =
3059 new (Context) CXXCtorInitializer*[1];
3060 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3061 Constructor->setCtorInitializers(initializer);
3062
Sean Huntb76af9c2011-05-03 23:05:34 +00003063 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003064 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003065 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3066 }
3067
Sean Huntc1598702011-05-05 00:05:47 +00003068 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003069
Sean Hunt059ce0d2011-05-01 07:04:31 +00003070 return false;
3071}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003072
John McCallb77115d2011-06-17 00:18:42 +00003073bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
3074 CXXCtorInitializer **Initializers,
3075 unsigned NumInitializers,
3076 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003077 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003078 // Just store the initializers as written, they will be checked during
3079 // instantiation.
3080 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003081 Constructor->setNumCtorInitializers(NumInitializers);
3082 CXXCtorInitializer **baseOrMemberInitializers =
3083 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003084 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00003085 NumInitializers * sizeof(CXXCtorInitializer*));
3086 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003087 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003088
3089 // Let template instantiation know whether we had errors.
3090 if (AnyErrors)
3091 Constructor->setInvalidDecl();
3092
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003093 return false;
3094 }
3095
John McCallf1860e52010-05-20 23:23:51 +00003096 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003097
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003098 // We need to build the initializer AST according to order of construction
3099 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003100 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003101 if (!ClassDecl)
3102 return true;
3103
Eli Friedman80c30da2009-11-09 19:20:36 +00003104 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003106 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003107 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003108
3109 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003110 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003111 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003112 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003113 }
3114
Anders Carlsson711f34a2010-04-21 19:52:01 +00003115 // Keep track of the direct virtual bases.
3116 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3117 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3118 E = ClassDecl->bases_end(); I != E; ++I) {
3119 if (I->isVirtual())
3120 DirectVBases.insert(I);
3121 }
3122
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003123 // Push virtual bases before others.
3124 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3125 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3126
Sean Huntcbb67482011-01-08 20:30:50 +00003127 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003128 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3129 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003130 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003131 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003132 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003133 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003134 VBase, IsInheritedVirtualBase,
3135 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003136 HadError = true;
3137 continue;
3138 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003139
John McCallf1860e52010-05-20 23:23:51 +00003140 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003141 }
3142 }
Mike Stump1eb44332009-09-09 15:08:12 +00003143
John McCallf1860e52010-05-20 23:23:51 +00003144 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003145 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3146 E = ClassDecl->bases_end(); Base != E; ++Base) {
3147 // Virtuals are in the virtual base list and already constructed.
3148 if (Base->isVirtual())
3149 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003150
Sean Huntcbb67482011-01-08 20:30:50 +00003151 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003152 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3153 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003154 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003155 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003156 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003157 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003158 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003159 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003160 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003161 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003162
John McCallf1860e52010-05-20 23:23:51 +00003163 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003164 }
3165 }
Mike Stump1eb44332009-09-09 15:08:12 +00003166
John McCallf1860e52010-05-20 23:23:51 +00003167 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003168 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3169 MemEnd = ClassDecl->decls_end();
3170 Mem != MemEnd; ++Mem) {
3171 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003172 // C++ [class.bit]p2:
3173 // A declaration for a bit-field that omits the identifier declares an
3174 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3175 // initialized.
3176 if (F->isUnnamedBitfield())
3177 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003178
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003179 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003180 // handle anonymous struct/union fields based on their individual
3181 // indirect fields.
3182 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3183 continue;
3184
3185 if (CollectFieldInitializer(*this, Info, F))
3186 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003187 continue;
3188 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003189
3190 // Beyond this point, we only consider default initialization.
3191 if (Info.IIK != IIK_Default)
3192 continue;
3193
3194 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3195 if (F->getType()->isIncompleteArrayType()) {
3196 assert(ClassDecl->hasFlexibleArrayMember() &&
3197 "Incomplete array type is not valid");
3198 continue;
3199 }
3200
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003201 // Initialize each field of an anonymous struct individually.
3202 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3203 HadError = true;
3204
3205 continue;
3206 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003207 }
Mike Stump1eb44332009-09-09 15:08:12 +00003208
John McCallf1860e52010-05-20 23:23:51 +00003209 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003210 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003211 Constructor->setNumCtorInitializers(NumInitializers);
3212 CXXCtorInitializer **baseOrMemberInitializers =
3213 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003214 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003215 NumInitializers * sizeof(CXXCtorInitializer*));
3216 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003217
John McCallef027fe2010-03-16 21:39:52 +00003218 // Constructors implicitly reference the base and member
3219 // destructors.
3220 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3221 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003222 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003223
3224 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003225}
3226
Eli Friedman6347f422009-07-21 19:28:10 +00003227static void *GetKeyForTopLevelField(FieldDecl *Field) {
3228 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003229 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003230 if (RT->getDecl()->isAnonymousStructOrUnion())
3231 return static_cast<void *>(RT->getDecl());
3232 }
3233 return static_cast<void *>(Field);
3234}
3235
Anders Carlssonea356fb2010-04-02 05:42:15 +00003236static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003237 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003238}
3239
Anders Carlssonea356fb2010-04-02 05:42:15 +00003240static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003241 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003242 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003243 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003244
Eli Friedman6347f422009-07-21 19:28:10 +00003245 // For fields injected into the class via declaration of an anonymous union,
3246 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003247 FieldDecl *Field = Member->getAnyMember();
3248
John McCall3c3ccdb2010-04-10 09:28:51 +00003249 // If the field is a member of an anonymous struct or union, our key
3250 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003251 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003252 if (RD->isAnonymousStructOrUnion()) {
3253 while (true) {
3254 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3255 if (Parent->isAnonymousStructOrUnion())
3256 RD = Parent;
3257 else
3258 break;
3259 }
3260
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003261 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003262 }
Mike Stump1eb44332009-09-09 15:08:12 +00003263
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003264 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003265}
3266
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003267static void
3268DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003269 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003270 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003271 unsigned NumInits) {
3272 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003273 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003274
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003275 // Don't check initializers order unless the warning is enabled at the
3276 // location of at least one initializer.
3277 bool ShouldCheckOrder = false;
3278 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003279 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003280 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3281 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003282 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003283 ShouldCheckOrder = true;
3284 break;
3285 }
3286 }
3287 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003288 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003289
John McCalld6ca8da2010-04-10 07:37:23 +00003290 // Build the list of bases and members in the order that they'll
3291 // actually be initialized. The explicit initializers should be in
3292 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003293 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003294
Anders Carlsson071d6102010-04-02 03:38:04 +00003295 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3296
John McCalld6ca8da2010-04-10 07:37:23 +00003297 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003298 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003299 ClassDecl->vbases_begin(),
3300 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003301 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003302
John McCalld6ca8da2010-04-10 07:37:23 +00003303 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003304 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003305 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003306 if (Base->isVirtual())
3307 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003308 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003309 }
Mike Stump1eb44332009-09-09 15:08:12 +00003310
John McCalld6ca8da2010-04-10 07:37:23 +00003311 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003312 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003313 E = ClassDecl->field_end(); Field != E; ++Field) {
3314 if (Field->isUnnamedBitfield())
3315 continue;
3316
David Blaikie581deb32012-06-06 20:45:41 +00003317 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003318 }
3319
John McCalld6ca8da2010-04-10 07:37:23 +00003320 unsigned NumIdealInits = IdealInitKeys.size();
3321 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003322
Sean Huntcbb67482011-01-08 20:30:50 +00003323 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003324 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003325 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003326 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003327
3328 // Scan forward to try to find this initializer in the idealized
3329 // initializers list.
3330 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3331 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003332 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003333
3334 // If we didn't find this initializer, it must be because we
3335 // scanned past it on a previous iteration. That can only
3336 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003337 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003338 Sema::SemaDiagnosticBuilder D =
3339 SemaRef.Diag(PrevInit->getSourceLocation(),
3340 diag::warn_initializer_out_of_order);
3341
Francois Pichet00eb3f92010-12-04 09:14:42 +00003342 if (PrevInit->isAnyMemberInitializer())
3343 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003344 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003345 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003346
Francois Pichet00eb3f92010-12-04 09:14:42 +00003347 if (Init->isAnyMemberInitializer())
3348 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003349 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003350 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003351
3352 // Move back to the initializer's location in the ideal list.
3353 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3354 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003355 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003356
3357 assert(IdealIndex != NumIdealInits &&
3358 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003359 }
John McCalld6ca8da2010-04-10 07:37:23 +00003360
3361 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003362 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003363}
3364
John McCall3c3ccdb2010-04-10 09:28:51 +00003365namespace {
3366bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003367 CXXCtorInitializer *Init,
3368 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003369 if (!PrevInit) {
3370 PrevInit = Init;
3371 return false;
3372 }
3373
3374 if (FieldDecl *Field = Init->getMember())
3375 S.Diag(Init->getSourceLocation(),
3376 diag::err_multiple_mem_initialization)
3377 << Field->getDeclName()
3378 << Init->getSourceRange();
3379 else {
John McCallf4c73712011-01-19 06:33:43 +00003380 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003381 assert(BaseClass && "neither field nor base");
3382 S.Diag(Init->getSourceLocation(),
3383 diag::err_multiple_base_initialization)
3384 << QualType(BaseClass, 0)
3385 << Init->getSourceRange();
3386 }
3387 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3388 << 0 << PrevInit->getSourceRange();
3389
3390 return true;
3391}
3392
Sean Huntcbb67482011-01-08 20:30:50 +00003393typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003394typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3395
3396bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003397 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003398 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003399 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003400 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003401 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003402
3403 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003404 if (Parent->isUnion()) {
3405 UnionEntry &En = Unions[Parent];
3406 if (En.first && En.first != Child) {
3407 S.Diag(Init->getSourceLocation(),
3408 diag::err_multiple_mem_union_initialization)
3409 << Field->getDeclName()
3410 << Init->getSourceRange();
3411 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3412 << 0 << En.second->getSourceRange();
3413 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003414 }
3415 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003416 En.first = Child;
3417 En.second = Init;
3418 }
David Blaikie6fe29652011-11-17 06:01:57 +00003419 if (!Parent->isAnonymousStructOrUnion())
3420 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003421 }
3422
3423 Child = Parent;
3424 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003425 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003426
3427 return false;
3428}
3429}
3430
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003431/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003432void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003433 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003434 CXXCtorInitializer **meminits,
3435 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003436 bool AnyErrors) {
3437 if (!ConstructorDecl)
3438 return;
3439
3440 AdjustDeclIfTemplate(ConstructorDecl);
3441
3442 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003443 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003444
3445 if (!Constructor) {
3446 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3447 return;
3448 }
3449
Sean Huntcbb67482011-01-08 20:30:50 +00003450 CXXCtorInitializer **MemInits =
3451 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003452
3453 // Mapping for the duplicate initializers check.
3454 // For member initializers, this is keyed with a FieldDecl*.
3455 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003456 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003457
3458 // Mapping for the inconsistent anonymous-union initializers check.
3459 RedundantUnionMap MemberUnions;
3460
Anders Carlssonea356fb2010-04-02 05:42:15 +00003461 bool HadError = false;
3462 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003463 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003464
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003465 // Set the source order index.
3466 Init->setSourceOrder(i);
3467
Francois Pichet00eb3f92010-12-04 09:14:42 +00003468 if (Init->isAnyMemberInitializer()) {
3469 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003470 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3471 CheckRedundantUnionInit(*this, Init, MemberUnions))
3472 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003473 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003474 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3475 if (CheckRedundantInit(*this, Init, Members[Key]))
3476 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003477 } else {
3478 assert(Init->isDelegatingInitializer());
3479 // This must be the only initializer
Richard Smitha6ddea62012-09-14 18:21:10 +00003480 if (NumMemInits != 1) {
3481 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003482 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003483 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003484 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003485 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003486 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003487 // Return immediately as the initializer is set.
3488 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003489 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003490 }
3491
Anders Carlssonea356fb2010-04-02 05:42:15 +00003492 if (HadError)
3493 return;
3494
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003495 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003496
Sean Huntcbb67482011-01-08 20:30:50 +00003497 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003498}
3499
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003500void
John McCallef027fe2010-03-16 21:39:52 +00003501Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3502 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003503 // Ignore dependent contexts. Also ignore unions, since their members never
3504 // have destructors implicitly called.
3505 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003506 return;
John McCall58e6f342010-03-16 05:22:47 +00003507
3508 // FIXME: all the access-control diagnostics are positioned on the
3509 // field/base declaration. That's probably good; that said, the
3510 // user might reasonably want to know why the destructor is being
3511 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003512
Anders Carlsson9f853df2009-11-17 04:44:12 +00003513 // Non-static data members.
3514 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3515 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003516 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003517 if (Field->isInvalidDecl())
3518 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003519
3520 // Don't destroy incomplete or zero-length arrays.
3521 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3522 continue;
3523
Anders Carlsson9f853df2009-11-17 04:44:12 +00003524 QualType FieldType = Context.getBaseElementType(Field->getType());
3525
3526 const RecordType* RT = FieldType->getAs<RecordType>();
3527 if (!RT)
3528 continue;
3529
3530 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003531 if (FieldClassDecl->isInvalidDecl())
3532 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003533 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003534 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003535 // The destructor for an implicit anonymous union member is never invoked.
3536 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3537 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003538
Douglas Gregordb89f282010-07-01 22:47:18 +00003539 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003540 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003541 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003542 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003543 << Field->getDeclName()
3544 << FieldType);
3545
Eli Friedman5f2987c2012-02-02 03:46:19 +00003546 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003547 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003548 }
3549
John McCall58e6f342010-03-16 05:22:47 +00003550 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3551
Anders Carlsson9f853df2009-11-17 04:44:12 +00003552 // Bases.
3553 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3554 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003555 // Bases are always records in a well-formed non-dependent class.
3556 const RecordType *RT = Base->getType()->getAs<RecordType>();
3557
3558 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003559 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003560 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003561
John McCall58e6f342010-03-16 05:22:47 +00003562 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003563 // If our base class is invalid, we probably can't get its dtor anyway.
3564 if (BaseClassDecl->isInvalidDecl())
3565 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003566 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003567 continue;
John McCall58e6f342010-03-16 05:22:47 +00003568
Douglas Gregordb89f282010-07-01 22:47:18 +00003569 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003570 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003571
3572 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003573 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003574 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003575 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003576 << Base->getSourceRange(),
3577 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003578
Eli Friedman5f2987c2012-02-02 03:46:19 +00003579 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003580 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003581 }
3582
3583 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003584 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3585 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003586
3587 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003588 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003589
3590 // Ignore direct virtual bases.
3591 if (DirectVirtualBases.count(RT))
3592 continue;
3593
John McCall58e6f342010-03-16 05:22:47 +00003594 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003595 // If our base class is invalid, we probably can't get its dtor anyway.
3596 if (BaseClassDecl->isInvalidDecl())
3597 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003598 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003599 continue;
John McCall58e6f342010-03-16 05:22:47 +00003600
Douglas Gregordb89f282010-07-01 22:47:18 +00003601 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003602 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003603 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003604 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003605 << VBase->getType(),
3606 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003607
Eli Friedman5f2987c2012-02-02 03:46:19 +00003608 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003609 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003610 }
3611}
3612
John McCalld226f652010-08-21 09:40:31 +00003613void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003614 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003615 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003616
Mike Stump1eb44332009-09-09 15:08:12 +00003617 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003618 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003619 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003620}
3621
Mike Stump1eb44332009-09-09 15:08:12 +00003622bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003623 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003624 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3625 unsigned DiagID;
3626 AbstractDiagSelID SelID;
3627
3628 public:
3629 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3630 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3631
3632 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003633 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003634 if (SelID == -1)
3635 S.Diag(Loc, DiagID) << T;
3636 else
3637 S.Diag(Loc, DiagID) << SelID << T;
3638 }
3639 } Diagnoser(DiagID, SelID);
3640
3641 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003642}
3643
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003644bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003645 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003646 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003647 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003648
Anders Carlsson11f21a02009-03-23 19:10:31 +00003649 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003650 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003651
Ted Kremenek6217b802009-07-29 21:53:49 +00003652 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003653 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003654 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003655 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003656
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003657 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003658 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003659 }
Mike Stump1eb44332009-09-09 15:08:12 +00003660
Ted Kremenek6217b802009-07-29 21:53:49 +00003661 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003662 if (!RT)
3663 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003664
John McCall86ff3082010-02-04 22:26:26 +00003665 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003666
John McCall94c3b562010-08-18 09:41:07 +00003667 // We can't answer whether something is abstract until it has a
3668 // definition. If it's currently being defined, we'll walk back
3669 // over all the declarations when we have a full definition.
3670 const CXXRecordDecl *Def = RD->getDefinition();
3671 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003672 return false;
3673
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003674 if (!RD->isAbstract())
3675 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003676
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003677 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003678 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003679
John McCall94c3b562010-08-18 09:41:07 +00003680 return true;
3681}
3682
3683void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3684 // Check if we've already emitted the list of pure virtual functions
3685 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003686 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003687 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003689 CXXFinalOverriderMap FinalOverriders;
3690 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003692 // Keep a set of seen pure methods so we won't diagnose the same method
3693 // more than once.
3694 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3695
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003696 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3697 MEnd = FinalOverriders.end();
3698 M != MEnd;
3699 ++M) {
3700 for (OverridingMethods::iterator SO = M->second.begin(),
3701 SOEnd = M->second.end();
3702 SO != SOEnd; ++SO) {
3703 // C++ [class.abstract]p4:
3704 // A class is abstract if it contains or inherits at least one
3705 // pure virtual function for which the final overrider is pure
3706 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003707
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003708 //
3709 if (SO->second.size() != 1)
3710 continue;
3711
3712 if (!SO->second.front().Method->isPure())
3713 continue;
3714
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003715 if (!SeenPureMethods.insert(SO->second.front().Method))
3716 continue;
3717
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003718 Diag(SO->second.front().Method->getLocation(),
3719 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003720 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003721 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003722 }
3723
3724 if (!PureVirtualClassDiagSet)
3725 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3726 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003727}
3728
Anders Carlsson8211eff2009-03-24 01:19:16 +00003729namespace {
John McCall94c3b562010-08-18 09:41:07 +00003730struct AbstractUsageInfo {
3731 Sema &S;
3732 CXXRecordDecl *Record;
3733 CanQualType AbstractType;
3734 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003735
John McCall94c3b562010-08-18 09:41:07 +00003736 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3737 : S(S), Record(Record),
3738 AbstractType(S.Context.getCanonicalType(
3739 S.Context.getTypeDeclType(Record))),
3740 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003741
John McCall94c3b562010-08-18 09:41:07 +00003742 void DiagnoseAbstractType() {
3743 if (Invalid) return;
3744 S.DiagnoseAbstractType(Record);
3745 Invalid = true;
3746 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003747
John McCall94c3b562010-08-18 09:41:07 +00003748 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3749};
3750
3751struct CheckAbstractUsage {
3752 AbstractUsageInfo &Info;
3753 const NamedDecl *Ctx;
3754
3755 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3756 : Info(Info), Ctx(Ctx) {}
3757
3758 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3759 switch (TL.getTypeLocClass()) {
3760#define ABSTRACT_TYPELOC(CLASS, PARENT)
3761#define TYPELOC(CLASS, PARENT) \
3762 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3763#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003764 }
John McCall94c3b562010-08-18 09:41:07 +00003765 }
Mike Stump1eb44332009-09-09 15:08:12 +00003766
John McCall94c3b562010-08-18 09:41:07 +00003767 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3768 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3769 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003770 if (!TL.getArg(I))
3771 continue;
3772
John McCall94c3b562010-08-18 09:41:07 +00003773 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3774 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003775 }
John McCall94c3b562010-08-18 09:41:07 +00003776 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003777
John McCall94c3b562010-08-18 09:41:07 +00003778 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3779 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3780 }
Mike Stump1eb44332009-09-09 15:08:12 +00003781
John McCall94c3b562010-08-18 09:41:07 +00003782 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3783 // Visit the type parameters from a permissive context.
3784 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3785 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3786 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3787 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3788 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3789 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003790 }
John McCall94c3b562010-08-18 09:41:07 +00003791 }
Mike Stump1eb44332009-09-09 15:08:12 +00003792
John McCall94c3b562010-08-18 09:41:07 +00003793 // Visit pointee types from a permissive context.
3794#define CheckPolymorphic(Type) \
3795 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3796 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3797 }
3798 CheckPolymorphic(PointerTypeLoc)
3799 CheckPolymorphic(ReferenceTypeLoc)
3800 CheckPolymorphic(MemberPointerTypeLoc)
3801 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003802 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003803
John McCall94c3b562010-08-18 09:41:07 +00003804 /// Handle all the types we haven't given a more specific
3805 /// implementation for above.
3806 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3807 // Every other kind of type that we haven't called out already
3808 // that has an inner type is either (1) sugar or (2) contains that
3809 // inner type in some way as a subobject.
3810 if (TypeLoc Next = TL.getNextTypeLoc())
3811 return Visit(Next, Sel);
3812
3813 // If there's no inner type and we're in a permissive context,
3814 // don't diagnose.
3815 if (Sel == Sema::AbstractNone) return;
3816
3817 // Check whether the type matches the abstract type.
3818 QualType T = TL.getType();
3819 if (T->isArrayType()) {
3820 Sel = Sema::AbstractArrayType;
3821 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003822 }
John McCall94c3b562010-08-18 09:41:07 +00003823 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3824 if (CT != Info.AbstractType) return;
3825
3826 // It matched; do some magic.
3827 if (Sel == Sema::AbstractArrayType) {
3828 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3829 << T << TL.getSourceRange();
3830 } else {
3831 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3832 << Sel << T << TL.getSourceRange();
3833 }
3834 Info.DiagnoseAbstractType();
3835 }
3836};
3837
3838void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3839 Sema::AbstractDiagSelID Sel) {
3840 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3841}
3842
3843}
3844
3845/// Check for invalid uses of an abstract type in a method declaration.
3846static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3847 CXXMethodDecl *MD) {
3848 // No need to do the check on definitions, which require that
3849 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003850 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003851 return;
3852
3853 // For safety's sake, just ignore it if we don't have type source
3854 // information. This should never happen for non-implicit methods,
3855 // but...
3856 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3857 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3858}
3859
3860/// Check for invalid uses of an abstract type within a class definition.
3861static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3862 CXXRecordDecl *RD) {
3863 for (CXXRecordDecl::decl_iterator
3864 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3865 Decl *D = *I;
3866 if (D->isImplicit()) continue;
3867
3868 // Methods and method templates.
3869 if (isa<CXXMethodDecl>(D)) {
3870 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3871 } else if (isa<FunctionTemplateDecl>(D)) {
3872 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3873 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3874
3875 // Fields and static variables.
3876 } else if (isa<FieldDecl>(D)) {
3877 FieldDecl *FD = cast<FieldDecl>(D);
3878 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3879 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3880 } else if (isa<VarDecl>(D)) {
3881 VarDecl *VD = cast<VarDecl>(D);
3882 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3883 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3884
3885 // Nested classes and class templates.
3886 } else if (isa<CXXRecordDecl>(D)) {
3887 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3888 } else if (isa<ClassTemplateDecl>(D)) {
3889 CheckAbstractClassUsage(Info,
3890 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3891 }
3892 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003893}
3894
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003895/// \brief Perform semantic checks on a class definition that has been
3896/// completing, introducing implicitly-declared members, checking for
3897/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003898void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003899 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003900 return;
3901
John McCall94c3b562010-08-18 09:41:07 +00003902 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3903 AbstractUsageInfo Info(*this, Record);
3904 CheckAbstractClassUsage(Info, Record);
3905 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003906
3907 // If this is not an aggregate type and has no user-declared constructor,
3908 // complain about any non-static data members of reference or const scalar
3909 // type, since they will never get initializers.
3910 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003911 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3912 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003913 bool Complained = false;
3914 for (RecordDecl::field_iterator F = Record->field_begin(),
3915 FEnd = Record->field_end();
3916 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003917 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003918 continue;
3919
Douglas Gregor325e5932010-04-15 00:00:53 +00003920 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003921 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003922 if (!Complained) {
3923 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3924 << Record->getTagKind() << Record;
3925 Complained = true;
3926 }
3927
3928 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3929 << F->getType()->isReferenceType()
3930 << F->getDeclName();
3931 }
3932 }
3933 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003934
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003935 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003936 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003937
3938 if (Record->getIdentifier()) {
3939 // C++ [class.mem]p13:
3940 // If T is the name of a class, then each of the following shall have a
3941 // name different from T:
3942 // - every member of every anonymous union that is a member of class T.
3943 //
3944 // C++ [class.mem]p14:
3945 // In addition, if class T has a user-declared constructor (12.1), every
3946 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00003947 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3948 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3949 ++I) {
3950 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00003951 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3952 isa<IndirectFieldDecl>(D)) {
3953 Diag(D->getLocation(), diag::err_member_name_of_class)
3954 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003955 break;
3956 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003957 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003958 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003959
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003960 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003961 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003962 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003963 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003964 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3965 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3966 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003967
David Blaikieb6b5b972012-09-21 03:21:07 +00003968 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3969 Diag(Record->getLocation(), diag::warn_abstract_final_class);
3970 DiagnoseAbstractType(Record);
3971 }
3972
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003973 if (!Record->isDependentType()) {
3974 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3975 MEnd = Record->method_end();
3976 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00003977 // See if a method overloads virtual methods in a base
3978 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00003979 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003980 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00003981
3982 // Check whether the explicitly-defaulted special members are valid.
3983 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
3984 CheckExplicitlyDefaultedSpecialMember(*M);
3985
3986 // For an explicitly defaulted or deleted special member, we defer
3987 // determining triviality until the class is complete. That time is now!
3988 if (!M->isImplicit() && !M->isUserProvided()) {
3989 CXXSpecialMember CSM = getSpecialMember(*M);
3990 if (CSM != CXXInvalid) {
3991 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
3992
3993 // Inform the class that we've finished declaring this member.
3994 Record->finishedDefaultedOrDeletedMember(*M);
3995 }
3996 }
3997 }
3998 }
3999
4000 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4001 // function that is not a constructor declares that member function to be
4002 // const. [...] The class of which that function is a member shall be
4003 // a literal type.
4004 //
4005 // If the class has virtual bases, any constexpr members will already have
4006 // been diagnosed by the checks performed on the member declaration, so
4007 // suppress this (less useful) diagnostic.
4008 //
4009 // We delay this until we know whether an explicitly-defaulted (or deleted)
4010 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004011 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004012 !Record->isLiteral() && !Record->getNumVBases()) {
4013 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4014 MEnd = Record->method_end();
4015 M != MEnd; ++M) {
4016 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4017 switch (Record->getTemplateSpecializationKind()) {
4018 case TSK_ImplicitInstantiation:
4019 case TSK_ExplicitInstantiationDeclaration:
4020 case TSK_ExplicitInstantiationDefinition:
4021 // If a template instantiates to a non-literal type, but its members
4022 // instantiate to constexpr functions, the template is technically
4023 // ill-formed, but we allow it for sanity.
4024 continue;
4025
4026 case TSK_Undeclared:
4027 case TSK_ExplicitSpecialization:
4028 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4029 diag::err_constexpr_method_non_literal);
4030 break;
4031 }
4032
4033 // Only produce one error per class.
4034 break;
4035 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004036 }
4037 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004038
4039 // Declare inherited constructors. We do this eagerly here because:
4040 // - The standard requires an eager diagnostic for conflicting inherited
4041 // constructors from different classes.
4042 // - The lazy declaration of the other implicit constructors is so as to not
4043 // waste space and performance on classes that are not meant to be
4044 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4045 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004046 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004047}
4048
Richard Smith7756afa2012-06-10 05:43:50 +00004049/// Is the special member function which would be selected to perform the
4050/// specified operation on the specified class type a constexpr constructor?
4051static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4052 Sema::CXXSpecialMember CSM,
4053 bool ConstArg) {
4054 Sema::SpecialMemberOverloadResult *SMOR =
4055 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4056 false, false, false, false);
4057 if (!SMOR || !SMOR->getMethod())
4058 // A constructor we wouldn't select can't be "involved in initializing"
4059 // anything.
4060 return true;
4061 return SMOR->getMethod()->isConstexpr();
4062}
4063
4064/// Determine whether the specified special member function would be constexpr
4065/// if it were implicitly defined.
4066static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4067 Sema::CXXSpecialMember CSM,
4068 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004069 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004070 return false;
4071
4072 // C++11 [dcl.constexpr]p4:
4073 // In the definition of a constexpr constructor [...]
4074 switch (CSM) {
4075 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004076 // Since default constructor lookup is essentially trivial (and cannot
4077 // involve, for instance, template instantiation), we compute whether a
4078 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4079 //
4080 // This is important for performance; we need to know whether the default
4081 // constructor is constexpr to determine whether the type is a literal type.
4082 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4083
Richard Smith7756afa2012-06-10 05:43:50 +00004084 case Sema::CXXCopyConstructor:
4085 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004086 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004087 break;
4088
4089 case Sema::CXXCopyAssignment:
4090 case Sema::CXXMoveAssignment:
4091 case Sema::CXXDestructor:
4092 case Sema::CXXInvalid:
4093 return false;
4094 }
4095
4096 // -- if the class is a non-empty union, or for each non-empty anonymous
4097 // union member of a non-union class, exactly one non-static data member
4098 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004099 //
4100 // If we squint, this is guaranteed, since exactly one non-static data member
4101 // will be initialized (if the constructor isn't deleted), we just don't know
4102 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004103 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004104 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004105
4106 // -- the class shall not have any virtual base classes;
4107 if (ClassDecl->getNumVBases())
4108 return false;
4109
4110 // -- every constructor involved in initializing [...] base class
4111 // sub-objects shall be a constexpr constructor;
4112 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4113 BEnd = ClassDecl->bases_end();
4114 B != BEnd; ++B) {
4115 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4116 if (!BaseType) continue;
4117
4118 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4119 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4120 return false;
4121 }
4122
4123 // -- every constructor involved in initializing non-static data members
4124 // [...] shall be a constexpr constructor;
4125 // -- every non-static data member and base class sub-object shall be
4126 // initialized
4127 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4128 FEnd = ClassDecl->field_end();
4129 F != FEnd; ++F) {
4130 if (F->isInvalidDecl())
4131 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004132 if (const RecordType *RecordTy =
4133 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004134 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4135 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4136 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004137 }
4138 }
4139
4140 // All OK, it's constexpr!
4141 return true;
4142}
4143
Richard Smithb9d0b762012-07-27 04:22:15 +00004144static Sema::ImplicitExceptionSpecification
4145computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4146 switch (S.getSpecialMember(MD)) {
4147 case Sema::CXXDefaultConstructor:
4148 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4149 case Sema::CXXCopyConstructor:
4150 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4151 case Sema::CXXCopyAssignment:
4152 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4153 case Sema::CXXMoveConstructor:
4154 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4155 case Sema::CXXMoveAssignment:
4156 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4157 case Sema::CXXDestructor:
4158 return S.ComputeDefaultedDtorExceptionSpec(MD);
4159 case Sema::CXXInvalid:
4160 break;
4161 }
4162 llvm_unreachable("only special members have implicit exception specs");
4163}
4164
Richard Smithdd25e802012-07-30 23:48:14 +00004165static void
4166updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4167 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4168 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4169 ExceptSpec.getEPI(EPI);
4170 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4171 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4172 FPT->getNumArgs(), EPI));
4173 FD->setType(QualType(NewFPT, 0));
4174}
4175
Richard Smithb9d0b762012-07-27 04:22:15 +00004176void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4177 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4178 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4179 return;
4180
Richard Smithdd25e802012-07-30 23:48:14 +00004181 // Evaluate the exception specification.
4182 ImplicitExceptionSpecification ExceptSpec =
4183 computeImplicitExceptionSpec(*this, Loc, MD);
4184
4185 // Update the type of the special member to use it.
4186 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4187
4188 // A user-provided destructor can be defined outside the class. When that
4189 // happens, be sure to update the exception specification on both
4190 // declarations.
4191 const FunctionProtoType *CanonicalFPT =
4192 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4193 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4194 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4195 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004196}
4197
Richard Smith3003e1d2012-05-15 04:39:51 +00004198void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4199 CXXRecordDecl *RD = MD->getParent();
4200 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004201
Richard Smith3003e1d2012-05-15 04:39:51 +00004202 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4203 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004204
4205 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004206 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004207 bool First = MD == MD->getCanonicalDecl();
4208
4209 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004210
4211 // C++11 [dcl.fct.def.default]p1:
4212 // A function that is explicitly defaulted shall
4213 // -- be a special member function (checked elsewhere),
4214 // -- have the same type (except for ref-qualifiers, and except that a
4215 // copy operation can take a non-const reference) as an implicit
4216 // declaration, and
4217 // -- not have default arguments.
4218 unsigned ExpectedParams = 1;
4219 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4220 ExpectedParams = 0;
4221 if (MD->getNumParams() != ExpectedParams) {
4222 // This also checks for default arguments: a copy or move constructor with a
4223 // default argument is classified as a default constructor, and assignment
4224 // operations and destructors can't have default arguments.
4225 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4226 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004227 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004228 } else if (MD->isVariadic()) {
4229 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4230 << CSM << MD->getSourceRange();
4231 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004232 }
4233
Richard Smith3003e1d2012-05-15 04:39:51 +00004234 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004235
Richard Smith7756afa2012-06-10 05:43:50 +00004236 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004237 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004238 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004239 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004240 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004241
Richard Smith3003e1d2012-05-15 04:39:51 +00004242 QualType ReturnType = Context.VoidTy;
4243 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4244 // Check for return type matching.
4245 ReturnType = Type->getResultType();
4246 QualType ExpectedReturnType =
4247 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4248 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4249 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4250 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4251 HadError = true;
4252 }
4253
4254 // A defaulted special member cannot have cv-qualifiers.
4255 if (Type->getTypeQuals()) {
4256 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4257 << (CSM == CXXMoveAssignment);
4258 HadError = true;
4259 }
4260 }
4261
4262 // Check for parameter type matching.
4263 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004264 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004265 if (ExpectedParams && ArgType->isReferenceType()) {
4266 // Argument must be reference to possibly-const T.
4267 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004268 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004269
4270 if (ReferentType.isVolatileQualified()) {
4271 Diag(MD->getLocation(),
4272 diag::err_defaulted_special_member_volatile_param) << CSM;
4273 HadError = true;
4274 }
4275
Richard Smith7756afa2012-06-10 05:43:50 +00004276 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004277 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4278 Diag(MD->getLocation(),
4279 diag::err_defaulted_special_member_copy_const_param)
4280 << (CSM == CXXCopyAssignment);
4281 // FIXME: Explain why this special member can't be const.
4282 } else {
4283 Diag(MD->getLocation(),
4284 diag::err_defaulted_special_member_move_const_param)
4285 << (CSM == CXXMoveAssignment);
4286 }
4287 HadError = true;
4288 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004289 } else if (ExpectedParams) {
4290 // A copy assignment operator can take its argument by value, but a
4291 // defaulted one cannot.
4292 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004293 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004294 HadError = true;
4295 }
Sean Huntbe631222011-05-17 20:44:43 +00004296
Richard Smith61802452011-12-22 02:22:31 +00004297 // C++11 [dcl.fct.def.default]p2:
4298 // An explicitly-defaulted function may be declared constexpr only if it
4299 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004300 // Do not apply this rule to members of class templates, since core issue 1358
4301 // makes such functions always instantiate to constexpr functions. For
4302 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004303 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4304 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004305 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4306 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4307 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004308 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004309 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004310 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004311
Richard Smith61802452011-12-22 02:22:31 +00004312 // and may have an explicit exception-specification only if it is compatible
4313 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004314 if (Type->hasExceptionSpec()) {
4315 // Delay the check if this is the first declaration of the special member,
4316 // since we may not have parsed some necessary in-class initializers yet.
4317 if (First)
4318 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4319 else
4320 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4321 }
Richard Smith61802452011-12-22 02:22:31 +00004322
4323 // If a function is explicitly defaulted on its first declaration,
4324 if (First) {
4325 // -- it is implicitly considered to be constexpr if the implicit
4326 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004327 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004328
Richard Smith3003e1d2012-05-15 04:39:51 +00004329 // -- it is implicitly considered to have the same exception-specification
4330 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004331 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4332 EPI.ExceptionSpecType = EST_Unevaluated;
4333 EPI.ExceptionSpecDecl = MD;
4334 MD->setType(Context.getFunctionType(ReturnType, &ArgType,
4335 ExpectedParams, EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004336 }
4337
Richard Smith3003e1d2012-05-15 04:39:51 +00004338 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004339 if (First) {
4340 MD->setDeletedAsWritten();
4341 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004342 // C++11 [dcl.fct.def.default]p4:
4343 // [For a] user-provided explicitly-defaulted function [...] if such a
4344 // function is implicitly defined as deleted, the program is ill-formed.
4345 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4346 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004347 }
4348 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004349
Richard Smith3003e1d2012-05-15 04:39:51 +00004350 if (HadError)
4351 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004352}
4353
Richard Smith1d28caf2012-12-11 01:14:52 +00004354/// Check whether the exception specification provided for an
4355/// explicitly-defaulted special member matches the exception specification
4356/// that would have been generated for an implicit special member, per
4357/// C++11 [dcl.fct.def.default]p2.
4358void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4359 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4360 // Compute the implicit exception specification.
4361 FunctionProtoType::ExtProtoInfo EPI;
4362 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4363 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4364 Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4365
4366 // Ensure that it matches.
4367 CheckEquivalentExceptionSpec(
4368 PDiag(diag::err_incorrect_defaulted_exception_spec)
4369 << getSpecialMember(MD), PDiag(),
4370 ImplicitType, SourceLocation(),
4371 SpecifiedType, MD->getLocation());
4372}
4373
4374void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4375 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4376 I != N; ++I)
4377 CheckExplicitlyDefaultedMemberExceptionSpec(
4378 DelayedDefaultedMemberExceptionSpecs[I].first,
4379 DelayedDefaultedMemberExceptionSpecs[I].second);
4380
4381 DelayedDefaultedMemberExceptionSpecs.clear();
4382}
4383
Richard Smith7d5088a2012-02-18 02:02:13 +00004384namespace {
4385struct SpecialMemberDeletionInfo {
4386 Sema &S;
4387 CXXMethodDecl *MD;
4388 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004389 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004390
4391 // Properties of the special member, computed for convenience.
4392 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4393 SourceLocation Loc;
4394
4395 bool AllFieldsAreConst;
4396
4397 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004398 Sema::CXXSpecialMember CSM, bool Diagnose)
4399 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004400 IsConstructor(false), IsAssignment(false), IsMove(false),
4401 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4402 AllFieldsAreConst(true) {
4403 switch (CSM) {
4404 case Sema::CXXDefaultConstructor:
4405 case Sema::CXXCopyConstructor:
4406 IsConstructor = true;
4407 break;
4408 case Sema::CXXMoveConstructor:
4409 IsConstructor = true;
4410 IsMove = true;
4411 break;
4412 case Sema::CXXCopyAssignment:
4413 IsAssignment = true;
4414 break;
4415 case Sema::CXXMoveAssignment:
4416 IsAssignment = true;
4417 IsMove = true;
4418 break;
4419 case Sema::CXXDestructor:
4420 break;
4421 case Sema::CXXInvalid:
4422 llvm_unreachable("invalid special member kind");
4423 }
4424
4425 if (MD->getNumParams()) {
4426 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4427 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4428 }
4429 }
4430
4431 bool inUnion() const { return MD->getParent()->isUnion(); }
4432
4433 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004434 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4435 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004436 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004437 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4438 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4439 Quals = 0;
4440 return S.LookupSpecialMember(Class, CSM,
4441 ConstArg || (Quals & Qualifiers::Const),
4442 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004443 MD->getRefQualifier() == RQ_RValue,
4444 TQ & Qualifiers::Const,
4445 TQ & Qualifiers::Volatile);
4446 }
4447
Richard Smith6c4c36c2012-03-30 20:53:28 +00004448 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004449
Richard Smith6c4c36c2012-03-30 20:53:28 +00004450 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004451 bool shouldDeleteForField(FieldDecl *FD);
4452 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004453
Richard Smith517bb842012-07-18 03:51:16 +00004454 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4455 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004456 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4457 Sema::SpecialMemberOverloadResult *SMOR,
4458 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004459
4460 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004461};
4462}
4463
John McCall12d8d802012-04-09 20:53:23 +00004464/// Is the given special member inaccessible when used on the given
4465/// sub-object.
4466bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4467 CXXMethodDecl *target) {
4468 /// If we're operating on a base class, the object type is the
4469 /// type of this special member.
4470 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004471 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004472 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4473 objectTy = S.Context.getTypeDeclType(MD->getParent());
4474 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4475
4476 // If we're operating on a field, the object type is the type of the field.
4477 } else {
4478 objectTy = S.Context.getTypeDeclType(target->getParent());
4479 }
4480
4481 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4482}
4483
Richard Smith6c4c36c2012-03-30 20:53:28 +00004484/// Check whether we should delete a special member due to the implicit
4485/// definition containing a call to a special member of a subobject.
4486bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4487 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4488 bool IsDtorCallInCtor) {
4489 CXXMethodDecl *Decl = SMOR->getMethod();
4490 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4491
4492 int DiagKind = -1;
4493
4494 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4495 DiagKind = !Decl ? 0 : 1;
4496 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4497 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004498 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004499 DiagKind = 3;
4500 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4501 !Decl->isTrivial()) {
4502 // A member of a union must have a trivial corresponding special member.
4503 // As a weird special case, a destructor call from a union's constructor
4504 // must be accessible and non-deleted, but need not be trivial. Such a
4505 // destructor is never actually called, but is semantically checked as
4506 // if it were.
4507 DiagKind = 4;
4508 }
4509
4510 if (DiagKind == -1)
4511 return false;
4512
4513 if (Diagnose) {
4514 if (Field) {
4515 S.Diag(Field->getLocation(),
4516 diag::note_deleted_special_member_class_subobject)
4517 << CSM << MD->getParent() << /*IsField*/true
4518 << Field << DiagKind << IsDtorCallInCtor;
4519 } else {
4520 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4521 S.Diag(Base->getLocStart(),
4522 diag::note_deleted_special_member_class_subobject)
4523 << CSM << MD->getParent() << /*IsField*/false
4524 << Base->getType() << DiagKind << IsDtorCallInCtor;
4525 }
4526
4527 if (DiagKind == 1)
4528 S.NoteDeletedFunction(Decl);
4529 // FIXME: Explain inaccessibility if DiagKind == 3.
4530 }
4531
4532 return true;
4533}
4534
Richard Smith9a561d52012-02-26 09:11:52 +00004535/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004536/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004537bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004538 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004539 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004540
4541 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004542 // -- any direct or virtual base class, or non-static data member with no
4543 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004544 // either M has no default constructor or overload resolution as applied
4545 // to M's default constructor results in an ambiguity or in a function
4546 // that is deleted or inaccessible
4547 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4548 // -- a direct or virtual base class B that cannot be copied/moved because
4549 // overload resolution, as applied to B's corresponding special member,
4550 // results in an ambiguity or a function that is deleted or inaccessible
4551 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004552 // C++11 [class.dtor]p5:
4553 // -- any direct or virtual base class [...] has a type with a destructor
4554 // that is deleted or inaccessible
4555 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004556 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004557 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004558 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004559
Richard Smith6c4c36c2012-03-30 20:53:28 +00004560 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4561 // -- any direct or virtual base class or non-static data member has a
4562 // type with a destructor that is deleted or inaccessible
4563 if (IsConstructor) {
4564 Sema::SpecialMemberOverloadResult *SMOR =
4565 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4566 false, false, false, false, false);
4567 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4568 return true;
4569 }
4570
Richard Smith9a561d52012-02-26 09:11:52 +00004571 return false;
4572}
4573
4574/// Check whether we should delete a special member function due to the class
4575/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004576bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004577 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004578 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004579}
4580
4581/// Check whether we should delete a special member function due to the class
4582/// having a particular non-static data member.
4583bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4584 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4585 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4586
4587 if (CSM == Sema::CXXDefaultConstructor) {
4588 // For a default constructor, all references must be initialized in-class
4589 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004590 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4591 if (Diagnose)
4592 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4593 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004594 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004595 }
Richard Smith79363f52012-02-27 06:07:25 +00004596 // C++11 [class.ctor]p5: any non-variant non-static data member of
4597 // const-qualified type (or array thereof) with no
4598 // brace-or-equal-initializer does not have a user-provided default
4599 // constructor.
4600 if (!inUnion() && FieldType.isConstQualified() &&
4601 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004602 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4603 if (Diagnose)
4604 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004605 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004606 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004607 }
4608
4609 if (inUnion() && !FieldType.isConstQualified())
4610 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004611 } else if (CSM == Sema::CXXCopyConstructor) {
4612 // For a copy constructor, data members must not be of rvalue reference
4613 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004614 if (FieldType->isRValueReferenceType()) {
4615 if (Diagnose)
4616 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4617 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004618 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004619 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004620 } else if (IsAssignment) {
4621 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004622 if (FieldType->isReferenceType()) {
4623 if (Diagnose)
4624 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4625 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004626 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004627 }
4628 if (!FieldRecord && FieldType.isConstQualified()) {
4629 // C++11 [class.copy]p23:
4630 // -- a non-static data member of const non-class type (or array thereof)
4631 if (Diagnose)
4632 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004633 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004634 return true;
4635 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004636 }
4637
4638 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004639 // Some additional restrictions exist on the variant members.
4640 if (!inUnion() && FieldRecord->isUnion() &&
4641 FieldRecord->isAnonymousStructOrUnion()) {
4642 bool AllVariantFieldsAreConst = true;
4643
Richard Smithdf8dc862012-03-29 19:00:10 +00004644 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004645 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4646 UE = FieldRecord->field_end();
4647 UI != UE; ++UI) {
4648 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004649
4650 if (!UnionFieldType.isConstQualified())
4651 AllVariantFieldsAreConst = false;
4652
Richard Smith9a561d52012-02-26 09:11:52 +00004653 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4654 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004655 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4656 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004657 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004658 }
4659
4660 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004661 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004662 FieldRecord->field_begin() != FieldRecord->field_end()) {
4663 if (Diagnose)
4664 S.Diag(FieldRecord->getLocation(),
4665 diag::note_deleted_default_ctor_all_const)
4666 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004667 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004668 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004669
Richard Smithdf8dc862012-03-29 19:00:10 +00004670 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004671 // This is technically non-conformant, but sanity demands it.
4672 return false;
4673 }
4674
Richard Smith517bb842012-07-18 03:51:16 +00004675 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4676 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004677 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004678 }
4679
4680 return false;
4681}
4682
4683/// C++11 [class.ctor] p5:
4684/// A defaulted default constructor for a class X is defined as deleted if
4685/// X is a union and all of its variant members are of const-qualified type.
4686bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004687 // This is a silly definition, because it gives an empty union a deleted
4688 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004689 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4690 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4691 if (Diagnose)
4692 S.Diag(MD->getParent()->getLocation(),
4693 diag::note_deleted_default_ctor_all_const)
4694 << MD->getParent() << /*not anonymous union*/0;
4695 return true;
4696 }
4697 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004698}
4699
4700/// Determine whether a defaulted special member function should be defined as
4701/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4702/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004703bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4704 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004705 if (MD->isInvalidDecl())
4706 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004707 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004708 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004709 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004710 return false;
4711
Richard Smith7d5088a2012-02-18 02:02:13 +00004712 // C++11 [expr.lambda.prim]p19:
4713 // The closure type associated with a lambda-expression has a
4714 // deleted (8.4.3) default constructor and a deleted copy
4715 // assignment operator.
4716 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004717 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4718 if (Diagnose)
4719 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004720 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004721 }
4722
Richard Smith5bdaac52012-04-02 20:59:25 +00004723 // For an anonymous struct or union, the copy and assignment special members
4724 // will never be used, so skip the check. For an anonymous union declared at
4725 // namespace scope, the constructor and destructor are used.
4726 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4727 RD->isAnonymousStructOrUnion())
4728 return false;
4729
Richard Smith6c4c36c2012-03-30 20:53:28 +00004730 // C++11 [class.copy]p7, p18:
4731 // If the class definition declares a move constructor or move assignment
4732 // operator, an implicitly declared copy constructor or copy assignment
4733 // operator is defined as deleted.
4734 if (MD->isImplicit() &&
4735 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4736 CXXMethodDecl *UserDeclaredMove = 0;
4737
4738 // In Microsoft mode, a user-declared move only causes the deletion of the
4739 // corresponding copy operation, not both copy operations.
4740 if (RD->hasUserDeclaredMoveConstructor() &&
4741 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4742 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004743
4744 // Find any user-declared move constructor.
4745 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4746 E = RD->ctor_end(); I != E; ++I) {
4747 if (I->isMoveConstructor()) {
4748 UserDeclaredMove = *I;
4749 break;
4750 }
4751 }
Richard Smith1c931be2012-04-02 18:40:40 +00004752 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004753 } else if (RD->hasUserDeclaredMoveAssignment() &&
4754 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4755 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004756
4757 // Find any user-declared move assignment operator.
4758 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4759 E = RD->method_end(); I != E; ++I) {
4760 if (I->isMoveAssignmentOperator()) {
4761 UserDeclaredMove = *I;
4762 break;
4763 }
4764 }
Richard Smith1c931be2012-04-02 18:40:40 +00004765 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004766 }
4767
4768 if (UserDeclaredMove) {
4769 Diag(UserDeclaredMove->getLocation(),
4770 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004771 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004772 << UserDeclaredMove->isMoveAssignmentOperator();
4773 return true;
4774 }
4775 }
Sean Hunte16da072011-10-10 06:18:57 +00004776
Richard Smith5bdaac52012-04-02 20:59:25 +00004777 // Do access control from the special member function
4778 ContextRAII MethodContext(*this, MD);
4779
Richard Smith9a561d52012-02-26 09:11:52 +00004780 // C++11 [class.dtor]p5:
4781 // -- for a virtual destructor, lookup of the non-array deallocation function
4782 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004783 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004784 FunctionDecl *OperatorDelete = 0;
4785 DeclarationName Name =
4786 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4787 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004788 OperatorDelete, false)) {
4789 if (Diagnose)
4790 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004791 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004792 }
Richard Smith9a561d52012-02-26 09:11:52 +00004793 }
4794
Richard Smith6c4c36c2012-03-30 20:53:28 +00004795 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004796
Sean Huntcdee3fe2011-05-11 22:34:38 +00004797 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004798 BE = RD->bases_end(); BI != BE; ++BI)
4799 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004800 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004801 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004802
4803 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004804 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004805 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004806 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004807
4808 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004809 FE = RD->field_end(); FI != FE; ++FI)
4810 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004811 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004812 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004813
Richard Smith7d5088a2012-02-18 02:02:13 +00004814 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004815 return true;
4816
4817 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004818}
4819
Richard Smithac713512012-12-08 02:53:02 +00004820/// Perform lookup for a special member of the specified kind, and determine
4821/// whether it is trivial. If the triviality can be determined without the
4822/// lookup, skip it. This is intended for use when determining whether a
4823/// special member of a containing object is trivial, and thus does not ever
4824/// perform overload resolution for default constructors.
4825///
4826/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4827/// member that was most likely to be intended to be trivial, if any.
4828static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4829 Sema::CXXSpecialMember CSM, unsigned Quals,
4830 CXXMethodDecl **Selected) {
4831 if (Selected)
4832 *Selected = 0;
4833
4834 switch (CSM) {
4835 case Sema::CXXInvalid:
4836 llvm_unreachable("not a special member");
4837
4838 case Sema::CXXDefaultConstructor:
4839 // C++11 [class.ctor]p5:
4840 // A default constructor is trivial if:
4841 // - all the [direct subobjects] have trivial default constructors
4842 //
4843 // Note, no overload resolution is performed in this case.
4844 if (RD->hasTrivialDefaultConstructor())
4845 return true;
4846
4847 if (Selected) {
4848 // If there's a default constructor which could have been trivial, dig it
4849 // out. Otherwise, if there's any user-provided default constructor, point
4850 // to that as an example of why there's not a trivial one.
4851 CXXConstructorDecl *DefCtor = 0;
4852 if (RD->needsImplicitDefaultConstructor())
4853 S.DeclareImplicitDefaultConstructor(RD);
4854 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4855 CE = RD->ctor_end(); CI != CE; ++CI) {
4856 if (!CI->isDefaultConstructor())
4857 continue;
4858 DefCtor = *CI;
4859 if (!DefCtor->isUserProvided())
4860 break;
4861 }
4862
4863 *Selected = DefCtor;
4864 }
4865
4866 return false;
4867
4868 case Sema::CXXDestructor:
4869 // C++11 [class.dtor]p5:
4870 // A destructor is trivial if:
4871 // - all the direct [subobjects] have trivial destructors
4872 if (RD->hasTrivialDestructor())
4873 return true;
4874
4875 if (Selected) {
4876 if (RD->needsImplicitDestructor())
4877 S.DeclareImplicitDestructor(RD);
4878 *Selected = RD->getDestructor();
4879 }
4880
4881 return false;
4882
4883 case Sema::CXXCopyConstructor:
4884 // C++11 [class.copy]p12:
4885 // A copy constructor is trivial if:
4886 // - the constructor selected to copy each direct [subobject] is trivial
4887 if (RD->hasTrivialCopyConstructor()) {
4888 if (Quals == Qualifiers::Const)
4889 // We must either select the trivial copy constructor or reach an
4890 // ambiguity; no need to actually perform overload resolution.
4891 return true;
4892 } else if (!Selected) {
4893 return false;
4894 }
4895 // In C++98, we are not supposed to perform overload resolution here, but we
4896 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4897 // cases like B as having a non-trivial copy constructor:
4898 // struct A { template<typename T> A(T&); };
4899 // struct B { mutable A a; };
4900 goto NeedOverloadResolution;
4901
4902 case Sema::CXXCopyAssignment:
4903 // C++11 [class.copy]p25:
4904 // A copy assignment operator is trivial if:
4905 // - the assignment operator selected to copy each direct [subobject] is
4906 // trivial
4907 if (RD->hasTrivialCopyAssignment()) {
4908 if (Quals == Qualifiers::Const)
4909 return true;
4910 } else if (!Selected) {
4911 return false;
4912 }
4913 // In C++98, we are not supposed to perform overload resolution here, but we
4914 // treat that as a language defect.
4915 goto NeedOverloadResolution;
4916
4917 case Sema::CXXMoveConstructor:
4918 case Sema::CXXMoveAssignment:
4919 NeedOverloadResolution:
4920 Sema::SpecialMemberOverloadResult *SMOR =
4921 S.LookupSpecialMember(RD, CSM,
4922 Quals & Qualifiers::Const,
4923 Quals & Qualifiers::Volatile,
4924 /*RValueThis*/false, /*ConstThis*/false,
4925 /*VolatileThis*/false);
4926
4927 // The standard doesn't describe how to behave if the lookup is ambiguous.
4928 // We treat it as not making the member non-trivial, just like the standard
4929 // mandates for the default constructor. This should rarely matter, because
4930 // the member will also be deleted.
4931 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4932 return true;
4933
4934 if (!SMOR->getMethod()) {
4935 assert(SMOR->getKind() ==
4936 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4937 return false;
4938 }
4939
4940 // We deliberately don't check if we found a deleted special member. We're
4941 // not supposed to!
4942 if (Selected)
4943 *Selected = SMOR->getMethod();
4944 return SMOR->getMethod()->isTrivial();
4945 }
4946
4947 llvm_unreachable("unknown special method kind");
4948}
4949
4950CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
4951 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
4952 CI != CE; ++CI)
4953 if (!CI->isImplicit())
4954 return *CI;
4955
4956 // Look for constructor templates.
4957 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
4958 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
4959 if (CXXConstructorDecl *CD =
4960 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
4961 return CD;
4962 }
4963
4964 return 0;
4965}
4966
4967/// The kind of subobject we are checking for triviality. The values of this
4968/// enumeration are used in diagnostics.
4969enum TrivialSubobjectKind {
4970 /// The subobject is a base class.
4971 TSK_BaseClass,
4972 /// The subobject is a non-static data member.
4973 TSK_Field,
4974 /// The object is actually the complete object.
4975 TSK_CompleteObject
4976};
4977
4978/// Check whether the special member selected for a given type would be trivial.
4979static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
4980 QualType SubType,
4981 Sema::CXXSpecialMember CSM,
4982 TrivialSubobjectKind Kind,
4983 bool Diagnose) {
4984 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
4985 if (!SubRD)
4986 return true;
4987
4988 CXXMethodDecl *Selected;
4989 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
4990 Diagnose ? &Selected : 0))
4991 return true;
4992
4993 if (Diagnose) {
4994 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
4995 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
4996 << Kind << SubType.getUnqualifiedType();
4997 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
4998 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
4999 } else if (!Selected)
5000 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5001 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5002 else if (Selected->isUserProvided()) {
5003 if (Kind == TSK_CompleteObject)
5004 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5005 << Kind << SubType.getUnqualifiedType() << CSM;
5006 else {
5007 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5008 << Kind << SubType.getUnqualifiedType() << CSM;
5009 S.Diag(Selected->getLocation(), diag::note_declared_at);
5010 }
5011 } else {
5012 if (Kind != TSK_CompleteObject)
5013 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5014 << Kind << SubType.getUnqualifiedType() << CSM;
5015
5016 // Explain why the defaulted or deleted special member isn't trivial.
5017 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5018 }
5019 }
5020
5021 return false;
5022}
5023
5024/// Check whether the members of a class type allow a special member to be
5025/// trivial.
5026static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5027 Sema::CXXSpecialMember CSM,
5028 bool ConstArg, bool Diagnose) {
5029 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5030 FE = RD->field_end(); FI != FE; ++FI) {
5031 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5032 continue;
5033
5034 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5035
5036 // Pretend anonymous struct or union members are members of this class.
5037 if (FI->isAnonymousStructOrUnion()) {
5038 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5039 CSM, ConstArg, Diagnose))
5040 return false;
5041 continue;
5042 }
5043
5044 // C++11 [class.ctor]p5:
5045 // A default constructor is trivial if [...]
5046 // -- no non-static data member of its class has a
5047 // brace-or-equal-initializer
5048 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5049 if (Diagnose)
5050 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5051 return false;
5052 }
5053
5054 // Objective C ARC 4.3.5:
5055 // [...] nontrivally ownership-qualified types are [...] not trivially
5056 // default constructible, copy constructible, move constructible, copy
5057 // assignable, move assignable, or destructible [...]
5058 if (S.getLangOpts().ObjCAutoRefCount &&
5059 FieldType.hasNonTrivialObjCLifetime()) {
5060 if (Diagnose)
5061 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5062 << RD << FieldType.getObjCLifetime();
5063 return false;
5064 }
5065
5066 if (ConstArg && !FI->isMutable())
5067 FieldType.addConst();
5068 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5069 TSK_Field, Diagnose))
5070 return false;
5071 }
5072
5073 return true;
5074}
5075
5076/// Diagnose why the specified class does not have a trivial special member of
5077/// the given kind.
5078void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5079 QualType Ty = Context.getRecordType(RD);
5080 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5081 Ty.addConst();
5082
5083 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5084 TSK_CompleteObject, /*Diagnose*/true);
5085}
5086
5087/// Determine whether a defaulted or deleted special member function is trivial,
5088/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5089/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5090bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5091 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005092 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5093
5094 CXXRecordDecl *RD = MD->getParent();
5095
5096 bool ConstArg = false;
5097 ParmVarDecl *Param0 = MD->getNumParams() ? MD->getParamDecl(0) : 0;
5098
5099 // C++11 [class.copy]p12, p25:
5100 // A [special member] is trivial if its declared parameter type is the same
5101 // as if it had been implicitly declared [...]
5102 switch (CSM) {
5103 case CXXDefaultConstructor:
5104 case CXXDestructor:
5105 // Trivial default constructors and destructors cannot have parameters.
5106 break;
5107
5108 case CXXCopyConstructor:
5109 case CXXCopyAssignment: {
5110 // Trivial copy operations always have const, non-volatile parameter types.
5111 ConstArg = true;
5112 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5113 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5114 if (Diagnose)
5115 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5116 << Param0->getSourceRange() << Param0->getType()
5117 << Context.getLValueReferenceType(
5118 Context.getRecordType(RD).withConst());
5119 return false;
5120 }
5121 break;
5122 }
5123
5124 case CXXMoveConstructor:
5125 case CXXMoveAssignment: {
5126 // Trivial move operations always have non-cv-qualified parameters.
5127 const RValueReferenceType *RT =
5128 Param0->getType()->getAs<RValueReferenceType>();
5129 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5130 if (Diagnose)
5131 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5132 << Param0->getSourceRange() << Param0->getType()
5133 << Context.getRValueReferenceType(Context.getRecordType(RD));
5134 return false;
5135 }
5136 break;
5137 }
5138
5139 case CXXInvalid:
5140 llvm_unreachable("not a special member");
5141 }
5142
5143 // FIXME: We require that the parameter-declaration-clause is equivalent to
5144 // that of an implicit declaration, not just that the declared parameter type
5145 // matches, in order to prevent absuridities like a function simultaneously
5146 // being a trivial copy constructor and a non-trivial default constructor.
5147 // This issue has not yet been assigned a core issue number.
5148 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5149 if (Diagnose)
5150 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5151 diag::note_nontrivial_default_arg)
5152 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5153 return false;
5154 }
5155 if (MD->isVariadic()) {
5156 if (Diagnose)
5157 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5158 return false;
5159 }
5160
5161 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5162 // A copy/move [constructor or assignment operator] is trivial if
5163 // -- the [member] selected to copy/move each direct base class subobject
5164 // is trivial
5165 //
5166 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5167 // A [default constructor or destructor] is trivial if
5168 // -- all the direct base classes have trivial [default constructors or
5169 // destructors]
5170 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5171 BE = RD->bases_end(); BI != BE; ++BI)
5172 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5173 ConstArg ? BI->getType().withConst()
5174 : BI->getType(),
5175 CSM, TSK_BaseClass, Diagnose))
5176 return false;
5177
5178 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5179 // A copy/move [constructor or assignment operator] for a class X is
5180 // trivial if
5181 // -- for each non-static data member of X that is of class type (or array
5182 // thereof), the constructor selected to copy/move that member is
5183 // trivial
5184 //
5185 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5186 // A [default constructor or destructor] is trivial if
5187 // -- for all of the non-static data members of its class that are of class
5188 // type (or array thereof), each such class has a trivial [default
5189 // constructor or destructor]
5190 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5191 return false;
5192
5193 // C++11 [class.dtor]p5:
5194 // A destructor is trivial if [...]
5195 // -- the destructor is not virtual
5196 if (CSM == CXXDestructor && MD->isVirtual()) {
5197 if (Diagnose)
5198 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5199 return false;
5200 }
5201
5202 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5203 // A [special member] for class X is trivial if [...]
5204 // -- class X has no virtual functions and no virtual base classes
5205 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5206 if (!Diagnose)
5207 return false;
5208
5209 if (RD->getNumVBases()) {
5210 // Check for virtual bases. We already know that the corresponding
5211 // member in all bases is trivial, so vbases must all be direct.
5212 CXXBaseSpecifier &BS = *RD->vbases_begin();
5213 assert(BS.isVirtual());
5214 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5215 return false;
5216 }
5217
5218 // Must have a virtual method.
5219 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5220 ME = RD->method_end(); MI != ME; ++MI) {
5221 if (MI->isVirtual()) {
5222 SourceLocation MLoc = MI->getLocStart();
5223 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5224 return false;
5225 }
5226 }
5227
5228 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5229 }
5230
5231 // Looks like it's trivial!
5232 return true;
5233}
5234
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005235/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005236namespace {
5237 struct FindHiddenVirtualMethodData {
5238 Sema *S;
5239 CXXMethodDecl *Method;
5240 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005241 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005242 };
5243}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005244
David Blaikie5f750682012-10-19 00:53:08 +00005245/// \brief Check whether any most overriden method from MD in Methods
5246static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5247 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5248 if (MD->size_overridden_methods() == 0)
5249 return Methods.count(MD->getCanonicalDecl());
5250 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5251 E = MD->end_overridden_methods();
5252 I != E; ++I)
5253 if (CheckMostOverridenMethods(*I, Methods))
5254 return true;
5255 return false;
5256}
5257
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005258/// \brief Member lookup function that determines whether a given C++
5259/// method overloads virtual methods in a base class without overriding any,
5260/// to be used with CXXRecordDecl::lookupInBases().
5261static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5262 CXXBasePath &Path,
5263 void *UserData) {
5264 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5265
5266 FindHiddenVirtualMethodData &Data
5267 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5268
5269 DeclarationName Name = Data.Method->getDeclName();
5270 assert(Name.getNameKind() == DeclarationName::Identifier);
5271
5272 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005273 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005274 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005275 !Path.Decls.empty();
5276 Path.Decls = Path.Decls.slice(1)) {
5277 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005278 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005279 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005280 foundSameNameMethod = true;
5281 // Interested only in hidden virtual methods.
5282 if (!MD->isVirtual())
5283 continue;
5284 // If the method we are checking overrides a method from its base
5285 // don't warn about the other overloaded methods.
5286 if (!Data.S->IsOverload(Data.Method, MD, false))
5287 return true;
5288 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005289 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005290 overloadedMethods.push_back(MD);
5291 }
5292 }
5293
5294 if (foundSameNameMethod)
5295 Data.OverloadedMethods.append(overloadedMethods.begin(),
5296 overloadedMethods.end());
5297 return foundSameNameMethod;
5298}
5299
David Blaikie5f750682012-10-19 00:53:08 +00005300/// \brief Add the most overriden methods from MD to Methods
5301static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5302 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5303 if (MD->size_overridden_methods() == 0)
5304 Methods.insert(MD->getCanonicalDecl());
5305 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5306 E = MD->end_overridden_methods();
5307 I != E; ++I)
5308 AddMostOverridenMethods(*I, Methods);
5309}
5310
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005311/// \brief See if a method overloads virtual methods in a base class without
5312/// overriding any.
5313void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5314 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005315 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005316 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005317 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005318 return;
5319
5320 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5321 /*bool RecordPaths=*/false,
5322 /*bool DetectVirtual=*/false);
5323 FindHiddenVirtualMethodData Data;
5324 Data.Method = MD;
5325 Data.S = this;
5326
5327 // Keep the base methods that were overriden or introduced in the subclass
5328 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005329 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5330 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5331 NamedDecl *ND = *I;
5332 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005333 ND = shad->getTargetDecl();
5334 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5335 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005336 }
5337
5338 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5339 !Data.OverloadedMethods.empty()) {
5340 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5341 << MD << (Data.OverloadedMethods.size() > 1);
5342
5343 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5344 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5345 Diag(overloadedMD->getLocation(),
5346 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5347 }
5348 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005349}
5350
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005351void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005352 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005353 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005354 SourceLocation RBrac,
5355 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005356 if (!TagDecl)
5357 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005358
Douglas Gregor42af25f2009-05-11 19:58:34 +00005359 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005360
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005361 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5362 if (l->getKind() != AttributeList::AT_Visibility)
5363 continue;
5364 l->setInvalid();
5365 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5366 l->getName();
5367 }
5368
David Blaikie77b6de02011-09-22 02:58:26 +00005369 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005370 // strict aliasing violation!
5371 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005372 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005373
Douglas Gregor23c94db2010-07-02 17:43:08 +00005374 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005375 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005376}
5377
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005378/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5379/// special functions, such as the default constructor, copy
5380/// constructor, or destructor, to the given C++ class (C++
5381/// [special]p1). This routine can only be executed just before the
5382/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005383void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005384 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005385 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005386
Richard Smithbc2a35d2012-12-08 08:32:28 +00005387 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005388 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005389
Richard Smithbc2a35d2012-12-08 08:32:28 +00005390 // If the properties or semantics of the copy constructor couldn't be
5391 // determined while the class was being declared, force a declaration
5392 // of it now.
5393 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5394 DeclareImplicitCopyConstructor(ClassDecl);
5395 }
5396
Richard Smith80ad52f2013-01-02 11:42:31 +00005397 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005398 ++ASTContext::NumImplicitMoveConstructors;
5399
Richard Smithbc2a35d2012-12-08 08:32:28 +00005400 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5401 DeclareImplicitMoveConstructor(ClassDecl);
5402 }
5403
Douglas Gregora376d102010-07-02 21:50:04 +00005404 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5405 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005406
5407 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005408 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005409 // it shows up in the right place in the vtable and that we diagnose
5410 // problems with the implicit exception specification.
5411 if (ClassDecl->isDynamicClass() ||
5412 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005413 DeclareImplicitCopyAssignment(ClassDecl);
5414 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005415
Richard Smith80ad52f2013-01-02 11:42:31 +00005416 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005417 ++ASTContext::NumImplicitMoveAssignmentOperators;
5418
5419 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005420 if (ClassDecl->isDynamicClass() ||
5421 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005422 DeclareImplicitMoveAssignment(ClassDecl);
5423 }
5424
Douglas Gregor4923aa22010-07-02 20:37:36 +00005425 if (!ClassDecl->hasUserDeclaredDestructor()) {
5426 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005427
5428 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005429 // have to declare the destructor immediately. This ensures that, e.g., it
5430 // shows up in the right place in the vtable and that we diagnose problems
5431 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005432 if (ClassDecl->isDynamicClass() ||
5433 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005434 DeclareImplicitDestructor(ClassDecl);
5435 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005436}
5437
Francois Pichet8387e2a2011-04-22 22:18:13 +00005438void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5439 if (!D)
5440 return;
5441
5442 int NumParamList = D->getNumTemplateParameterLists();
5443 for (int i = 0; i < NumParamList; i++) {
5444 TemplateParameterList* Params = D->getTemplateParameterList(i);
5445 for (TemplateParameterList::iterator Param = Params->begin(),
5446 ParamEnd = Params->end();
5447 Param != ParamEnd; ++Param) {
5448 NamedDecl *Named = cast<NamedDecl>(*Param);
5449 if (Named->getDeclName()) {
5450 S->AddDecl(Named);
5451 IdResolver.AddDecl(Named);
5452 }
5453 }
5454 }
5455}
5456
John McCalld226f652010-08-21 09:40:31 +00005457void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005458 if (!D)
5459 return;
5460
5461 TemplateParameterList *Params = 0;
5462 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5463 Params = Template->getTemplateParameters();
5464 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5465 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5466 Params = PartialSpec->getTemplateParameters();
5467 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005468 return;
5469
Douglas Gregor6569d682009-05-27 23:11:45 +00005470 for (TemplateParameterList::iterator Param = Params->begin(),
5471 ParamEnd = Params->end();
5472 Param != ParamEnd; ++Param) {
5473 NamedDecl *Named = cast<NamedDecl>(*Param);
5474 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005475 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005476 IdResolver.AddDecl(Named);
5477 }
5478 }
5479}
5480
John McCalld226f652010-08-21 09:40:31 +00005481void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005482 if (!RecordD) return;
5483 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005484 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005485 PushDeclContext(S, Record);
5486}
5487
John McCalld226f652010-08-21 09:40:31 +00005488void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005489 if (!RecordD) return;
5490 PopDeclContext();
5491}
5492
Douglas Gregor72b505b2008-12-16 21:30:33 +00005493/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5494/// parsing a top-level (non-nested) C++ class, and we are now
5495/// parsing those parts of the given Method declaration that could
5496/// not be parsed earlier (C++ [class.mem]p2), such as default
5497/// arguments. This action should enter the scope of the given
5498/// Method declaration as if we had just parsed the qualified method
5499/// name. However, it should not bring the parameters into scope;
5500/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005501void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005502}
5503
5504/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5505/// C++ method declaration. We're (re-)introducing the given
5506/// function parameter into scope for use in parsing later parts of
5507/// the method declaration. For example, we could see an
5508/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005509void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005510 if (!ParamD)
5511 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005512
John McCalld226f652010-08-21 09:40:31 +00005513 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005514
5515 // If this parameter has an unparsed default argument, clear it out
5516 // to make way for the parsed default argument.
5517 if (Param->hasUnparsedDefaultArg())
5518 Param->setDefaultArg(0);
5519
John McCalld226f652010-08-21 09:40:31 +00005520 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005521 if (Param->getDeclName())
5522 IdResolver.AddDecl(Param);
5523}
5524
5525/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5526/// processing the delayed method declaration for Method. The method
5527/// declaration is now considered finished. There may be a separate
5528/// ActOnStartOfFunctionDef action later (not necessarily
5529/// immediately!) for this method, if it was also defined inside the
5530/// class body.
John McCalld226f652010-08-21 09:40:31 +00005531void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005532 if (!MethodD)
5533 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005534
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005535 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005536
John McCalld226f652010-08-21 09:40:31 +00005537 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005538
5539 // Now that we have our default arguments, check the constructor
5540 // again. It could produce additional diagnostics or affect whether
5541 // the class has implicitly-declared destructors, among other
5542 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005543 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5544 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005545
5546 // Check the default arguments, which we may have added.
5547 if (!Method->isInvalidDecl())
5548 CheckCXXDefaultArguments(Method);
5549}
5550
Douglas Gregor42a552f2008-11-05 20:51:48 +00005551/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005552/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005553/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005554/// emit diagnostics and set the invalid bit to true. In any case, the type
5555/// will be updated to reflect a well-formed type for the constructor and
5556/// returned.
5557QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005558 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005559 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005560
5561 // C++ [class.ctor]p3:
5562 // A constructor shall not be virtual (10.3) or static (9.4). A
5563 // constructor can be invoked for a const, volatile or const
5564 // volatile object. A constructor shall not be declared const,
5565 // volatile, or const volatile (9.3.2).
5566 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005567 if (!D.isInvalidType())
5568 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5569 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5570 << SourceRange(D.getIdentifierLoc());
5571 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005572 }
John McCalld931b082010-08-26 03:08:43 +00005573 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005574 if (!D.isInvalidType())
5575 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5576 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5577 << SourceRange(D.getIdentifierLoc());
5578 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005579 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005580 }
Mike Stump1eb44332009-09-09 15:08:12 +00005581
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005582 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005583 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005584 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005585 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5586 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005587 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005588 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5589 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005590 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005591 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5592 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005593 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005594 }
Mike Stump1eb44332009-09-09 15:08:12 +00005595
Douglas Gregorc938c162011-01-26 05:01:58 +00005596 // C++0x [class.ctor]p4:
5597 // A constructor shall not be declared with a ref-qualifier.
5598 if (FTI.hasRefQualifier()) {
5599 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5600 << FTI.RefQualifierIsLValueRef
5601 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5602 D.setInvalidType();
5603 }
5604
Douglas Gregor42a552f2008-11-05 20:51:48 +00005605 // Rebuild the function type "R" without any type qualifiers (in
5606 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005607 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005608 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005609 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5610 return R;
5611
5612 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5613 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005614 EPI.RefQualifier = RQ_None;
5615
Chris Lattner65401802009-04-25 08:28:21 +00005616 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005617 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005618}
5619
Douglas Gregor72b505b2008-12-16 21:30:33 +00005620/// CheckConstructor - Checks a fully-formed constructor for
5621/// well-formedness, issuing any diagnostics required. Returns true if
5622/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005623void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005624 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005625 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5626 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005627 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005628
5629 // C++ [class.copy]p3:
5630 // A declaration of a constructor for a class X is ill-formed if
5631 // its first parameter is of type (optionally cv-qualified) X and
5632 // either there are no other parameters or else all other
5633 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005634 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005635 ((Constructor->getNumParams() == 1) ||
5636 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005637 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5638 Constructor->getTemplateSpecializationKind()
5639 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005640 QualType ParamType = Constructor->getParamDecl(0)->getType();
5641 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5642 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005643 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005644 const char *ConstRef
5645 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5646 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005647 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005648 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005649
5650 // FIXME: Rather that making the constructor invalid, we should endeavor
5651 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005652 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005653 }
5654 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005655}
5656
John McCall15442822010-08-04 01:04:25 +00005657/// CheckDestructor - Checks a fully-formed destructor definition for
5658/// well-formedness, issuing any diagnostics required. Returns true
5659/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005660bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005661 CXXRecordDecl *RD = Destructor->getParent();
5662
5663 if (Destructor->isVirtual()) {
5664 SourceLocation Loc;
5665
5666 if (!Destructor->isImplicit())
5667 Loc = Destructor->getLocation();
5668 else
5669 Loc = RD->getLocation();
5670
5671 // If we have a virtual destructor, look up the deallocation function
5672 FunctionDecl *OperatorDelete = 0;
5673 DeclarationName Name =
5674 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005675 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005676 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005677
Eli Friedman5f2987c2012-02-02 03:46:19 +00005678 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005679
5680 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005681 }
Anders Carlsson37909802009-11-30 21:24:50 +00005682
5683 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005684}
5685
Mike Stump1eb44332009-09-09 15:08:12 +00005686static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005687FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5688 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5689 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005690 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005691}
5692
Douglas Gregor42a552f2008-11-05 20:51:48 +00005693/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5694/// the well-formednes of the destructor declarator @p D with type @p
5695/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005696/// emit diagnostics and set the declarator to invalid. Even if this happens,
5697/// will be updated to reflect a well-formed type for the destructor and
5698/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005699QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005700 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005701 // C++ [class.dtor]p1:
5702 // [...] A typedef-name that names a class is a class-name
5703 // (7.1.3); however, a typedef-name that names a class shall not
5704 // be used as the identifier in the declarator for a destructor
5705 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005706 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005707 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005708 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005709 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005710 else if (const TemplateSpecializationType *TST =
5711 DeclaratorType->getAs<TemplateSpecializationType>())
5712 if (TST->isTypeAlias())
5713 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5714 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005715
5716 // C++ [class.dtor]p2:
5717 // A destructor is used to destroy objects of its class type. A
5718 // destructor takes no parameters, and no return type can be
5719 // specified for it (not even void). The address of a destructor
5720 // shall not be taken. A destructor shall not be static. A
5721 // destructor can be invoked for a const, volatile or const
5722 // volatile object. A destructor shall not be declared const,
5723 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005724 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005725 if (!D.isInvalidType())
5726 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5727 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005728 << SourceRange(D.getIdentifierLoc())
5729 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5730
John McCalld931b082010-08-26 03:08:43 +00005731 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005732 }
Chris Lattner65401802009-04-25 08:28:21 +00005733 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005734 // Destructors don't have return types, but the parser will
5735 // happily parse something like:
5736 //
5737 // class X {
5738 // float ~X();
5739 // };
5740 //
5741 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005742 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5743 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5744 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005745 }
Mike Stump1eb44332009-09-09 15:08:12 +00005746
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005747 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005748 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005749 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005750 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5751 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005752 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005753 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5754 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005755 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005756 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5757 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005758 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005759 }
5760
Douglas Gregorc938c162011-01-26 05:01:58 +00005761 // C++0x [class.dtor]p2:
5762 // A destructor shall not be declared with a ref-qualifier.
5763 if (FTI.hasRefQualifier()) {
5764 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5765 << FTI.RefQualifierIsLValueRef
5766 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5767 D.setInvalidType();
5768 }
5769
Douglas Gregor42a552f2008-11-05 20:51:48 +00005770 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005771 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005772 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5773
5774 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005775 FTI.freeArgs();
5776 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005777 }
5778
Mike Stump1eb44332009-09-09 15:08:12 +00005779 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005780 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005781 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005782 D.setInvalidType();
5783 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005784
5785 // Rebuild the function type "R" without any type qualifiers or
5786 // parameters (in case any of the errors above fired) and with
5787 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005788 // types.
John McCalle23cf432010-12-14 08:05:40 +00005789 if (!D.isInvalidType())
5790 return R;
5791
Douglas Gregord92ec472010-07-01 05:10:53 +00005792 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005793 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5794 EPI.Variadic = false;
5795 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005796 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005797 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005798}
5799
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005800/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5801/// well-formednes of the conversion function declarator @p D with
5802/// type @p R. If there are any errors in the declarator, this routine
5803/// will emit diagnostics and return true. Otherwise, it will return
5804/// false. Either way, the type @p R will be updated to reflect a
5805/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005806void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005807 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005808 // C++ [class.conv.fct]p1:
5809 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005810 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005811 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005812 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005813 if (!D.isInvalidType())
5814 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5815 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5816 << SourceRange(D.getIdentifierLoc());
5817 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005818 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005819 }
John McCalla3f81372010-04-13 00:04:31 +00005820
5821 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5822
Chris Lattner6e475012009-04-25 08:35:12 +00005823 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005824 // Conversion functions don't have return types, but the parser will
5825 // happily parse something like:
5826 //
5827 // class X {
5828 // float operator bool();
5829 // };
5830 //
5831 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005832 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5833 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5834 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005835 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005836 }
5837
John McCalla3f81372010-04-13 00:04:31 +00005838 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5839
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005840 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005841 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005842 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5843
5844 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005845 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005846 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005847 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005848 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005849 D.setInvalidType();
5850 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005851
John McCalla3f81372010-04-13 00:04:31 +00005852 // Diagnose "&operator bool()" and other such nonsense. This
5853 // is actually a gcc extension which we don't support.
5854 if (Proto->getResultType() != ConvType) {
5855 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5856 << Proto->getResultType();
5857 D.setInvalidType();
5858 ConvType = Proto->getResultType();
5859 }
5860
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005861 // C++ [class.conv.fct]p4:
5862 // The conversion-type-id shall not represent a function type nor
5863 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005864 if (ConvType->isArrayType()) {
5865 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5866 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005867 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005868 } else if (ConvType->isFunctionType()) {
5869 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5870 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005871 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005872 }
5873
5874 // Rebuild the function type "R" without any parameters (in case any
5875 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005876 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005877 if (D.isInvalidType())
5878 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005879
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005880 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005881 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005882 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005883 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005884 diag::warn_cxx98_compat_explicit_conversion_functions :
5885 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005886 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005887}
5888
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005889/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5890/// the declaration of the given C++ conversion function. This routine
5891/// is responsible for recording the conversion function in the C++
5892/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005893Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005894 assert(Conversion && "Expected to receive a conversion function declaration");
5895
Douglas Gregor9d350972008-12-12 08:25:50 +00005896 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005897
5898 // Make sure we aren't redeclaring the conversion function.
5899 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005900
5901 // C++ [class.conv.fct]p1:
5902 // [...] A conversion function is never used to convert a
5903 // (possibly cv-qualified) object to the (possibly cv-qualified)
5904 // same object type (or a reference to it), to a (possibly
5905 // cv-qualified) base class of that type (or a reference to it),
5906 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005907 // FIXME: Suppress this warning if the conversion function ends up being a
5908 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005909 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005910 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005911 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005912 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005913 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5914 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005915 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005916 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005917 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5918 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005919 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005920 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005921 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005922 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005923 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005924 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005925 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005926 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005927 }
5928
Douglas Gregore80622f2010-09-29 04:25:11 +00005929 if (FunctionTemplateDecl *ConversionTemplate
5930 = Conversion->getDescribedFunctionTemplate())
5931 return ConversionTemplate;
5932
John McCalld226f652010-08-21 09:40:31 +00005933 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005934}
5935
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005936//===----------------------------------------------------------------------===//
5937// Namespace Handling
5938//===----------------------------------------------------------------------===//
5939
Richard Smithd1a55a62012-10-04 22:13:39 +00005940/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5941/// reopened.
5942static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5943 SourceLocation Loc,
5944 IdentifierInfo *II, bool *IsInline,
5945 NamespaceDecl *PrevNS) {
5946 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00005947
Richard Smithc969e6a2012-10-05 01:46:25 +00005948 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5949 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5950 // inline namespaces, with the intention of bringing names into namespace std.
5951 //
5952 // We support this just well enough to get that case working; this is not
5953 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00005954 if (*IsInline && II && II->getName().startswith("__atomic") &&
5955 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00005956 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00005957 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5958 NS = NS->getPreviousDecl())
5959 NS->setInline(*IsInline);
5960 // Patch up the lookup table for the containing namespace. This isn't really
5961 // correct, but it's good enough for this particular case.
5962 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5963 E = PrevNS->decls_end(); I != E; ++I)
5964 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5965 PrevNS->getParent()->makeDeclVisibleInContext(ND);
5966 return;
5967 }
5968
5969 if (PrevNS->isInline())
5970 // The user probably just forgot the 'inline', so suggest that it
5971 // be added back.
5972 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5973 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
5974 else
5975 S.Diag(Loc, diag::err_inline_namespace_mismatch)
5976 << IsInline;
5977
5978 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
5979 *IsInline = PrevNS->isInline();
5980}
John McCallea318642010-08-26 09:15:37 +00005981
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005982/// ActOnStartNamespaceDef - This is called at the start of a namespace
5983/// definition.
John McCalld226f652010-08-21 09:40:31 +00005984Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005985 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005986 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005987 SourceLocation IdentLoc,
5988 IdentifierInfo *II,
5989 SourceLocation LBrace,
5990 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005991 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5992 // For anonymous namespace, take the location of the left brace.
5993 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005994 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005995 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005996 bool IsStd = false;
5997 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005998 Scope *DeclRegionScope = NamespcScope->getParent();
5999
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006000 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006001 if (II) {
6002 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006003 // The identifier in an original-namespace-definition shall not
6004 // have been previously defined in the declarative region in
6005 // which the original-namespace-definition appears. The
6006 // identifier in an original-namespace-definition is the name of
6007 // the namespace. Subsequently in that declarative region, it is
6008 // treated as an original-namespace-name.
6009 //
6010 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006011 // look through using directives, just look for any ordinary names.
6012
6013 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006014 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6015 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006016 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006017 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6018 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6019 ++I) {
6020 if ((*I)->getIdentifierNamespace() & IDNS) {
6021 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006022 break;
6023 }
6024 }
6025
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006026 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6027
6028 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006029 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006030 if (IsInline != PrevNS->isInline())
6031 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6032 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006033 } else if (PrevDecl) {
6034 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006035 Diag(Loc, diag::err_redefinition_different_kind)
6036 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006037 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006038 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006039 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006040 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006041 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006042 // This is the first "real" definition of the namespace "std", so update
6043 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006044 PrevNS = getStdNamespace();
6045 IsStd = true;
6046 AddToKnown = !IsInline;
6047 } else {
6048 // We've seen this namespace for the first time.
6049 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006050 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006051 } else {
John McCall9aeed322009-10-01 00:25:31 +00006052 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006053
6054 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006055 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006056 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006057 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006058 } else {
6059 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006060 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006061 }
6062
Richard Smithd1a55a62012-10-04 22:13:39 +00006063 if (PrevNS && IsInline != PrevNS->isInline())
6064 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6065 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006066 }
6067
6068 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6069 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006070 if (IsInvalid)
6071 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006072
6073 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006074
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006075 // FIXME: Should we be merging attributes?
6076 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006077 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006078
6079 if (IsStd)
6080 StdNamespace = Namespc;
6081 if (AddToKnown)
6082 KnownNamespaces[Namespc] = false;
6083
6084 if (II) {
6085 PushOnScopeChains(Namespc, DeclRegionScope);
6086 } else {
6087 // Link the anonymous namespace into its parent.
6088 DeclContext *Parent = CurContext->getRedeclContext();
6089 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6090 TU->setAnonymousNamespace(Namespc);
6091 } else {
6092 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006093 }
John McCall9aeed322009-10-01 00:25:31 +00006094
Douglas Gregora4181472010-03-24 00:46:35 +00006095 CurContext->addDecl(Namespc);
6096
John McCall9aeed322009-10-01 00:25:31 +00006097 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6098 // behaves as if it were replaced by
6099 // namespace unique { /* empty body */ }
6100 // using namespace unique;
6101 // namespace unique { namespace-body }
6102 // where all occurrences of 'unique' in a translation unit are
6103 // replaced by the same identifier and this identifier differs
6104 // from all other identifiers in the entire program.
6105
6106 // We just create the namespace with an empty name and then add an
6107 // implicit using declaration, just like the standard suggests.
6108 //
6109 // CodeGen enforces the "universally unique" aspect by giving all
6110 // declarations semantically contained within an anonymous
6111 // namespace internal linkage.
6112
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006113 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006114 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006115 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006116 /* 'using' */ LBrace,
6117 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006118 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006119 /* identifier */ SourceLocation(),
6120 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006121 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006122 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006123 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006124 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006125 }
6126
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006127 ActOnDocumentableDecl(Namespc);
6128
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006129 // Although we could have an invalid decl (i.e. the namespace name is a
6130 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006131 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6132 // for the namespace has the declarations that showed up in that particular
6133 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006134 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006135 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006136}
6137
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006138/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6139/// is a namespace alias, returns the namespace it points to.
6140static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6141 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6142 return AD->getNamespace();
6143 return dyn_cast_or_null<NamespaceDecl>(D);
6144}
6145
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006146/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6147/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006148void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006149 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6150 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006151 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006152 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006153 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006154 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006155}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006156
John McCall384aff82010-08-25 07:42:41 +00006157CXXRecordDecl *Sema::getStdBadAlloc() const {
6158 return cast_or_null<CXXRecordDecl>(
6159 StdBadAlloc.get(Context.getExternalSource()));
6160}
6161
6162NamespaceDecl *Sema::getStdNamespace() const {
6163 return cast_or_null<NamespaceDecl>(
6164 StdNamespace.get(Context.getExternalSource()));
6165}
6166
Douglas Gregor66992202010-06-29 17:53:46 +00006167/// \brief Retrieve the special "std" namespace, which may require us to
6168/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006169NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006170 if (!StdNamespace) {
6171 // The "std" namespace has not yet been defined, so build one implicitly.
6172 StdNamespace = NamespaceDecl::Create(Context,
6173 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006174 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006175 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006176 &PP.getIdentifierTable().get("std"),
6177 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006178 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006179 }
6180
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006181 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006182}
6183
Sebastian Redl395e04d2012-01-17 22:49:33 +00006184bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006185 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006186 "Looking for std::initializer_list outside of C++.");
6187
6188 // We're looking for implicit instantiations of
6189 // template <typename E> class std::initializer_list.
6190
6191 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6192 return false;
6193
Sebastian Redl84760e32012-01-17 22:49:58 +00006194 ClassTemplateDecl *Template = 0;
6195 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006196
Sebastian Redl84760e32012-01-17 22:49:58 +00006197 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006198
Sebastian Redl84760e32012-01-17 22:49:58 +00006199 ClassTemplateSpecializationDecl *Specialization =
6200 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6201 if (!Specialization)
6202 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006203
Sebastian Redl84760e32012-01-17 22:49:58 +00006204 Template = Specialization->getSpecializedTemplate();
6205 Arguments = Specialization->getTemplateArgs().data();
6206 } else if (const TemplateSpecializationType *TST =
6207 Ty->getAs<TemplateSpecializationType>()) {
6208 Template = dyn_cast_or_null<ClassTemplateDecl>(
6209 TST->getTemplateName().getAsTemplateDecl());
6210 Arguments = TST->getArgs();
6211 }
6212 if (!Template)
6213 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006214
6215 if (!StdInitializerList) {
6216 // Haven't recognized std::initializer_list yet, maybe this is it.
6217 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6218 if (TemplateClass->getIdentifier() !=
6219 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006220 !getStdNamespace()->InEnclosingNamespaceSetOf(
6221 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006222 return false;
6223 // This is a template called std::initializer_list, but is it the right
6224 // template?
6225 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006226 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006227 return false;
6228 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6229 return false;
6230
6231 // It's the right template.
6232 StdInitializerList = Template;
6233 }
6234
6235 if (Template != StdInitializerList)
6236 return false;
6237
6238 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006239 if (Element)
6240 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006241 return true;
6242}
6243
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006244static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6245 NamespaceDecl *Std = S.getStdNamespace();
6246 if (!Std) {
6247 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6248 return 0;
6249 }
6250
6251 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6252 Loc, Sema::LookupOrdinaryName);
6253 if (!S.LookupQualifiedName(Result, Std)) {
6254 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6255 return 0;
6256 }
6257 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6258 if (!Template) {
6259 Result.suppressDiagnostics();
6260 // We found something weird. Complain about the first thing we found.
6261 NamedDecl *Found = *Result.begin();
6262 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6263 return 0;
6264 }
6265
6266 // We found some template called std::initializer_list. Now verify that it's
6267 // correct.
6268 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006269 if (Params->getMinRequiredArguments() != 1 ||
6270 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006271 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6272 return 0;
6273 }
6274
6275 return Template;
6276}
6277
6278QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6279 if (!StdInitializerList) {
6280 StdInitializerList = LookupStdInitializerList(*this, Loc);
6281 if (!StdInitializerList)
6282 return QualType();
6283 }
6284
6285 TemplateArgumentListInfo Args(Loc, Loc);
6286 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6287 Context.getTrivialTypeSourceInfo(Element,
6288 Loc)));
6289 return Context.getCanonicalType(
6290 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6291}
6292
Sebastian Redl98d36062012-01-17 22:50:14 +00006293bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6294 // C++ [dcl.init.list]p2:
6295 // A constructor is an initializer-list constructor if its first parameter
6296 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6297 // std::initializer_list<E> for some type E, and either there are no other
6298 // parameters or else all other parameters have default arguments.
6299 if (Ctor->getNumParams() < 1 ||
6300 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6301 return false;
6302
6303 QualType ArgType = Ctor->getParamDecl(0)->getType();
6304 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6305 ArgType = RT->getPointeeType().getUnqualifiedType();
6306
6307 return isStdInitializerList(ArgType, 0);
6308}
6309
Douglas Gregor9172aa62011-03-26 22:25:30 +00006310/// \brief Determine whether a using statement is in a context where it will be
6311/// apply in all contexts.
6312static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6313 switch (CurContext->getDeclKind()) {
6314 case Decl::TranslationUnit:
6315 return true;
6316 case Decl::LinkageSpec:
6317 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6318 default:
6319 return false;
6320 }
6321}
6322
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006323namespace {
6324
6325// Callback to only accept typo corrections that are namespaces.
6326class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6327 public:
6328 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6329 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6330 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6331 }
6332 return false;
6333 }
6334};
6335
6336}
6337
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006338static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6339 CXXScopeSpec &SS,
6340 SourceLocation IdentLoc,
6341 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006342 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006343 R.clear();
6344 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006345 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006346 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006347 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6348 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006349 if (DeclContext *DC = S.computeDeclContext(SS, false))
6350 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6351 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006352 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6353 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006354 else
6355 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6356 << Ident << CorrectedQuotedStr
6357 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006358
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006359 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6360 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006361
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006362 R.addDecl(Corrected.getCorrectionDecl());
6363 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006364 }
6365 return false;
6366}
6367
John McCalld226f652010-08-21 09:40:31 +00006368Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006369 SourceLocation UsingLoc,
6370 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006371 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006372 SourceLocation IdentLoc,
6373 IdentifierInfo *NamespcName,
6374 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006375 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6376 assert(NamespcName && "Invalid NamespcName.");
6377 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006378
6379 // This can only happen along a recovery path.
6380 while (S->getFlags() & Scope::TemplateParamScope)
6381 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006382 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006383
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006384 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006385 NestedNameSpecifier *Qualifier = 0;
6386 if (SS.isSet())
6387 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6388
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006389 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006390 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6391 LookupParsedName(R, S, &SS);
6392 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006393 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006394
Douglas Gregor66992202010-06-29 17:53:46 +00006395 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006396 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006397 // Allow "using namespace std;" or "using namespace ::std;" even if
6398 // "std" hasn't been defined yet, for GCC compatibility.
6399 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6400 NamespcName->isStr("std")) {
6401 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006402 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006403 R.resolveKind();
6404 }
6405 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006406 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006407 }
6408
John McCallf36e02d2009-10-09 21:13:30 +00006409 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006410 NamedDecl *Named = R.getFoundDecl();
6411 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6412 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006413 // C++ [namespace.udir]p1:
6414 // A using-directive specifies that the names in the nominated
6415 // namespace can be used in the scope in which the
6416 // using-directive appears after the using-directive. During
6417 // unqualified name lookup (3.4.1), the names appear as if they
6418 // were declared in the nearest enclosing namespace which
6419 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006420 // namespace. [Note: in this context, "contains" means "contains
6421 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006422
6423 // Find enclosing context containing both using-directive and
6424 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006425 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006426 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6427 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6428 CommonAncestor = CommonAncestor->getParent();
6429
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006430 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006431 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006432 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006433
Douglas Gregor9172aa62011-03-26 22:25:30 +00006434 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006435 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006436 Diag(IdentLoc, diag::warn_using_directive_in_header);
6437 }
6438
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006439 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006440 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006441 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006442 }
6443
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006444 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006445 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006446}
6447
6448void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006449 // If the scope has an associated entity and the using directive is at
6450 // namespace or translation unit scope, add the UsingDirectiveDecl into
6451 // its lookup structure so qualified name lookup can find it.
6452 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6453 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006454 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006455 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006456 // Otherwise, it is at block sope. The using-directives will affect lookup
6457 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006458 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006459}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006460
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006461
John McCalld226f652010-08-21 09:40:31 +00006462Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006463 AccessSpecifier AS,
6464 bool HasUsingKeyword,
6465 SourceLocation UsingLoc,
6466 CXXScopeSpec &SS,
6467 UnqualifiedId &Name,
6468 AttributeList *AttrList,
6469 bool IsTypeName,
6470 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006471 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006472
Douglas Gregor12c118a2009-11-04 16:30:06 +00006473 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006474 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006475 case UnqualifiedId::IK_Identifier:
6476 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006477 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006478 case UnqualifiedId::IK_ConversionFunctionId:
6479 break;
6480
6481 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006482 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006483 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006484 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006485 getLangOpts().CPlusPlus11 ?
Richard Smitha1366cb2012-04-27 19:33:05 +00006486 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6487 // instead once inheriting constructors work.
6488 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00006489 diag::err_using_decl_constructor)
6490 << SS.getRange();
6491
Richard Smith80ad52f2013-01-02 11:42:31 +00006492 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006493
John McCalld226f652010-08-21 09:40:31 +00006494 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006495
6496 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006497 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006498 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006499 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006500
6501 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006502 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006503 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006504 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006505 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006506
6507 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6508 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006509 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006510 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006511
John McCall60fa3cf2009-12-11 02:10:03 +00006512 // Warn about using declarations.
6513 // TODO: store that the declaration was written without 'using' and
6514 // talk about access decls instead of using decls in the
6515 // diagnostics.
6516 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006517 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006518
6519 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006520 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006521 }
6522
Douglas Gregor56c04582010-12-16 00:46:58 +00006523 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6524 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6525 return 0;
6526
John McCall9488ea12009-11-17 05:59:44 +00006527 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006528 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006529 /* IsInstantiation */ false,
6530 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006531 if (UD)
6532 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006533
John McCalld226f652010-08-21 09:40:31 +00006534 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006535}
6536
Douglas Gregor09acc982010-07-07 23:08:52 +00006537/// \brief Determine whether a using declaration considers the given
6538/// declarations as "equivalent", e.g., if they are redeclarations of
6539/// the same entity or are both typedefs of the same type.
6540static bool
6541IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6542 bool &SuppressRedeclaration) {
6543 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6544 SuppressRedeclaration = false;
6545 return true;
6546 }
6547
Richard Smith162e1c12011-04-15 14:24:37 +00006548 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6549 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006550 SuppressRedeclaration = true;
6551 return Context.hasSameType(TD1->getUnderlyingType(),
6552 TD2->getUnderlyingType());
6553 }
6554
6555 return false;
6556}
6557
6558
John McCall9f54ad42009-12-10 09:41:52 +00006559/// Determines whether to create a using shadow decl for a particular
6560/// decl, given the set of decls existing prior to this using lookup.
6561bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6562 const LookupResult &Previous) {
6563 // Diagnose finding a decl which is not from a base class of the
6564 // current class. We do this now because there are cases where this
6565 // function will silently decide not to build a shadow decl, which
6566 // will pre-empt further diagnostics.
6567 //
6568 // We don't need to do this in C++0x because we do the check once on
6569 // the qualifier.
6570 //
6571 // FIXME: diagnose the following if we care enough:
6572 // struct A { int foo; };
6573 // struct B : A { using A::foo; };
6574 // template <class T> struct C : A {};
6575 // template <class T> struct D : C<T> { using B::foo; } // <---
6576 // This is invalid (during instantiation) in C++03 because B::foo
6577 // resolves to the using decl in B, which is not a base class of D<T>.
6578 // We can't diagnose it immediately because C<T> is an unknown
6579 // specialization. The UsingShadowDecl in D<T> then points directly
6580 // to A::foo, which will look well-formed when we instantiate.
6581 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006582 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006583 DeclContext *OrigDC = Orig->getDeclContext();
6584
6585 // Handle enums and anonymous structs.
6586 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6587 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6588 while (OrigRec->isAnonymousStructOrUnion())
6589 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6590
6591 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6592 if (OrigDC == CurContext) {
6593 Diag(Using->getLocation(),
6594 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006595 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006596 Diag(Orig->getLocation(), diag::note_using_decl_target);
6597 return true;
6598 }
6599
Douglas Gregordc355712011-02-25 00:36:19 +00006600 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006601 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006602 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006603 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006604 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006605 Diag(Orig->getLocation(), diag::note_using_decl_target);
6606 return true;
6607 }
6608 }
6609
6610 if (Previous.empty()) return false;
6611
6612 NamedDecl *Target = Orig;
6613 if (isa<UsingShadowDecl>(Target))
6614 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6615
John McCalld7533ec2009-12-11 02:33:26 +00006616 // If the target happens to be one of the previous declarations, we
6617 // don't have a conflict.
6618 //
6619 // FIXME: but we might be increasing its access, in which case we
6620 // should redeclare it.
6621 NamedDecl *NonTag = 0, *Tag = 0;
6622 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6623 I != E; ++I) {
6624 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006625 bool Result;
6626 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6627 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006628
6629 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6630 }
6631
John McCall9f54ad42009-12-10 09:41:52 +00006632 if (Target->isFunctionOrFunctionTemplate()) {
6633 FunctionDecl *FD;
6634 if (isa<FunctionTemplateDecl>(Target))
6635 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6636 else
6637 FD = cast<FunctionDecl>(Target);
6638
6639 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006640 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006641 case Ovl_Overload:
6642 return false;
6643
6644 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006645 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006646 break;
6647
6648 // We found a decl with the exact signature.
6649 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006650 // If we're in a record, we want to hide the target, so we
6651 // return true (without a diagnostic) to tell the caller not to
6652 // build a shadow decl.
6653 if (CurContext->isRecord())
6654 return true;
6655
6656 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006657 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006658 break;
6659 }
6660
6661 Diag(Target->getLocation(), diag::note_using_decl_target);
6662 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6663 return true;
6664 }
6665
6666 // Target is not a function.
6667
John McCall9f54ad42009-12-10 09:41:52 +00006668 if (isa<TagDecl>(Target)) {
6669 // No conflict between a tag and a non-tag.
6670 if (!Tag) return false;
6671
John McCall41ce66f2009-12-10 19:51:03 +00006672 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006673 Diag(Target->getLocation(), diag::note_using_decl_target);
6674 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6675 return true;
6676 }
6677
6678 // No conflict between a tag and a non-tag.
6679 if (!NonTag) return false;
6680
John McCall41ce66f2009-12-10 19:51:03 +00006681 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006682 Diag(Target->getLocation(), diag::note_using_decl_target);
6683 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6684 return true;
6685}
6686
John McCall9488ea12009-11-17 05:59:44 +00006687/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006688UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006689 UsingDecl *UD,
6690 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006691
6692 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006693 NamedDecl *Target = Orig;
6694 if (isa<UsingShadowDecl>(Target)) {
6695 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6696 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006697 }
6698
6699 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006700 = UsingShadowDecl::Create(Context, CurContext,
6701 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006702 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006703
6704 Shadow->setAccess(UD->getAccess());
6705 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6706 Shadow->setInvalidDecl();
6707
John McCall9488ea12009-11-17 05:59:44 +00006708 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006709 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006710 else
John McCall604e7f12009-12-08 07:46:18 +00006711 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006712
John McCall604e7f12009-12-08 07:46:18 +00006713
John McCall9f54ad42009-12-10 09:41:52 +00006714 return Shadow;
6715}
John McCall604e7f12009-12-08 07:46:18 +00006716
John McCall9f54ad42009-12-10 09:41:52 +00006717/// Hides a using shadow declaration. This is required by the current
6718/// using-decl implementation when a resolvable using declaration in a
6719/// class is followed by a declaration which would hide or override
6720/// one or more of the using decl's targets; for example:
6721///
6722/// struct Base { void foo(int); };
6723/// struct Derived : Base {
6724/// using Base::foo;
6725/// void foo(int);
6726/// };
6727///
6728/// The governing language is C++03 [namespace.udecl]p12:
6729///
6730/// When a using-declaration brings names from a base class into a
6731/// derived class scope, member functions in the derived class
6732/// override and/or hide member functions with the same name and
6733/// parameter types in a base class (rather than conflicting).
6734///
6735/// There are two ways to implement this:
6736/// (1) optimistically create shadow decls when they're not hidden
6737/// by existing declarations, or
6738/// (2) don't create any shadow decls (or at least don't make them
6739/// visible) until we've fully parsed/instantiated the class.
6740/// The problem with (1) is that we might have to retroactively remove
6741/// a shadow decl, which requires several O(n) operations because the
6742/// decl structures are (very reasonably) not designed for removal.
6743/// (2) avoids this but is very fiddly and phase-dependent.
6744void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006745 if (Shadow->getDeclName().getNameKind() ==
6746 DeclarationName::CXXConversionFunctionName)
6747 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6748
John McCall9f54ad42009-12-10 09:41:52 +00006749 // Remove it from the DeclContext...
6750 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006751
John McCall9f54ad42009-12-10 09:41:52 +00006752 // ...and the scope, if applicable...
6753 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006754 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006755 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006756 }
6757
John McCall9f54ad42009-12-10 09:41:52 +00006758 // ...and the using decl.
6759 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6760
6761 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006762 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006763}
6764
John McCall7ba107a2009-11-18 02:36:19 +00006765/// Builds a using declaration.
6766///
6767/// \param IsInstantiation - Whether this call arises from an
6768/// instantiation of an unresolved using declaration. We treat
6769/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006770NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6771 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006772 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006773 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006774 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006775 bool IsInstantiation,
6776 bool IsTypeName,
6777 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006778 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006779 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006780 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006781
Anders Carlsson550b14b2009-08-28 05:49:21 +00006782 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006783
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006784 if (SS.isEmpty()) {
6785 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006786 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006787 }
Mike Stump1eb44332009-09-09 15:08:12 +00006788
John McCall9f54ad42009-12-10 09:41:52 +00006789 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006790 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006791 ForRedeclaration);
6792 Previous.setHideTags(false);
6793 if (S) {
6794 LookupName(Previous, S);
6795
6796 // It is really dumb that we have to do this.
6797 LookupResult::Filter F = Previous.makeFilter();
6798 while (F.hasNext()) {
6799 NamedDecl *D = F.next();
6800 if (!isDeclInScope(D, CurContext, S))
6801 F.erase();
6802 }
6803 F.done();
6804 } else {
6805 assert(IsInstantiation && "no scope in non-instantiation");
6806 assert(CurContext->isRecord() && "scope not record in instantiation");
6807 LookupQualifiedName(Previous, CurContext);
6808 }
6809
John McCall9f54ad42009-12-10 09:41:52 +00006810 // Check for invalid redeclarations.
6811 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6812 return 0;
6813
6814 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006815 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6816 return 0;
6817
John McCallaf8e6ed2009-11-12 03:15:40 +00006818 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006819 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006820 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006821 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006822 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006823 // FIXME: not all declaration name kinds are legal here
6824 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6825 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006826 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006827 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006828 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006829 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6830 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006831 }
John McCalled976492009-12-04 22:46:56 +00006832 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006833 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6834 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006835 }
John McCalled976492009-12-04 22:46:56 +00006836 D->setAccess(AS);
6837 CurContext->addDecl(D);
6838
6839 if (!LookupContext) return D;
6840 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006841
John McCall77bb1aa2010-05-01 00:40:08 +00006842 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006843 UD->setInvalidDecl();
6844 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006845 }
6846
Richard Smithc5a89a12012-04-02 01:30:27 +00006847 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006848 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006849 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006850 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006851 return UD;
6852 }
6853
6854 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006855
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006856 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006857
John McCall604e7f12009-12-08 07:46:18 +00006858 // Unlike most lookups, we don't always want to hide tag
6859 // declarations: tag names are visible through the using declaration
6860 // even if hidden by ordinary names, *except* in a dependent context
6861 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006862 if (!IsInstantiation)
6863 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006864
John McCallb9abd8722012-04-07 03:04:20 +00006865 // For the purposes of this lookup, we have a base object type
6866 // equal to that of the current context.
6867 if (CurContext->isRecord()) {
6868 R.setBaseObjectType(
6869 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6870 }
6871
John McCalla24dc2e2009-11-17 02:14:36 +00006872 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006873
John McCallf36e02d2009-10-09 21:13:30 +00006874 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006875 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006876 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006877 UD->setInvalidDecl();
6878 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006879 }
6880
John McCalled976492009-12-04 22:46:56 +00006881 if (R.isAmbiguous()) {
6882 UD->setInvalidDecl();
6883 return UD;
6884 }
Mike Stump1eb44332009-09-09 15:08:12 +00006885
John McCall7ba107a2009-11-18 02:36:19 +00006886 if (IsTypeName) {
6887 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006888 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006889 Diag(IdentLoc, diag::err_using_typename_non_type);
6890 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6891 Diag((*I)->getUnderlyingDecl()->getLocation(),
6892 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006893 UD->setInvalidDecl();
6894 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006895 }
6896 } else {
6897 // If we asked for a non-typename and we got a type, error out,
6898 // but only if this is an instantiation of an unresolved using
6899 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006900 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006901 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6902 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006903 UD->setInvalidDecl();
6904 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006905 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006906 }
6907
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006908 // C++0x N2914 [namespace.udecl]p6:
6909 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006910 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006911 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6912 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006913 UD->setInvalidDecl();
6914 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006915 }
Mike Stump1eb44332009-09-09 15:08:12 +00006916
John McCall9f54ad42009-12-10 09:41:52 +00006917 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6918 if (!CheckUsingShadowDecl(UD, *I, Previous))
6919 BuildUsingShadowDecl(S, UD, *I);
6920 }
John McCall9488ea12009-11-17 05:59:44 +00006921
6922 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006923}
6924
Sebastian Redlf677ea32011-02-05 19:23:19 +00006925/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006926bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6927 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006928
Douglas Gregordc355712011-02-25 00:36:19 +00006929 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006930 assert(SourceType &&
6931 "Using decl naming constructor doesn't have type in scope spec.");
6932 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6933
6934 // Check whether the named type is a direct base class.
6935 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6936 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6937 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6938 BaseIt != BaseE; ++BaseIt) {
6939 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6940 if (CanonicalSourceType == BaseType)
6941 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006942 if (BaseIt->getType()->isDependentType())
6943 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006944 }
6945
6946 if (BaseIt == BaseE) {
6947 // Did not find SourceType in the bases.
6948 Diag(UD->getUsingLocation(),
6949 diag::err_using_decl_constructor_not_in_direct_base)
6950 << UD->getNameInfo().getSourceRange()
6951 << QualType(SourceType, 0) << TargetClass;
6952 return true;
6953 }
6954
Richard Smithc5a89a12012-04-02 01:30:27 +00006955 if (!CurContext->isDependentContext())
6956 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006957
6958 return false;
6959}
6960
John McCall9f54ad42009-12-10 09:41:52 +00006961/// Checks that the given using declaration is not an invalid
6962/// redeclaration. Note that this is checking only for the using decl
6963/// itself, not for any ill-formedness among the UsingShadowDecls.
6964bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6965 bool isTypeName,
6966 const CXXScopeSpec &SS,
6967 SourceLocation NameLoc,
6968 const LookupResult &Prev) {
6969 // C++03 [namespace.udecl]p8:
6970 // C++0x [namespace.udecl]p10:
6971 // A using-declaration is a declaration and can therefore be used
6972 // repeatedly where (and only where) multiple declarations are
6973 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006974 //
John McCall8a726212010-11-29 18:01:58 +00006975 // That's in non-member contexts.
6976 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006977 return false;
6978
6979 NestedNameSpecifier *Qual
6980 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6981
6982 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6983 NamedDecl *D = *I;
6984
6985 bool DTypename;
6986 NestedNameSpecifier *DQual;
6987 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6988 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006989 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006990 } else if (UnresolvedUsingValueDecl *UD
6991 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6992 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006993 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006994 } else if (UnresolvedUsingTypenameDecl *UD
6995 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6996 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006997 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006998 } else continue;
6999
7000 // using decls differ if one says 'typename' and the other doesn't.
7001 // FIXME: non-dependent using decls?
7002 if (isTypeName != DTypename) continue;
7003
7004 // using decls differ if they name different scopes (but note that
7005 // template instantiation can cause this check to trigger when it
7006 // didn't before instantiation).
7007 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7008 Context.getCanonicalNestedNameSpecifier(DQual))
7009 continue;
7010
7011 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007012 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007013 return true;
7014 }
7015
7016 return false;
7017}
7018
John McCall604e7f12009-12-08 07:46:18 +00007019
John McCalled976492009-12-04 22:46:56 +00007020/// Checks that the given nested-name qualifier used in a using decl
7021/// in the current context is appropriately related to the current
7022/// scope. If an error is found, diagnoses it and returns true.
7023bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7024 const CXXScopeSpec &SS,
7025 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007026 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007027
John McCall604e7f12009-12-08 07:46:18 +00007028 if (!CurContext->isRecord()) {
7029 // C++03 [namespace.udecl]p3:
7030 // C++0x [namespace.udecl]p8:
7031 // A using-declaration for a class member shall be a member-declaration.
7032
7033 // If we weren't able to compute a valid scope, it must be a
7034 // dependent class scope.
7035 if (!NamedContext || NamedContext->isRecord()) {
7036 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7037 << SS.getRange();
7038 return true;
7039 }
7040
7041 // Otherwise, everything is known to be fine.
7042 return false;
7043 }
7044
7045 // The current scope is a record.
7046
7047 // If the named context is dependent, we can't decide much.
7048 if (!NamedContext) {
7049 // FIXME: in C++0x, we can diagnose if we can prove that the
7050 // nested-name-specifier does not refer to a base class, which is
7051 // still possible in some cases.
7052
7053 // Otherwise we have to conservatively report that things might be
7054 // okay.
7055 return false;
7056 }
7057
7058 if (!NamedContext->isRecord()) {
7059 // Ideally this would point at the last name in the specifier,
7060 // but we don't have that level of source info.
7061 Diag(SS.getRange().getBegin(),
7062 diag::err_using_decl_nested_name_specifier_is_not_class)
7063 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7064 return true;
7065 }
7066
Douglas Gregor6fb07292010-12-21 07:41:49 +00007067 if (!NamedContext->isDependentContext() &&
7068 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7069 return true;
7070
Richard Smith80ad52f2013-01-02 11:42:31 +00007071 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007072 // C++0x [namespace.udecl]p3:
7073 // In a using-declaration used as a member-declaration, the
7074 // nested-name-specifier shall name a base class of the class
7075 // being defined.
7076
7077 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7078 cast<CXXRecordDecl>(NamedContext))) {
7079 if (CurContext == NamedContext) {
7080 Diag(NameLoc,
7081 diag::err_using_decl_nested_name_specifier_is_current_class)
7082 << SS.getRange();
7083 return true;
7084 }
7085
7086 Diag(SS.getRange().getBegin(),
7087 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7088 << (NestedNameSpecifier*) SS.getScopeRep()
7089 << cast<CXXRecordDecl>(CurContext)
7090 << SS.getRange();
7091 return true;
7092 }
7093
7094 return false;
7095 }
7096
7097 // C++03 [namespace.udecl]p4:
7098 // A using-declaration used as a member-declaration shall refer
7099 // to a member of a base class of the class being defined [etc.].
7100
7101 // Salient point: SS doesn't have to name a base class as long as
7102 // lookup only finds members from base classes. Therefore we can
7103 // diagnose here only if we can prove that that can't happen,
7104 // i.e. if the class hierarchies provably don't intersect.
7105
7106 // TODO: it would be nice if "definitely valid" results were cached
7107 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7108 // need to be repeated.
7109
7110 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007111 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007112
7113 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7114 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7115 Data->Bases.insert(Base);
7116 return true;
7117 }
7118
7119 bool hasDependentBases(const CXXRecordDecl *Class) {
7120 return !Class->forallBases(collect, this);
7121 }
7122
7123 /// Returns true if the base is dependent or is one of the
7124 /// accumulated base classes.
7125 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7126 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7127 return !Data->Bases.count(Base);
7128 }
7129
7130 bool mightShareBases(const CXXRecordDecl *Class) {
7131 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7132 }
7133 };
7134
7135 UserData Data;
7136
7137 // Returns false if we find a dependent base.
7138 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7139 return false;
7140
7141 // Returns false if the class has a dependent base or if it or one
7142 // of its bases is present in the base set of the current context.
7143 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7144 return false;
7145
7146 Diag(SS.getRange().getBegin(),
7147 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7148 << (NestedNameSpecifier*) SS.getScopeRep()
7149 << cast<CXXRecordDecl>(CurContext)
7150 << SS.getRange();
7151
7152 return true;
John McCalled976492009-12-04 22:46:56 +00007153}
7154
Richard Smith162e1c12011-04-15 14:24:37 +00007155Decl *Sema::ActOnAliasDeclaration(Scope *S,
7156 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007157 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007158 SourceLocation UsingLoc,
7159 UnqualifiedId &Name,
7160 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007161 // Skip up to the relevant declaration scope.
7162 while (S->getFlags() & Scope::TemplateParamScope)
7163 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007164 assert((S->getFlags() & Scope::DeclScope) &&
7165 "got alias-declaration outside of declaration scope");
7166
7167 if (Type.isInvalid())
7168 return 0;
7169
7170 bool Invalid = false;
7171 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7172 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007173 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007174
7175 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7176 return 0;
7177
7178 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007179 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007180 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007181 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7182 TInfo->getTypeLoc().getBeginLoc());
7183 }
Richard Smith162e1c12011-04-15 14:24:37 +00007184
7185 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7186 LookupName(Previous, S);
7187
7188 // Warn about shadowing the name of a template parameter.
7189 if (Previous.isSingleResult() &&
7190 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007191 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007192 Previous.clear();
7193 }
7194
7195 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7196 "name in alias declaration must be an identifier");
7197 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7198 Name.StartLocation,
7199 Name.Identifier, TInfo);
7200
7201 NewTD->setAccess(AS);
7202
7203 if (Invalid)
7204 NewTD->setInvalidDecl();
7205
Richard Smith3e4c6c42011-05-05 21:57:07 +00007206 CheckTypedefForVariablyModifiedType(S, NewTD);
7207 Invalid |= NewTD->isInvalidDecl();
7208
Richard Smith162e1c12011-04-15 14:24:37 +00007209 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007210
7211 NamedDecl *NewND;
7212 if (TemplateParamLists.size()) {
7213 TypeAliasTemplateDecl *OldDecl = 0;
7214 TemplateParameterList *OldTemplateParams = 0;
7215
7216 if (TemplateParamLists.size() != 1) {
7217 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007218 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7219 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007220 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007221 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007222
7223 // Only consider previous declarations in the same scope.
7224 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7225 /*ExplicitInstantiationOrSpecialization*/false);
7226 if (!Previous.empty()) {
7227 Redeclaration = true;
7228
7229 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7230 if (!OldDecl && !Invalid) {
7231 Diag(UsingLoc, diag::err_redefinition_different_kind)
7232 << Name.Identifier;
7233
7234 NamedDecl *OldD = Previous.getRepresentativeDecl();
7235 if (OldD->getLocation().isValid())
7236 Diag(OldD->getLocation(), diag::note_previous_definition);
7237
7238 Invalid = true;
7239 }
7240
7241 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7242 if (TemplateParameterListsAreEqual(TemplateParams,
7243 OldDecl->getTemplateParameters(),
7244 /*Complain=*/true,
7245 TPL_TemplateMatch))
7246 OldTemplateParams = OldDecl->getTemplateParameters();
7247 else
7248 Invalid = true;
7249
7250 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7251 if (!Invalid &&
7252 !Context.hasSameType(OldTD->getUnderlyingType(),
7253 NewTD->getUnderlyingType())) {
7254 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7255 // but we can't reasonably accept it.
7256 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7257 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7258 if (OldTD->getLocation().isValid())
7259 Diag(OldTD->getLocation(), diag::note_previous_definition);
7260 Invalid = true;
7261 }
7262 }
7263 }
7264
7265 // Merge any previous default template arguments into our parameters,
7266 // and check the parameter list.
7267 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7268 TPC_TypeAliasTemplate))
7269 return 0;
7270
7271 TypeAliasTemplateDecl *NewDecl =
7272 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7273 Name.Identifier, TemplateParams,
7274 NewTD);
7275
7276 NewDecl->setAccess(AS);
7277
7278 if (Invalid)
7279 NewDecl->setInvalidDecl();
7280 else if (OldDecl)
7281 NewDecl->setPreviousDeclaration(OldDecl);
7282
7283 NewND = NewDecl;
7284 } else {
7285 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7286 NewND = NewTD;
7287 }
Richard Smith162e1c12011-04-15 14:24:37 +00007288
7289 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007290 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007291
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007292 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007293 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007294}
7295
John McCalld226f652010-08-21 09:40:31 +00007296Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007297 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007298 SourceLocation AliasLoc,
7299 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007300 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007301 SourceLocation IdentLoc,
7302 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007303
Anders Carlsson81c85c42009-03-28 23:53:49 +00007304 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007305 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7306 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007307
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007308 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007309 NamedDecl *PrevDecl
7310 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7311 ForRedeclaration);
7312 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7313 PrevDecl = 0;
7314
7315 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007316 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007317 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007318 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007319 // FIXME: At some point, we'll want to create the (redundant)
7320 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007321 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007322 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007323 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007324 }
Mike Stump1eb44332009-09-09 15:08:12 +00007325
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007326 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7327 diag::err_redefinition_different_kind;
7328 Diag(AliasLoc, DiagID) << Alias;
7329 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007330 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007331 }
7332
John McCalla24dc2e2009-11-17 02:14:36 +00007333 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007334 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007335
John McCallf36e02d2009-10-09 21:13:30 +00007336 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007337 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007338 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007339 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007340 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007341 }
Mike Stump1eb44332009-09-09 15:08:12 +00007342
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007343 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007344 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007345 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007346 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007347
John McCall3dbd3d52010-02-16 06:53:13 +00007348 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007349 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007350}
7351
Sean Hunt001cad92011-05-10 00:49:42 +00007352Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007353Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7354 CXXMethodDecl *MD) {
7355 CXXRecordDecl *ClassDecl = MD->getParent();
7356
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007357 // C++ [except.spec]p14:
7358 // An implicitly declared special member function (Clause 12) shall have an
7359 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007360 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007361 if (ClassDecl->isInvalidDecl())
7362 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007363
Sebastian Redl60618fa2011-03-12 11:50:43 +00007364 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007365 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7366 BEnd = ClassDecl->bases_end();
7367 B != BEnd; ++B) {
7368 if (B->isVirtual()) // Handled below.
7369 continue;
7370
Douglas Gregor18274032010-07-03 00:47:00 +00007371 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7372 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007373 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7374 // If this is a deleted function, add it anyway. This might be conformant
7375 // with the standard. This might not. I'm not sure. It might not matter.
7376 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007377 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007378 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007379 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007380
7381 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007382 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7383 BEnd = ClassDecl->vbases_end();
7384 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007385 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7386 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007387 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7388 // If this is a deleted function, add it anyway. This might be conformant
7389 // with the standard. This might not. I'm not sure. It might not matter.
7390 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007391 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007392 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007393 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007394
7395 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007396 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7397 FEnd = ClassDecl->field_end();
7398 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007399 if (F->hasInClassInitializer()) {
7400 if (Expr *E = F->getInClassInitializer())
7401 ExceptSpec.CalledExpr(E);
7402 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007403 // DR1351:
7404 // If the brace-or-equal-initializer of a non-static data member
7405 // invokes a defaulted default constructor of its class or of an
7406 // enclosing class in a potentially evaluated subexpression, the
7407 // program is ill-formed.
7408 //
7409 // This resolution is unworkable: the exception specification of the
7410 // default constructor can be needed in an unevaluated context, in
7411 // particular, in the operand of a noexcept-expression, and we can be
7412 // unable to compute an exception specification for an enclosed class.
7413 //
7414 // We do not allow an in-class initializer to require the evaluation
7415 // of the exception specification for any in-class initializer whose
7416 // definition is not lexically complete.
7417 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007418 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007419 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007420 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7421 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7422 // If this is a deleted function, add it anyway. This might be conformant
7423 // with the standard. This might not. I'm not sure. It might not matter.
7424 // In particular, the problem is that this function never gets called. It
7425 // might just be ill-formed because this function attempts to refer to
7426 // a deleted function here.
7427 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007428 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007429 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007430 }
John McCalle23cf432010-12-14 08:05:40 +00007431
Sean Hunt001cad92011-05-10 00:49:42 +00007432 return ExceptSpec;
7433}
7434
Richard Smithafb49182012-11-29 01:34:07 +00007435namespace {
7436/// RAII object to register a special member as being currently declared.
7437struct DeclaringSpecialMember {
7438 Sema &S;
7439 Sema::SpecialMemberDecl D;
7440 bool WasAlreadyBeingDeclared;
7441
7442 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7443 : S(S), D(RD, CSM) {
7444 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7445 if (WasAlreadyBeingDeclared)
7446 // This almost never happens, but if it does, ensure that our cache
7447 // doesn't contain a stale result.
7448 S.SpecialMemberCache.clear();
7449
7450 // FIXME: Register a note to be produced if we encounter an error while
7451 // declaring the special member.
7452 }
7453 ~DeclaringSpecialMember() {
7454 if (!WasAlreadyBeingDeclared)
7455 S.SpecialMembersBeingDeclared.erase(D);
7456 }
7457
7458 /// \brief Are we already trying to declare this special member?
7459 bool isAlreadyBeingDeclared() const {
7460 return WasAlreadyBeingDeclared;
7461 }
7462};
7463}
7464
Sean Hunt001cad92011-05-10 00:49:42 +00007465CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7466 CXXRecordDecl *ClassDecl) {
7467 // C++ [class.ctor]p5:
7468 // A default constructor for a class X is a constructor of class X
7469 // that can be called without an argument. If there is no
7470 // user-declared constructor for class X, a default constructor is
7471 // implicitly declared. An implicitly-declared default constructor
7472 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007473 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007474 "Should not build implicit default constructor!");
7475
Richard Smithafb49182012-11-29 01:34:07 +00007476 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7477 if (DSM.isAlreadyBeingDeclared())
7478 return 0;
7479
Richard Smith7756afa2012-06-10 05:43:50 +00007480 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7481 CXXDefaultConstructor,
7482 false);
7483
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007484 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007485 CanQualType ClassType
7486 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007487 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007488 DeclarationName Name
7489 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007490 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007491 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007492 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007493 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007494 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007495 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007496 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007497 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007498
7499 // Build an exception specification pointing back at this constructor.
7500 FunctionProtoType::ExtProtoInfo EPI;
7501 EPI.ExceptionSpecType = EST_Unevaluated;
7502 EPI.ExceptionSpecDecl = DefaultCon;
7503 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7504
Richard Smithbc2a35d2012-12-08 08:32:28 +00007505 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7506 // constructors is easy to compute.
7507 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7508
7509 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7510 DefaultCon->setDeletedAsWritten();
7511
Douglas Gregor18274032010-07-03 00:47:00 +00007512 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007513 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007514
Douglas Gregor23c94db2010-07-02 17:43:08 +00007515 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007516 PushOnScopeChains(DefaultCon, S, false);
7517 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007518
Douglas Gregor32df23e2010-07-01 22:02:46 +00007519 return DefaultCon;
7520}
7521
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007522void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7523 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007524 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007525 !Constructor->doesThisDeclarationHaveABody() &&
7526 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007527 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007528
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007529 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007530 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007531
Eli Friedman9a14db32012-10-18 20:14:08 +00007532 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007533 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007534 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007535 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007536 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007537 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007538 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007539 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007540 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007541
7542 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007543 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007544
7545 Constructor->setUsed();
7546 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007547
7548 if (ASTMutationListener *L = getASTMutationListener()) {
7549 L->CompletedImplicitDefinition(Constructor);
7550 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007551}
7552
Richard Smith7a614d82011-06-11 17:19:42 +00007553void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007554 // Check that any explicitly-defaulted methods have exception specifications
7555 // compatible with their implicit exception specifications.
7556 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007557}
7558
Sebastian Redlf677ea32011-02-05 19:23:19 +00007559void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7560 // We start with an initial pass over the base classes to collect those that
7561 // inherit constructors from. If there are none, we can forgo all further
7562 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007563 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007564 BasesVector BasesToInheritFrom;
7565 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7566 BaseE = ClassDecl->bases_end();
7567 BaseIt != BaseE; ++BaseIt) {
7568 if (BaseIt->getInheritConstructors()) {
7569 QualType Base = BaseIt->getType();
7570 if (Base->isDependentType()) {
7571 // If we inherit constructors from anything that is dependent, just
7572 // abort processing altogether. We'll get another chance for the
7573 // instantiations.
7574 return;
7575 }
7576 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7577 }
7578 }
7579 if (BasesToInheritFrom.empty())
7580 return;
7581
7582 // Now collect the constructors that we already have in the current class.
7583 // Those take precedence over inherited constructors.
7584 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7585 // unless there is a user-declared constructor with the same signature in
7586 // the class where the using-declaration appears.
7587 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7588 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7589 CtorE = ClassDecl->ctor_end();
7590 CtorIt != CtorE; ++CtorIt) {
7591 ExistingConstructors.insert(
7592 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7593 }
7594
Sebastian Redlf677ea32011-02-05 19:23:19 +00007595 DeclarationName CreatedCtorName =
7596 Context.DeclarationNames.getCXXConstructorName(
7597 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7598
7599 // Now comes the true work.
7600 // First, we keep a map from constructor types to the base that introduced
7601 // them. Needed for finding conflicting constructors. We also keep the
7602 // actually inserted declarations in there, for pretty diagnostics.
7603 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7604 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7605 ConstructorToSourceMap InheritedConstructors;
7606 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7607 BaseE = BasesToInheritFrom.end();
7608 BaseIt != BaseE; ++BaseIt) {
7609 const RecordType *Base = *BaseIt;
7610 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7611 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7612 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7613 CtorE = BaseDecl->ctor_end();
7614 CtorIt != CtorE; ++CtorIt) {
7615 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007616 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007617 DeclarationName Name =
7618 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007619 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7620 LookupQualifiedName(Result, CurContext);
7621 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007622 SourceLocation UsingLoc = UD ? UD->getLocation() :
7623 ClassDecl->getLocation();
7624
7625 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7626 // from the class X named in the using-declaration consists of actual
7627 // constructors and notional constructors that result from the
7628 // transformation of defaulted parameters as follows:
7629 // - all non-template default constructors of X, and
7630 // - for each non-template constructor of X that has at least one
7631 // parameter with a default argument, the set of constructors that
7632 // results from omitting any ellipsis parameter specification and
7633 // successively omitting parameters with a default argument from the
7634 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00007635 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007636 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7637 const FunctionProtoType *BaseCtorType =
7638 BaseCtor->getType()->getAs<FunctionProtoType>();
7639
7640 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7641 maxParams = BaseCtor->getNumParams();
7642 params <= maxParams; ++params) {
7643 // Skip default constructors. They're never inherited.
7644 if (params == 0)
7645 continue;
7646 // Skip copy and move constructors for the same reason.
7647 if (CanBeCopyOrMove && params == 1)
7648 continue;
7649
7650 // Build up a function type for this particular constructor.
7651 // FIXME: The working paper does not consider that the exception spec
7652 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007653 // source. This code doesn't yet, either. When it does, this code will
7654 // need to be delayed until after exception specifications and in-class
7655 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007656 const Type *NewCtorType;
7657 if (params == maxParams)
7658 NewCtorType = BaseCtorType;
7659 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007660 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007661 for (unsigned i = 0; i < params; ++i) {
7662 Args.push_back(BaseCtorType->getArgType(i));
7663 }
7664 FunctionProtoType::ExtProtoInfo ExtInfo =
7665 BaseCtorType->getExtProtoInfo();
7666 ExtInfo.Variadic = false;
7667 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7668 Args.data(), params, ExtInfo)
7669 .getTypePtr();
7670 }
7671 const Type *CanonicalNewCtorType =
7672 Context.getCanonicalType(NewCtorType);
7673
7674 // Now that we have the type, first check if the class already has a
7675 // constructor with this signature.
7676 if (ExistingConstructors.count(CanonicalNewCtorType))
7677 continue;
7678
7679 // Then we check if we have already declared an inherited constructor
7680 // with this signature.
7681 std::pair<ConstructorToSourceMap::iterator, bool> result =
7682 InheritedConstructors.insert(std::make_pair(
7683 CanonicalNewCtorType,
7684 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7685 if (!result.second) {
7686 // Already in the map. If it came from a different class, that's an
7687 // error. Not if it's from the same.
7688 CanQualType PreviousBase = result.first->second.first;
7689 if (CanonicalBase != PreviousBase) {
7690 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7691 const CXXConstructorDecl *PrevBaseCtor =
7692 PrevCtor->getInheritedConstructor();
7693 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7694
7695 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7696 Diag(BaseCtor->getLocation(),
7697 diag::note_using_decl_constructor_conflict_current_ctor);
7698 Diag(PrevBaseCtor->getLocation(),
7699 diag::note_using_decl_constructor_conflict_previous_ctor);
7700 Diag(PrevCtor->getLocation(),
7701 diag::note_using_decl_constructor_conflict_previous_using);
7702 }
7703 continue;
7704 }
7705
7706 // OK, we're there, now add the constructor.
7707 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007708 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007709 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7710 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007711 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7712 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007713 /*ImplicitlyDeclared=*/true,
7714 // FIXME: Due to a defect in the standard, we treat inherited
7715 // constructors as constexpr even if that makes them ill-formed.
7716 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007717 NewCtor->setAccess(BaseCtor->getAccess());
7718
7719 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007720 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007721 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007722 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7723 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007724 /*IdentifierInfo=*/0,
7725 BaseCtorType->getArgType(i),
7726 /*TInfo=*/0, SC_None,
7727 SC_None, /*DefaultArg=*/0));
7728 }
David Blaikie4278c652011-09-21 18:16:56 +00007729 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007730 NewCtor->setInheritedConstructor(BaseCtor);
7731
Sebastian Redlf677ea32011-02-05 19:23:19 +00007732 ClassDecl->addDecl(NewCtor);
7733 result.first->second.second = NewCtor;
7734 }
7735 }
7736 }
7737}
7738
Sean Huntcb45a0f2011-05-12 22:46:25 +00007739Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007740Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7741 CXXRecordDecl *ClassDecl = MD->getParent();
7742
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007743 // C++ [except.spec]p14:
7744 // An implicitly declared special member function (Clause 12) shall have
7745 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007746 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007747 if (ClassDecl->isInvalidDecl())
7748 return ExceptSpec;
7749
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007750 // Direct base-class destructors.
7751 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7752 BEnd = ClassDecl->bases_end();
7753 B != BEnd; ++B) {
7754 if (B->isVirtual()) // Handled below.
7755 continue;
7756
7757 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007758 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007759 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007760 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007761
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007762 // Virtual base-class destructors.
7763 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7764 BEnd = ClassDecl->vbases_end();
7765 B != BEnd; ++B) {
7766 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007767 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007768 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007769 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007770
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007771 // Field destructors.
7772 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7773 FEnd = ClassDecl->field_end();
7774 F != FEnd; ++F) {
7775 if (const RecordType *RecordTy
7776 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007777 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007778 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007779 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007780
Sean Huntcb45a0f2011-05-12 22:46:25 +00007781 return ExceptSpec;
7782}
7783
7784CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7785 // C++ [class.dtor]p2:
7786 // If a class has no user-declared destructor, a destructor is
7787 // declared implicitly. An implicitly-declared destructor is an
7788 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007789 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007790
Richard Smithafb49182012-11-29 01:34:07 +00007791 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7792 if (DSM.isAlreadyBeingDeclared())
7793 return 0;
7794
Douglas Gregor4923aa22010-07-02 20:37:36 +00007795 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007796 CanQualType ClassType
7797 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007798 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007799 DeclarationName Name
7800 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007801 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007802 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007803 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7804 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007805 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007806 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007807 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007808 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007809
7810 // Build an exception specification pointing back at this destructor.
7811 FunctionProtoType::ExtProtoInfo EPI;
7812 EPI.ExceptionSpecType = EST_Unevaluated;
7813 EPI.ExceptionSpecDecl = Destructor;
7814 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7815
Richard Smithbc2a35d2012-12-08 08:32:28 +00007816 AddOverriddenMethods(ClassDecl, Destructor);
7817
7818 // We don't need to use SpecialMemberIsTrivial here; triviality for
7819 // destructors is easy to compute.
7820 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7821
7822 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7823 Destructor->setDeletedAsWritten();
7824
Douglas Gregor4923aa22010-07-02 20:37:36 +00007825 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007826 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007827
Douglas Gregor4923aa22010-07-02 20:37:36 +00007828 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007829 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007830 PushOnScopeChains(Destructor, S, false);
7831 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007832
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007833 return Destructor;
7834}
7835
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007836void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007837 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007838 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007839 !Destructor->doesThisDeclarationHaveABody() &&
7840 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007841 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007842 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007843 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007844
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007845 if (Destructor->isInvalidDecl())
7846 return;
7847
Eli Friedman9a14db32012-10-18 20:14:08 +00007848 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007849
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007850 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007851 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7852 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007853
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007854 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007855 Diag(CurrentLocation, diag::note_member_synthesized_at)
7856 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7857
7858 Destructor->setInvalidDecl();
7859 return;
7860 }
7861
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007862 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007863 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007864 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007865 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007866 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007867
7868 if (ASTMutationListener *L = getASTMutationListener()) {
7869 L->CompletedImplicitDefinition(Destructor);
7870 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007871}
7872
Richard Smitha4156b82012-04-21 18:42:51 +00007873/// \brief Perform any semantic analysis which needs to be delayed until all
7874/// pending class member declarations have been parsed.
7875void Sema::ActOnFinishCXXMemberDecls() {
Richard Smitha4156b82012-04-21 18:42:51 +00007876 // Perform any deferred checking of exception specifications for virtual
7877 // destructors.
7878 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7879 i != e; ++i) {
7880 const CXXDestructorDecl *Dtor =
7881 DelayedDestructorExceptionSpecChecks[i].first;
7882 assert(!Dtor->getParent()->isDependentType() &&
7883 "Should not ever add destructors of templates into the list.");
7884 CheckOverridingFunctionExceptionSpec(Dtor,
7885 DelayedDestructorExceptionSpecChecks[i].second);
7886 }
7887 DelayedDestructorExceptionSpecChecks.clear();
7888}
7889
Richard Smithb9d0b762012-07-27 04:22:15 +00007890void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7891 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00007892 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00007893 "adjusting dtor exception specs was introduced in c++11");
7894
Sebastian Redl0ee33912011-05-19 05:13:44 +00007895 // C++11 [class.dtor]p3:
7896 // A declaration of a destructor that does not have an exception-
7897 // specification is implicitly considered to have the same exception-
7898 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007899 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007900 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007901 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007902 return;
7903
Chandler Carruth3f224b22011-09-20 04:55:26 +00007904 // Replace the destructor's type, building off the existing one. Fortunately,
7905 // the only thing of interest in the destructor type is its extended info.
7906 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007907 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7908 EPI.ExceptionSpecType = EST_Unevaluated;
7909 EPI.ExceptionSpecDecl = Destructor;
7910 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007911
Sebastian Redl0ee33912011-05-19 05:13:44 +00007912 // FIXME: If the destructor has a body that could throw, and the newly created
7913 // spec doesn't allow exceptions, we should emit a warning, because this
7914 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007915 // However, we don't have a body or an exception specification yet, so it
7916 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007917}
7918
Richard Smith8c889532012-11-14 00:50:40 +00007919/// When generating a defaulted copy or move assignment operator, if a field
7920/// should be copied with __builtin_memcpy rather than via explicit assignments,
7921/// do so. This optimization only applies for arrays of scalars, and for arrays
7922/// of class type where the selected copy/move-assignment operator is trivial.
7923static StmtResult
7924buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7925 Expr *To, Expr *From) {
7926 // Compute the size of the memory buffer to be copied.
7927 QualType SizeType = S.Context.getSizeType();
7928 llvm::APInt Size(S.Context.getTypeSize(SizeType),
7929 S.Context.getTypeSizeInChars(T).getQuantity());
7930
7931 // Take the address of the field references for "from" and "to". We
7932 // directly construct UnaryOperators here because semantic analysis
7933 // does not permit us to take the address of an xvalue.
7934 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7935 S.Context.getPointerType(From->getType()),
7936 VK_RValue, OK_Ordinary, Loc);
7937 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7938 S.Context.getPointerType(To->getType()),
7939 VK_RValue, OK_Ordinary, Loc);
7940
7941 const Type *E = T->getBaseElementTypeUnsafe();
7942 bool NeedsCollectableMemCpy =
7943 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7944
7945 // Create a reference to the __builtin_objc_memmove_collectable function
7946 StringRef MemCpyName = NeedsCollectableMemCpy ?
7947 "__builtin_objc_memmove_collectable" :
7948 "__builtin_memcpy";
7949 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
7950 Sema::LookupOrdinaryName);
7951 S.LookupName(R, S.TUScope, true);
7952
7953 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
7954 if (!MemCpy)
7955 // Something went horribly wrong earlier, and we will have complained
7956 // about it.
7957 return StmtError();
7958
7959 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
7960 VK_RValue, Loc, 0);
7961 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
7962
7963 Expr *CallArgs[] = {
7964 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
7965 };
7966 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
7967 Loc, CallArgs, Loc);
7968
7969 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7970 return S.Owned(Call.takeAs<Stmt>());
7971}
7972
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007973/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007974/// \c To.
7975///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007976/// This routine is used to copy/move the members of a class with an
7977/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007978/// copied are arrays, this routine builds for loops to copy them.
7979///
7980/// \param S The Sema object used for type-checking.
7981///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007982/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007983///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007984/// \param T The type of the expressions being copied/moved. Both expressions
7985/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007986///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007987/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007988///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007989/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007990///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007991/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007992/// Otherwise, it's a non-static member subobject.
7993///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007994/// \param Copying Whether we're copying or moving.
7995///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007996/// \param Depth Internal parameter recording the depth of the recursion.
7997///
Richard Smith8c889532012-11-14 00:50:40 +00007998/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
7999/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008000static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008001buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8002 Expr *To, Expr *From,
8003 bool CopyingBaseSubobject, bool Copying,
8004 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008005 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008006 // Each subobject is assigned in the manner appropriate to its type:
8007 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008008 // - if the subobject is of class type, as if by a call to operator= with
8009 // the subobject as the object expression and the corresponding
8010 // subobject of x as a single function argument (as if by explicit
8011 // qualification; that is, ignoring any possible virtual overriding
8012 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008013 //
8014 // C++03 [class.copy]p13:
8015 // - if the subobject is of class type, the copy assignment operator for
8016 // the class is used (as if by explicit qualification; that is,
8017 // ignoring any possible virtual overriding functions in more derived
8018 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008019 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8020 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008021
Douglas Gregor06a9f362010-05-01 20:49:11 +00008022 // Look for operator=.
8023 DeclarationName Name
8024 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8025 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8026 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008027
Richard Smith044c8aa2012-11-13 00:54:12 +00008028 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8029 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008030 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008031 LookupResult::Filter F = OpLookup.makeFilter();
8032 while (F.hasNext()) {
8033 NamedDecl *D = F.next();
8034 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8035 if (Method->isCopyAssignmentOperator() ||
8036 (!Copying && Method->isMoveAssignmentOperator()))
8037 continue;
8038
8039 F.erase();
8040 }
8041 F.done();
John McCallb0207482010-03-16 06:11:48 +00008042 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008043
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008044 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008045 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008046 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008047 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008048 // ambiguities), we need to cast "this" to that subobject type; to
8049 // ensure that we don't go through the virtual call mechanism, we need
8050 // to qualify the operator= name with the base class (see below). However,
8051 // this means that if the base class has a protected copy assignment
8052 // operator, the protected member access check will fail. So, we
8053 // rewrite "protected" access to "public" access in this case, since we
8054 // know by construction that we're calling from a derived class.
8055 if (CopyingBaseSubobject) {
8056 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8057 L != LEnd; ++L) {
8058 if (L.getAccess() == AS_protected)
8059 L.setAccess(AS_public);
8060 }
8061 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008062
Douglas Gregor06a9f362010-05-01 20:49:11 +00008063 // Create the nested-name-specifier that will be used to qualify the
8064 // reference to operator=; this is required to suppress the virtual
8065 // call mechanism.
8066 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008067 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008068 SS.MakeTrivial(S.Context,
8069 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008070 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008071 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008072
Douglas Gregor06a9f362010-05-01 20:49:11 +00008073 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008074 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008075 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008076 /*TemplateKWLoc=*/SourceLocation(),
8077 /*FirstQualifierInScope=*/0,
8078 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008079 /*TemplateArgs=*/0,
8080 /*SuppressQualifierCheck=*/true);
8081 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008082 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008083
Douglas Gregor06a9f362010-05-01 20:49:11 +00008084 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008085
Richard Smith044c8aa2012-11-13 00:54:12 +00008086 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008087 OpEqualRef.takeAs<Expr>(),
8088 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008089 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008090 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008091
Richard Smith8c889532012-11-14 00:50:40 +00008092 // If we built a call to a trivial 'operator=' while copying an array,
8093 // bail out. We'll replace the whole shebang with a memcpy.
8094 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8095 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8096 return StmtResult((Stmt*)0);
8097
Richard Smith044c8aa2012-11-13 00:54:12 +00008098 // Convert to an expression-statement, and clean up any produced
8099 // temporaries.
8100 return S.ActOnExprStmt(S.MakeFullExpr(Call.take(), Loc));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008101 }
John McCallb0207482010-03-16 06:11:48 +00008102
Richard Smith044c8aa2012-11-13 00:54:12 +00008103 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008104 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008105 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008106 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008107 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008108 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008109 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008110 return S.ActOnExprStmt(S.MakeFullExpr(Assignment.take(), Loc));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008111 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008112
8113 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008114 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008115
Douglas Gregor06a9f362010-05-01 20:49:11 +00008116 // Construct a loop over the array bounds, e.g.,
8117 //
8118 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8119 //
8120 // that will copy each of the array elements.
8121 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008122
Douglas Gregor06a9f362010-05-01 20:49:11 +00008123 // Create the iteration variable.
8124 IdentifierInfo *IterationVarName = 0;
8125 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008126 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008127 llvm::raw_svector_ostream OS(Str);
8128 OS << "__i" << Depth;
8129 IterationVarName = &S.Context.Idents.get(OS.str());
8130 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008131 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008132 IterationVarName, SizeType,
8133 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00008134 SC_None, SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008135
Douglas Gregor06a9f362010-05-01 20:49:11 +00008136 // Initialize the iteration variable to zero.
8137 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008138 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008139
8140 // Create a reference to the iteration variable; we'll use this several
8141 // times throughout.
8142 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008143 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008144 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008145 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8146 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8147
Douglas Gregor06a9f362010-05-01 20:49:11 +00008148 // Create the DeclStmt that holds the iteration variable.
8149 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008150
Douglas Gregor06a9f362010-05-01 20:49:11 +00008151 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008152 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008153 IterationVarRefRVal,
8154 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008155 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008156 IterationVarRefRVal,
8157 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008158 if (!Copying) // Cast to rvalue
8159 From = CastForMoving(S, From);
8160
8161 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008162 StmtResult Copy =
8163 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8164 To, From, CopyingBaseSubobject,
8165 Copying, Depth + 1);
8166 // Bail out if copying fails or if we determined that we should use memcpy.
8167 if (Copy.isInvalid() || !Copy.get())
8168 return Copy;
8169
8170 // Create the comparison against the array bound.
8171 llvm::APInt Upper
8172 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8173 Expr *Comparison
8174 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8175 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8176 BO_NE, S.Context.BoolTy,
8177 VK_RValue, OK_Ordinary, Loc, false);
8178
8179 // Create the pre-increment of the iteration variable.
8180 Expr *Increment
8181 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8182 VK_LValue, OK_Ordinary, Loc);
8183
Douglas Gregor06a9f362010-05-01 20:49:11 +00008184 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008185 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008186 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00008187 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008188 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008189}
8190
Richard Smith8c889532012-11-14 00:50:40 +00008191static StmtResult
8192buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8193 Expr *To, Expr *From,
8194 bool CopyingBaseSubobject, bool Copying) {
8195 // Maybe we should use a memcpy?
8196 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8197 T.isTriviallyCopyableType(S.Context))
8198 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8199
8200 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8201 CopyingBaseSubobject,
8202 Copying, 0));
8203
8204 // If we ended up picking a trivial assignment operator for an array of a
8205 // non-trivially-copyable class type, just emit a memcpy.
8206 if (!Result.isInvalid() && !Result.get())
8207 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8208
8209 return Result;
8210}
8211
Richard Smithb9d0b762012-07-27 04:22:15 +00008212Sema::ImplicitExceptionSpecification
8213Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8214 CXXRecordDecl *ClassDecl = MD->getParent();
8215
8216 ImplicitExceptionSpecification ExceptSpec(*this);
8217 if (ClassDecl->isInvalidDecl())
8218 return ExceptSpec;
8219
8220 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8221 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8222 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8223
Douglas Gregorb87786f2010-07-01 17:48:08 +00008224 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008225 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008226 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008227
8228 // It is unspecified whether or not an implicit copy assignment operator
8229 // attempts to deduplicate calls to assignment operators of virtual bases are
8230 // made. As such, this exception specification is effectively unspecified.
8231 // Based on a similar decision made for constness in C++0x, we're erring on
8232 // the side of assuming such calls to be made regardless of whether they
8233 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008234 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8235 BaseEnd = ClassDecl->bases_end();
8236 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008237 if (Base->isVirtual())
8238 continue;
8239
Douglas Gregora376d102010-07-02 21:50:04 +00008240 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008241 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008242 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8243 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008244 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008245 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008246
8247 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8248 BaseEnd = ClassDecl->vbases_end();
8249 Base != BaseEnd; ++Base) {
8250 CXXRecordDecl *BaseClassDecl
8251 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8252 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8253 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008254 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008255 }
8256
Douglas Gregorb87786f2010-07-01 17:48:08 +00008257 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8258 FieldEnd = ClassDecl->field_end();
8259 Field != FieldEnd;
8260 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008261 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008262 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8263 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008264 LookupCopyingAssignment(FieldClassDecl,
8265 ArgQuals | FieldType.getCVRQualifiers(),
8266 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008267 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008268 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008269 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008270
Richard Smithb9d0b762012-07-27 04:22:15 +00008271 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008272}
8273
8274CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8275 // Note: The following rules are largely analoguous to the copy
8276 // constructor rules. Note that virtual bases are not taken into account
8277 // for determining the argument type of the operator. Note also that
8278 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008279 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008280
Richard Smithafb49182012-11-29 01:34:07 +00008281 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8282 if (DSM.isAlreadyBeingDeclared())
8283 return 0;
8284
Sean Hunt30de05c2011-05-14 05:23:20 +00008285 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8286 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008287 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008288 ArgType = ArgType.withConst();
8289 ArgType = Context.getLValueReferenceType(ArgType);
8290
Douglas Gregord3c35902010-07-01 16:36:15 +00008291 // An implicitly-declared copy assignment operator is an inline public
8292 // member of its class.
8293 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008294 SourceLocation ClassLoc = ClassDecl->getLocation();
8295 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008296 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008297 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00008298 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00008299 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008300 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008301 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008302 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008303 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008304 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008305
8306 // Build an exception specification pointing back at this member.
8307 FunctionProtoType::ExtProtoInfo EPI;
8308 EPI.ExceptionSpecType = EST_Unevaluated;
8309 EPI.ExceptionSpecDecl = CopyAssignment;
8310 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8311
Douglas Gregord3c35902010-07-01 16:36:15 +00008312 // Add the parameter to the operator.
8313 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008314 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008315 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008316 SC_None,
8317 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008318 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008319
Richard Smithbc2a35d2012-12-08 08:32:28 +00008320 AddOverriddenMethods(ClassDecl, CopyAssignment);
8321
8322 CopyAssignment->setTrivial(
8323 ClassDecl->needsOverloadResolutionForCopyAssignment()
8324 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8325 : ClassDecl->hasTrivialCopyAssignment());
8326
Nico Weberafcc96a2012-01-23 03:19:29 +00008327 // C++0x [class.copy]p19:
8328 // .... If the class definition does not explicitly declare a copy
8329 // assignment operator, there is no user-declared move constructor, and
8330 // there is no user-declared move assignment operator, a copy assignment
8331 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008332 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00008333 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008334
Richard Smithbc2a35d2012-12-08 08:32:28 +00008335 // Note that we have added this copy-assignment operator.
8336 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8337
8338 if (Scope *S = getScopeForContext(ClassDecl))
8339 PushOnScopeChains(CopyAssignment, S, false);
8340 ClassDecl->addDecl(CopyAssignment);
8341
Douglas Gregord3c35902010-07-01 16:36:15 +00008342 return CopyAssignment;
8343}
8344
Douglas Gregor06a9f362010-05-01 20:49:11 +00008345void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8346 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008347 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008348 CopyAssignOperator->isOverloadedOperator() &&
8349 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008350 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8351 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008352 "DefineImplicitCopyAssignment called for wrong function");
8353
8354 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8355
8356 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8357 CopyAssignOperator->setInvalidDecl();
8358 return;
8359 }
8360
8361 CopyAssignOperator->setUsed();
8362
Eli Friedman9a14db32012-10-18 20:14:08 +00008363 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008364 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008365
8366 // C++0x [class.copy]p30:
8367 // The implicitly-defined or explicitly-defaulted copy assignment operator
8368 // for a non-union class X performs memberwise copy assignment of its
8369 // subobjects. The direct base classes of X are assigned first, in the
8370 // order of their declaration in the base-specifier-list, and then the
8371 // immediate non-static data members of X are assigned, in the order in
8372 // which they were declared in the class definition.
8373
8374 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008375 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008376
8377 // The parameter for the "other" object, which we are copying from.
8378 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8379 Qualifiers OtherQuals = Other->getType().getQualifiers();
8380 QualType OtherRefType = Other->getType();
8381 if (const LValueReferenceType *OtherRef
8382 = OtherRefType->getAs<LValueReferenceType>()) {
8383 OtherRefType = OtherRef->getPointeeType();
8384 OtherQuals = OtherRefType.getQualifiers();
8385 }
8386
8387 // Our location for everything implicitly-generated.
8388 SourceLocation Loc = CopyAssignOperator->getLocation();
8389
8390 // Construct a reference to the "other" object. We'll be using this
8391 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008392 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008393 assert(OtherRef && "Reference to parameter cannot fail!");
8394
8395 // Construct the "this" pointer. We'll be using this throughout the generated
8396 // ASTs.
8397 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8398 assert(This && "Reference to this cannot fail!");
8399
8400 // Assign base classes.
8401 bool Invalid = false;
8402 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8403 E = ClassDecl->bases_end(); Base != E; ++Base) {
8404 // Form the assignment:
8405 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8406 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008407 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008408 Invalid = true;
8409 continue;
8410 }
8411
John McCallf871d0c2010-08-07 06:22:56 +00008412 CXXCastPath BasePath;
8413 BasePath.push_back(Base);
8414
Douglas Gregor06a9f362010-05-01 20:49:11 +00008415 // Construct the "from" expression, which is an implicit cast to the
8416 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008417 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008418 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8419 CK_UncheckedDerivedToBase,
8420 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008421
8422 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008423 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008424
8425 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008426 To = ImpCastExprToType(To.take(),
8427 Context.getCVRQualifiedType(BaseType,
8428 CopyAssignOperator->getTypeQualifiers()),
8429 CK_UncheckedDerivedToBase,
8430 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008431
8432 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008433 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008434 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008435 /*CopyingBaseSubobject=*/true,
8436 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008437 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008438 Diag(CurrentLocation, diag::note_member_synthesized_at)
8439 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8440 CopyAssignOperator->setInvalidDecl();
8441 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008442 }
8443
8444 // Success! Record the copy.
8445 Statements.push_back(Copy.takeAs<Expr>());
8446 }
8447
Douglas Gregor06a9f362010-05-01 20:49:11 +00008448 // Assign non-static members.
8449 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8450 FieldEnd = ClassDecl->field_end();
8451 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008452 if (Field->isUnnamedBitfield())
8453 continue;
8454
Douglas Gregor06a9f362010-05-01 20:49:11 +00008455 // Check for members of reference type; we can't copy those.
8456 if (Field->getType()->isReferenceType()) {
8457 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8458 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8459 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008460 Diag(CurrentLocation, diag::note_member_synthesized_at)
8461 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008462 Invalid = true;
8463 continue;
8464 }
8465
8466 // Check for members of const-qualified, non-class type.
8467 QualType BaseType = Context.getBaseElementType(Field->getType());
8468 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8469 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8470 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8471 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008472 Diag(CurrentLocation, diag::note_member_synthesized_at)
8473 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008474 Invalid = true;
8475 continue;
8476 }
John McCallb77115d2011-06-17 00:18:42 +00008477
8478 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008479 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8480 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008481
8482 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008483 if (FieldType->isIncompleteArrayType()) {
8484 assert(ClassDecl->hasFlexibleArrayMember() &&
8485 "Incomplete array type is not valid");
8486 continue;
8487 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008488
8489 // Build references to the field in the object we're copying from and to.
8490 CXXScopeSpec SS; // Intentionally empty
8491 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8492 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008493 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008494 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008495 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008496 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008497 SS, SourceLocation(), 0,
8498 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008499 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008500 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008501 SS, SourceLocation(), 0,
8502 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008503 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8504 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008505
Douglas Gregor06a9f362010-05-01 20:49:11 +00008506 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008507 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008508 To.get(), From.get(),
8509 /*CopyingBaseSubobject=*/false,
8510 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008511 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008512 Diag(CurrentLocation, diag::note_member_synthesized_at)
8513 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8514 CopyAssignOperator->setInvalidDecl();
8515 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008516 }
8517
8518 // Success! Record the copy.
8519 Statements.push_back(Copy.takeAs<Stmt>());
8520 }
8521
8522 if (!Invalid) {
8523 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008524 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008525
John McCall60d7b3a2010-08-24 06:29:42 +00008526 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008527 if (Return.isInvalid())
8528 Invalid = true;
8529 else {
8530 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008531
8532 if (Trap.hasErrorOccurred()) {
8533 Diag(CurrentLocation, diag::note_member_synthesized_at)
8534 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8535 Invalid = true;
8536 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008537 }
8538 }
8539
8540 if (Invalid) {
8541 CopyAssignOperator->setInvalidDecl();
8542 return;
8543 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008544
8545 StmtResult Body;
8546 {
8547 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008548 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008549 /*isStmtExpr=*/false);
8550 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8551 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008552 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008553
8554 if (ASTMutationListener *L = getASTMutationListener()) {
8555 L->CompletedImplicitDefinition(CopyAssignOperator);
8556 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008557}
8558
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008559Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008560Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8561 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008562
Richard Smithb9d0b762012-07-27 04:22:15 +00008563 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008564 if (ClassDecl->isInvalidDecl())
8565 return ExceptSpec;
8566
8567 // C++0x [except.spec]p14:
8568 // An implicitly declared special member function (Clause 12) shall have an
8569 // exception-specification. [...]
8570
8571 // It is unspecified whether or not an implicit move assignment operator
8572 // attempts to deduplicate calls to assignment operators of virtual bases are
8573 // made. As such, this exception specification is effectively unspecified.
8574 // Based on a similar decision made for constness in C++0x, we're erring on
8575 // the side of assuming such calls to be made regardless of whether they
8576 // actually happen.
8577 // Note that a move constructor is not implicitly declared when there are
8578 // virtual bases, but it can still be user-declared and explicitly defaulted.
8579 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8580 BaseEnd = ClassDecl->bases_end();
8581 Base != BaseEnd; ++Base) {
8582 if (Base->isVirtual())
8583 continue;
8584
8585 CXXRecordDecl *BaseClassDecl
8586 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8587 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008588 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008589 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008590 }
8591
8592 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8593 BaseEnd = ClassDecl->vbases_end();
8594 Base != BaseEnd; ++Base) {
8595 CXXRecordDecl *BaseClassDecl
8596 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8597 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008598 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008599 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008600 }
8601
8602 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8603 FieldEnd = ClassDecl->field_end();
8604 Field != FieldEnd;
8605 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008606 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008607 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008608 if (CXXMethodDecl *MoveAssign =
8609 LookupMovingAssignment(FieldClassDecl,
8610 FieldType.getCVRQualifiers(),
8611 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008612 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008613 }
8614 }
8615
8616 return ExceptSpec;
8617}
8618
Richard Smith1c931be2012-04-02 18:40:40 +00008619/// Determine whether the class type has any direct or indirect virtual base
8620/// classes which have a non-trivial move assignment operator.
8621static bool
8622hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8623 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8624 BaseEnd = ClassDecl->vbases_end();
8625 Base != BaseEnd; ++Base) {
8626 CXXRecordDecl *BaseClass =
8627 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8628
8629 // Try to declare the move assignment. If it would be deleted, then the
8630 // class does not have a non-trivial move assignment.
8631 if (BaseClass->needsImplicitMoveAssignment())
8632 S.DeclareImplicitMoveAssignment(BaseClass);
8633
Richard Smith426391c2012-11-16 00:53:38 +00008634 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008635 return true;
8636 }
8637
8638 return false;
8639}
8640
8641/// Determine whether the given type either has a move constructor or is
8642/// trivially copyable.
8643static bool
8644hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8645 Type = S.Context.getBaseElementType(Type);
8646
8647 // FIXME: Technically, non-trivially-copyable non-class types, such as
8648 // reference types, are supposed to return false here, but that appears
8649 // to be a standard defect.
8650 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008651 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008652 return true;
8653
8654 if (Type.isTriviallyCopyableType(S.Context))
8655 return true;
8656
8657 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008658 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8659 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008660 if (ClassDecl->needsImplicitMoveConstructor())
8661 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008662 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008663 }
8664
Richard Smithe5411b72012-12-01 02:35:44 +00008665 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8666 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008667 if (ClassDecl->needsImplicitMoveAssignment())
8668 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008669 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008670}
8671
8672/// Determine whether all non-static data members and direct or virtual bases
8673/// of class \p ClassDecl have either a move operation, or are trivially
8674/// copyable.
8675static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8676 bool IsConstructor) {
8677 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8678 BaseEnd = ClassDecl->bases_end();
8679 Base != BaseEnd; ++Base) {
8680 if (Base->isVirtual())
8681 continue;
8682
8683 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8684 return false;
8685 }
8686
8687 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8688 BaseEnd = ClassDecl->vbases_end();
8689 Base != BaseEnd; ++Base) {
8690 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8691 return false;
8692 }
8693
8694 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8695 FieldEnd = ClassDecl->field_end();
8696 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008697 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008698 return false;
8699 }
8700
8701 return true;
8702}
8703
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008704CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008705 // C++11 [class.copy]p20:
8706 // If the definition of a class X does not explicitly declare a move
8707 // assignment operator, one will be implicitly declared as defaulted
8708 // if and only if:
8709 //
8710 // - [first 4 bullets]
8711 assert(ClassDecl->needsImplicitMoveAssignment());
8712
Richard Smithafb49182012-11-29 01:34:07 +00008713 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8714 if (DSM.isAlreadyBeingDeclared())
8715 return 0;
8716
Richard Smith1c931be2012-04-02 18:40:40 +00008717 // [Checked after we build the declaration]
8718 // - the move assignment operator would not be implicitly defined as
8719 // deleted,
8720
8721 // [DR1402]:
8722 // - X has no direct or indirect virtual base class with a non-trivial
8723 // move assignment operator, and
8724 // - each of X's non-static data members and direct or virtual base classes
8725 // has a type that either has a move assignment operator or is trivially
8726 // copyable.
8727 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8728 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8729 ClassDecl->setFailedImplicitMoveAssignment();
8730 return 0;
8731 }
8732
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008733 // Note: The following rules are largely analoguous to the move
8734 // constructor rules.
8735
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008736 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8737 QualType RetType = Context.getLValueReferenceType(ArgType);
8738 ArgType = Context.getRValueReferenceType(ArgType);
8739
8740 // An implicitly-declared move assignment operator is an inline public
8741 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008742 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8743 SourceLocation ClassLoc = ClassDecl->getLocation();
8744 DeclarationNameInfo NameInfo(Name, ClassLoc);
8745 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008746 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008747 /*TInfo=*/0, /*isStatic=*/false,
8748 /*StorageClassAsWritten=*/SC_None,
8749 /*isInline=*/true,
8750 /*isConstexpr=*/false,
8751 SourceLocation());
8752 MoveAssignment->setAccess(AS_public);
8753 MoveAssignment->setDefaulted();
8754 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008755
Richard Smithb9d0b762012-07-27 04:22:15 +00008756 // Build an exception specification pointing back at this member.
8757 FunctionProtoType::ExtProtoInfo EPI;
8758 EPI.ExceptionSpecType = EST_Unevaluated;
8759 EPI.ExceptionSpecDecl = MoveAssignment;
8760 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8761
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008762 // Add the parameter to the operator.
8763 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8764 ClassLoc, ClassLoc, /*Id=*/0,
8765 ArgType, /*TInfo=*/0,
8766 SC_None,
8767 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008768 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008769
Richard Smithbc2a35d2012-12-08 08:32:28 +00008770 AddOverriddenMethods(ClassDecl, MoveAssignment);
8771
8772 MoveAssignment->setTrivial(
8773 ClassDecl->needsOverloadResolutionForMoveAssignment()
8774 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8775 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008776
8777 // C++0x [class.copy]p9:
8778 // If the definition of a class X does not explicitly declare a move
8779 // assignment operator, one will be implicitly declared as defaulted if and
8780 // only if:
8781 // [...]
8782 // - the move assignment operator would not be implicitly defined as
8783 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008784 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008785 // Cache this result so that we don't try to generate this over and over
8786 // on every lookup, leaking memory and wasting time.
8787 ClassDecl->setFailedImplicitMoveAssignment();
8788 return 0;
8789 }
8790
Richard Smithbc2a35d2012-12-08 08:32:28 +00008791 // Note that we have added this copy-assignment operator.
8792 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8793
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008794 if (Scope *S = getScopeForContext(ClassDecl))
8795 PushOnScopeChains(MoveAssignment, S, false);
8796 ClassDecl->addDecl(MoveAssignment);
8797
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008798 return MoveAssignment;
8799}
8800
8801void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8802 CXXMethodDecl *MoveAssignOperator) {
8803 assert((MoveAssignOperator->isDefaulted() &&
8804 MoveAssignOperator->isOverloadedOperator() &&
8805 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008806 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8807 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008808 "DefineImplicitMoveAssignment called for wrong function");
8809
8810 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8811
8812 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8813 MoveAssignOperator->setInvalidDecl();
8814 return;
8815 }
8816
8817 MoveAssignOperator->setUsed();
8818
Eli Friedman9a14db32012-10-18 20:14:08 +00008819 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008820 DiagnosticErrorTrap Trap(Diags);
8821
8822 // C++0x [class.copy]p28:
8823 // The implicitly-defined or move assignment operator for a non-union class
8824 // X performs memberwise move assignment of its subobjects. The direct base
8825 // classes of X are assigned first, in the order of their declaration in the
8826 // base-specifier-list, and then the immediate non-static data members of X
8827 // are assigned, in the order in which they were declared in the class
8828 // definition.
8829
8830 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008831 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008832
8833 // The parameter for the "other" object, which we are move from.
8834 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8835 QualType OtherRefType = Other->getType()->
8836 getAs<RValueReferenceType>()->getPointeeType();
8837 assert(OtherRefType.getQualifiers() == 0 &&
8838 "Bad argument type of defaulted move assignment");
8839
8840 // Our location for everything implicitly-generated.
8841 SourceLocation Loc = MoveAssignOperator->getLocation();
8842
8843 // Construct a reference to the "other" object. We'll be using this
8844 // throughout the generated ASTs.
8845 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8846 assert(OtherRef && "Reference to parameter cannot fail!");
8847 // Cast to rvalue.
8848 OtherRef = CastForMoving(*this, OtherRef);
8849
8850 // Construct the "this" pointer. We'll be using this throughout the generated
8851 // ASTs.
8852 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8853 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008854
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008855 // Assign base classes.
8856 bool Invalid = false;
8857 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8858 E = ClassDecl->bases_end(); Base != E; ++Base) {
8859 // Form the assignment:
8860 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8861 QualType BaseType = Base->getType().getUnqualifiedType();
8862 if (!BaseType->isRecordType()) {
8863 Invalid = true;
8864 continue;
8865 }
8866
8867 CXXCastPath BasePath;
8868 BasePath.push_back(Base);
8869
8870 // Construct the "from" expression, which is an implicit cast to the
8871 // appropriately-qualified base type.
8872 Expr *From = OtherRef;
8873 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008874 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008875
8876 // Dereference "this".
8877 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8878
8879 // Implicitly cast "this" to the appropriately-qualified base type.
8880 To = ImpCastExprToType(To.take(),
8881 Context.getCVRQualifiedType(BaseType,
8882 MoveAssignOperator->getTypeQualifiers()),
8883 CK_UncheckedDerivedToBase,
8884 VK_LValue, &BasePath);
8885
8886 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00008887 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008888 To.get(), From,
8889 /*CopyingBaseSubobject=*/true,
8890 /*Copying=*/false);
8891 if (Move.isInvalid()) {
8892 Diag(CurrentLocation, diag::note_member_synthesized_at)
8893 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8894 MoveAssignOperator->setInvalidDecl();
8895 return;
8896 }
8897
8898 // Success! Record the move.
8899 Statements.push_back(Move.takeAs<Expr>());
8900 }
8901
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008902 // Assign non-static members.
8903 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8904 FieldEnd = ClassDecl->field_end();
8905 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008906 if (Field->isUnnamedBitfield())
8907 continue;
8908
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008909 // Check for members of reference type; we can't move those.
8910 if (Field->getType()->isReferenceType()) {
8911 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8912 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8913 Diag(Field->getLocation(), diag::note_declared_at);
8914 Diag(CurrentLocation, diag::note_member_synthesized_at)
8915 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8916 Invalid = true;
8917 continue;
8918 }
8919
8920 // Check for members of const-qualified, non-class type.
8921 QualType BaseType = Context.getBaseElementType(Field->getType());
8922 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8923 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8924 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8925 Diag(Field->getLocation(), diag::note_declared_at);
8926 Diag(CurrentLocation, diag::note_member_synthesized_at)
8927 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8928 Invalid = true;
8929 continue;
8930 }
8931
8932 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008933 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8934 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008935
8936 QualType FieldType = Field->getType().getNonReferenceType();
8937 if (FieldType->isIncompleteArrayType()) {
8938 assert(ClassDecl->hasFlexibleArrayMember() &&
8939 "Incomplete array type is not valid");
8940 continue;
8941 }
8942
8943 // Build references to the field in the object we're copying from and to.
8944 CXXScopeSpec SS; // Intentionally empty
8945 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8946 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008947 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008948 MemberLookup.resolveKind();
8949 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8950 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008951 SS, SourceLocation(), 0,
8952 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008953 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8954 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008955 SS, SourceLocation(), 0,
8956 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008957 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8958 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8959
8960 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8961 "Member reference with rvalue base must be rvalue except for reference "
8962 "members, which aren't allowed for move assignment.");
8963
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008964 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008965 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008966 To.get(), From.get(),
8967 /*CopyingBaseSubobject=*/false,
8968 /*Copying=*/false);
8969 if (Move.isInvalid()) {
8970 Diag(CurrentLocation, diag::note_member_synthesized_at)
8971 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8972 MoveAssignOperator->setInvalidDecl();
8973 return;
8974 }
Richard Smithe7ce7092012-11-12 23:33:00 +00008975
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008976 // Success! Record the copy.
8977 Statements.push_back(Move.takeAs<Stmt>());
8978 }
8979
8980 if (!Invalid) {
8981 // Add a "return *this;"
8982 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8983
8984 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8985 if (Return.isInvalid())
8986 Invalid = true;
8987 else {
8988 Statements.push_back(Return.takeAs<Stmt>());
8989
8990 if (Trap.hasErrorOccurred()) {
8991 Diag(CurrentLocation, diag::note_member_synthesized_at)
8992 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8993 Invalid = true;
8994 }
8995 }
8996 }
8997
8998 if (Invalid) {
8999 MoveAssignOperator->setInvalidDecl();
9000 return;
9001 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009002
9003 StmtResult Body;
9004 {
9005 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009006 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009007 /*isStmtExpr=*/false);
9008 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9009 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009010 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9011
9012 if (ASTMutationListener *L = getASTMutationListener()) {
9013 L->CompletedImplicitDefinition(MoveAssignOperator);
9014 }
9015}
9016
Richard Smithb9d0b762012-07-27 04:22:15 +00009017Sema::ImplicitExceptionSpecification
9018Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9019 CXXRecordDecl *ClassDecl = MD->getParent();
9020
9021 ImplicitExceptionSpecification ExceptSpec(*this);
9022 if (ClassDecl->isInvalidDecl())
9023 return ExceptSpec;
9024
9025 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9026 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9027 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9028
Douglas Gregor0d405db2010-07-01 20:59:04 +00009029 // C++ [except.spec]p14:
9030 // An implicitly declared special member function (Clause 12) shall have an
9031 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009032 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9033 BaseEnd = ClassDecl->bases_end();
9034 Base != BaseEnd;
9035 ++Base) {
9036 // Virtual bases are handled below.
9037 if (Base->isVirtual())
9038 continue;
9039
Douglas Gregor22584312010-07-02 23:41:54 +00009040 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009041 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009042 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009043 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009044 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009045 }
9046 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9047 BaseEnd = ClassDecl->vbases_end();
9048 Base != BaseEnd;
9049 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009050 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009051 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009052 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009053 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009054 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009055 }
9056 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9057 FieldEnd = ClassDecl->field_end();
9058 Field != FieldEnd;
9059 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009060 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009061 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9062 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009063 LookupCopyingConstructor(FieldClassDecl,
9064 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009065 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009066 }
9067 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009068
Richard Smithb9d0b762012-07-27 04:22:15 +00009069 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009070}
9071
9072CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9073 CXXRecordDecl *ClassDecl) {
9074 // C++ [class.copy]p4:
9075 // If the class definition does not explicitly declare a copy
9076 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009077 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009078
Richard Smithafb49182012-11-29 01:34:07 +00009079 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9080 if (DSM.isAlreadyBeingDeclared())
9081 return 0;
9082
Sean Hunt49634cf2011-05-13 06:10:58 +00009083 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9084 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009085 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009086 if (Const)
9087 ArgType = ArgType.withConst();
9088 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009089
Richard Smith7756afa2012-06-10 05:43:50 +00009090 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9091 CXXCopyConstructor,
9092 Const);
9093
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009094 DeclarationName Name
9095 = Context.DeclarationNames.getCXXConstructorName(
9096 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009097 SourceLocation ClassLoc = ClassDecl->getLocation();
9098 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009099
9100 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009101 // member of its class.
9102 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009103 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009104 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009105 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009106 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009107 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009108
Richard Smithb9d0b762012-07-27 04:22:15 +00009109 // Build an exception specification pointing back at this member.
9110 FunctionProtoType::ExtProtoInfo EPI;
9111 EPI.ExceptionSpecType = EST_Unevaluated;
9112 EPI.ExceptionSpecDecl = CopyConstructor;
9113 CopyConstructor->setType(
9114 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9115
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009116 // Add the parameter to the constructor.
9117 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009118 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009119 /*IdentifierInfo=*/0,
9120 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009121 SC_None,
9122 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009123 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009124
Richard Smithbc2a35d2012-12-08 08:32:28 +00009125 CopyConstructor->setTrivial(
9126 ClassDecl->needsOverloadResolutionForCopyConstructor()
9127 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9128 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009129
Nico Weberafcc96a2012-01-23 03:19:29 +00009130 // C++11 [class.copy]p8:
9131 // ... If the class definition does not explicitly declare a copy
9132 // constructor, there is no user-declared move constructor, and there is no
9133 // user-declared move assignment operator, a copy constructor is implicitly
9134 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009135 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00009136 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00009137
Richard Smithbc2a35d2012-12-08 08:32:28 +00009138 // Note that we have declared this constructor.
9139 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9140
9141 if (Scope *S = getScopeForContext(ClassDecl))
9142 PushOnScopeChains(CopyConstructor, S, false);
9143 ClassDecl->addDecl(CopyConstructor);
9144
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009145 return CopyConstructor;
9146}
9147
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009148void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009149 CXXConstructorDecl *CopyConstructor) {
9150 assert((CopyConstructor->isDefaulted() &&
9151 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009152 !CopyConstructor->doesThisDeclarationHaveABody() &&
9153 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009154 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009155
Anders Carlsson63010a72010-04-23 16:24:12 +00009156 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009157 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009158
Eli Friedman9a14db32012-10-18 20:14:08 +00009159 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009160 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009161
Sean Huntcbb67482011-01-08 20:30:50 +00009162 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009163 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009164 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009165 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009166 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009167 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009168 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009169 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9170 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009171 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009172 /*isStmtExpr=*/false)
9173 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009174 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009175 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009176
9177 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009178 if (ASTMutationListener *L = getASTMutationListener()) {
9179 L->CompletedImplicitDefinition(CopyConstructor);
9180 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009181}
9182
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009183Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009184Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9185 CXXRecordDecl *ClassDecl = MD->getParent();
9186
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009187 // C++ [except.spec]p14:
9188 // An implicitly declared special member function (Clause 12) shall have an
9189 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009190 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009191 if (ClassDecl->isInvalidDecl())
9192 return ExceptSpec;
9193
9194 // Direct base-class constructors.
9195 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9196 BEnd = ClassDecl->bases_end();
9197 B != BEnd; ++B) {
9198 if (B->isVirtual()) // Handled below.
9199 continue;
9200
9201 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9202 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009203 CXXConstructorDecl *Constructor =
9204 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009205 // If this is a deleted function, add it anyway. This might be conformant
9206 // with the standard. This might not. I'm not sure. It might not matter.
9207 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009208 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009209 }
9210 }
9211
9212 // Virtual base-class constructors.
9213 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9214 BEnd = ClassDecl->vbases_end();
9215 B != BEnd; ++B) {
9216 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9217 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009218 CXXConstructorDecl *Constructor =
9219 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009220 // If this is a deleted function, add it anyway. This might be conformant
9221 // with the standard. This might not. I'm not sure. It might not matter.
9222 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009223 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009224 }
9225 }
9226
9227 // Field constructors.
9228 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9229 FEnd = ClassDecl->field_end();
9230 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009231 QualType FieldType = Context.getBaseElementType(F->getType());
9232 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9233 CXXConstructorDecl *Constructor =
9234 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009235 // If this is a deleted function, add it anyway. This might be conformant
9236 // with the standard. This might not. I'm not sure. It might not matter.
9237 // In particular, the problem is that this function never gets called. It
9238 // might just be ill-formed because this function attempts to refer to
9239 // a deleted function here.
9240 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009241 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009242 }
9243 }
9244
9245 return ExceptSpec;
9246}
9247
9248CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9249 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009250 // C++11 [class.copy]p9:
9251 // If the definition of a class X does not explicitly declare a move
9252 // constructor, one will be implicitly declared as defaulted if and only if:
9253 //
9254 // - [first 4 bullets]
9255 assert(ClassDecl->needsImplicitMoveConstructor());
9256
Richard Smithafb49182012-11-29 01:34:07 +00009257 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9258 if (DSM.isAlreadyBeingDeclared())
9259 return 0;
9260
Richard Smith1c931be2012-04-02 18:40:40 +00009261 // [Checked after we build the declaration]
9262 // - the move assignment operator would not be implicitly defined as
9263 // deleted,
9264
9265 // [DR1402]:
9266 // - each of X's non-static data members and direct or virtual base classes
9267 // has a type that either has a move constructor or is trivially copyable.
9268 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9269 ClassDecl->setFailedImplicitMoveConstructor();
9270 return 0;
9271 }
9272
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009273 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9274 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009275
Richard Smith7756afa2012-06-10 05:43:50 +00009276 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9277 CXXMoveConstructor,
9278 false);
9279
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009280 DeclarationName Name
9281 = Context.DeclarationNames.getCXXConstructorName(
9282 Context.getCanonicalType(ClassType));
9283 SourceLocation ClassLoc = ClassDecl->getLocation();
9284 DeclarationNameInfo NameInfo(Name, ClassLoc);
9285
9286 // C++0x [class.copy]p11:
9287 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009288 // member of its class.
9289 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009290 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009291 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009292 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009293 MoveConstructor->setAccess(AS_public);
9294 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009295
Richard Smithb9d0b762012-07-27 04:22:15 +00009296 // Build an exception specification pointing back at this member.
9297 FunctionProtoType::ExtProtoInfo EPI;
9298 EPI.ExceptionSpecType = EST_Unevaluated;
9299 EPI.ExceptionSpecDecl = MoveConstructor;
9300 MoveConstructor->setType(
9301 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9302
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009303 // Add the parameter to the constructor.
9304 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9305 ClassLoc, ClassLoc,
9306 /*IdentifierInfo=*/0,
9307 ArgType, /*TInfo=*/0,
9308 SC_None,
9309 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009310 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009311
Richard Smithbc2a35d2012-12-08 08:32:28 +00009312 MoveConstructor->setTrivial(
9313 ClassDecl->needsOverloadResolutionForMoveConstructor()
9314 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9315 : ClassDecl->hasTrivialMoveConstructor());
9316
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009317 // C++0x [class.copy]p9:
9318 // If the definition of a class X does not explicitly declare a move
9319 // constructor, one will be implicitly declared as defaulted if and only if:
9320 // [...]
9321 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009322 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009323 // Cache this result so that we don't try to generate this over and over
9324 // on every lookup, leaking memory and wasting time.
9325 ClassDecl->setFailedImplicitMoveConstructor();
9326 return 0;
9327 }
9328
9329 // Note that we have declared this constructor.
9330 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9331
9332 if (Scope *S = getScopeForContext(ClassDecl))
9333 PushOnScopeChains(MoveConstructor, S, false);
9334 ClassDecl->addDecl(MoveConstructor);
9335
9336 return MoveConstructor;
9337}
9338
9339void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9340 CXXConstructorDecl *MoveConstructor) {
9341 assert((MoveConstructor->isDefaulted() &&
9342 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009343 !MoveConstructor->doesThisDeclarationHaveABody() &&
9344 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009345 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9346
9347 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9348 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9349
Eli Friedman9a14db32012-10-18 20:14:08 +00009350 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009351 DiagnosticErrorTrap Trap(Diags);
9352
9353 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
9354 Trap.hasErrorOccurred()) {
9355 Diag(CurrentLocation, diag::note_member_synthesized_at)
9356 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9357 MoveConstructor->setInvalidDecl();
9358 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009359 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009360 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9361 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009362 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009363 /*isStmtExpr=*/false)
9364 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009365 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009366 }
9367
9368 MoveConstructor->setUsed();
9369
9370 if (ASTMutationListener *L = getASTMutationListener()) {
9371 L->CompletedImplicitDefinition(MoveConstructor);
9372 }
9373}
9374
Douglas Gregore4e68d42012-02-15 19:33:52 +00009375bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9376 return FD->isDeleted() &&
9377 (FD->isDefaulted() || FD->isImplicit()) &&
9378 isa<CXXMethodDecl>(FD);
9379}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009380
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009381/// \brief Mark the call operator of the given lambda closure type as "used".
9382static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9383 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009384 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009385 Lambda->lookup(
9386 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009387 CallOperator->setReferenced();
9388 CallOperator->setUsed();
9389}
9390
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009391void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9392 SourceLocation CurrentLocation,
9393 CXXConversionDecl *Conv)
9394{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009395 CXXRecordDecl *Lambda = Conv->getParent();
9396
9397 // Make sure that the lambda call operator is marked used.
9398 markLambdaCallOperatorUsed(*this, Lambda);
9399
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009400 Conv->setUsed();
9401
Eli Friedman9a14db32012-10-18 20:14:08 +00009402 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009403 DiagnosticErrorTrap Trap(Diags);
9404
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009405 // Return the address of the __invoke function.
9406 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9407 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009408 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009409 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9410 VK_LValue, Conv->getLocation()).take();
9411 assert(FunctionRef && "Can't refer to __invoke function?");
9412 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009413 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009414 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009415 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009416
9417 // Fill in the __invoke function with a dummy implementation. IR generation
9418 // will fill in the actual details.
9419 Invoke->setUsed();
9420 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009421 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009422
9423 if (ASTMutationListener *L = getASTMutationListener()) {
9424 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009425 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009426 }
9427}
9428
9429void Sema::DefineImplicitLambdaToBlockPointerConversion(
9430 SourceLocation CurrentLocation,
9431 CXXConversionDecl *Conv)
9432{
9433 Conv->setUsed();
9434
Eli Friedman9a14db32012-10-18 20:14:08 +00009435 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009436 DiagnosticErrorTrap Trap(Diags);
9437
Douglas Gregorac1303e2012-02-22 05:02:47 +00009438 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009439 Expr *This = ActOnCXXThis(CurrentLocation).take();
9440 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009441
Eli Friedman23f02672012-03-01 04:01:32 +00009442 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9443 Conv->getLocation(),
9444 Conv, DerefThis);
9445
9446 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9447 // behavior. Note that only the general conversion function does this
9448 // (since it's unusable otherwise); in the case where we inline the
9449 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009450 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009451 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9452 CK_CopyAndAutoreleaseBlockObject,
9453 BuildBlock.get(), 0, VK_RValue);
9454
9455 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009456 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009457 Conv->setInvalidDecl();
9458 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009459 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009460
Douglas Gregorac1303e2012-02-22 05:02:47 +00009461 // Create the return statement that returns the block from the conversion
9462 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009463 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009464 if (Return.isInvalid()) {
9465 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9466 Conv->setInvalidDecl();
9467 return;
9468 }
9469
9470 // Set the body of the conversion function.
9471 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009472 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009473 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009474 Conv->getLocation()));
9475
Douglas Gregorac1303e2012-02-22 05:02:47 +00009476 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009477 if (ASTMutationListener *L = getASTMutationListener()) {
9478 L->CompletedImplicitDefinition(Conv);
9479 }
9480}
9481
Douglas Gregorf52757d2012-03-10 06:53:13 +00009482/// \brief Determine whether the given list arguments contains exactly one
9483/// "real" (non-default) argument.
9484static bool hasOneRealArgument(MultiExprArg Args) {
9485 switch (Args.size()) {
9486 case 0:
9487 return false;
9488
9489 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009490 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009491 return false;
9492
9493 // fall through
9494 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009495 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009496 }
9497
9498 return false;
9499}
9500
John McCall60d7b3a2010-08-24 06:29:42 +00009501ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009502Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009503 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009504 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009505 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009506 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009507 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009508 unsigned ConstructKind,
9509 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009510 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009511
Douglas Gregor2f599792010-04-02 18:24:57 +00009512 // C++0x [class.copy]p34:
9513 // When certain criteria are met, an implementation is allowed to
9514 // omit the copy/move construction of a class object, even if the
9515 // copy/move constructor and/or destructor for the object have
9516 // side effects. [...]
9517 // - when a temporary class object that has not been bound to a
9518 // reference (12.2) would be copied/moved to a class object
9519 // with the same cv-unqualified type, the copy/move operation
9520 // can be omitted by constructing the temporary object
9521 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009522 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009523 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009524 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009525 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009526 }
Mike Stump1eb44332009-09-09 15:08:12 +00009527
9528 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009529 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009530 IsListInitialization, RequiresZeroInit,
9531 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009532}
9533
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009534/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9535/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009536ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009537Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9538 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009539 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009540 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009541 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009542 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009543 unsigned ConstructKind,
9544 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009545 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009546 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009547 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009548 HadMultipleCandidates,
9549 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009550 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9551 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009552}
9553
John McCall68c6c9a2010-02-02 09:10:11 +00009554void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009555 if (VD->isInvalidDecl()) return;
9556
John McCall68c6c9a2010-02-02 09:10:11 +00009557 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009558 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009559 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009560 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009561
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009562 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009563 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009564 CheckDestructorAccess(VD->getLocation(), Destructor,
9565 PDiag(diag::err_access_dtor_var)
9566 << VD->getDeclName()
9567 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009568 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009569
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009570 if (!VD->hasGlobalStorage()) return;
9571
9572 // Emit warning for non-trivial dtor in global scope (a real global,
9573 // class-static, function-static).
9574 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9575
9576 // TODO: this should be re-enabled for static locals by !CXAAtExit
9577 if (!VD->isStaticLocal())
9578 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009579}
9580
Douglas Gregor39da0b82009-09-09 23:08:42 +00009581/// \brief Given a constructor and the set of arguments provided for the
9582/// constructor, convert the arguments and add any required default arguments
9583/// to form a proper call to this constructor.
9584///
9585/// \returns true if an error occurred, false otherwise.
9586bool
9587Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9588 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009589 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009590 SmallVectorImpl<Expr*> &ConvertedArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009591 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009592 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9593 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009594 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009595
9596 const FunctionProtoType *Proto
9597 = Constructor->getType()->getAs<FunctionProtoType>();
9598 assert(Proto && "Constructor without a prototype?");
9599 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009600
9601 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009602 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009603 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009604 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009605 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009606
9607 VariadicCallType CallType =
9608 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009609 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009610 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9611 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009612 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009613 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009614
9615 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9616
Richard Smith831421f2012-06-25 20:30:08 +00009617 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9618 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009619
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009620 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009621}
9622
Anders Carlsson20d45d22009-12-12 00:32:00 +00009623static inline bool
9624CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9625 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009626 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009627 if (isa<NamespaceDecl>(DC)) {
9628 return SemaRef.Diag(FnDecl->getLocation(),
9629 diag::err_operator_new_delete_declared_in_namespace)
9630 << FnDecl->getDeclName();
9631 }
9632
9633 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009634 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009635 return SemaRef.Diag(FnDecl->getLocation(),
9636 diag::err_operator_new_delete_declared_static)
9637 << FnDecl->getDeclName();
9638 }
9639
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009640 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009641}
9642
Anders Carlsson156c78e2009-12-13 17:53:43 +00009643static inline bool
9644CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9645 CanQualType ExpectedResultType,
9646 CanQualType ExpectedFirstParamType,
9647 unsigned DependentParamTypeDiag,
9648 unsigned InvalidParamTypeDiag) {
9649 QualType ResultType =
9650 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9651
9652 // Check that the result type is not dependent.
9653 if (ResultType->isDependentType())
9654 return SemaRef.Diag(FnDecl->getLocation(),
9655 diag::err_operator_new_delete_dependent_result_type)
9656 << FnDecl->getDeclName() << ExpectedResultType;
9657
9658 // Check that the result type is what we expect.
9659 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9660 return SemaRef.Diag(FnDecl->getLocation(),
9661 diag::err_operator_new_delete_invalid_result_type)
9662 << FnDecl->getDeclName() << ExpectedResultType;
9663
9664 // A function template must have at least 2 parameters.
9665 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9666 return SemaRef.Diag(FnDecl->getLocation(),
9667 diag::err_operator_new_delete_template_too_few_parameters)
9668 << FnDecl->getDeclName();
9669
9670 // The function decl must have at least 1 parameter.
9671 if (FnDecl->getNumParams() == 0)
9672 return SemaRef.Diag(FnDecl->getLocation(),
9673 diag::err_operator_new_delete_too_few_parameters)
9674 << FnDecl->getDeclName();
9675
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009676 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009677 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9678 if (FirstParamType->isDependentType())
9679 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9680 << FnDecl->getDeclName() << ExpectedFirstParamType;
9681
9682 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009683 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009684 ExpectedFirstParamType)
9685 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9686 << FnDecl->getDeclName() << ExpectedFirstParamType;
9687
9688 return false;
9689}
9690
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009691static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009692CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009693 // C++ [basic.stc.dynamic.allocation]p1:
9694 // A program is ill-formed if an allocation function is declared in a
9695 // namespace scope other than global scope or declared static in global
9696 // scope.
9697 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9698 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009699
9700 CanQualType SizeTy =
9701 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9702
9703 // C++ [basic.stc.dynamic.allocation]p1:
9704 // The return type shall be void*. The first parameter shall have type
9705 // std::size_t.
9706 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9707 SizeTy,
9708 diag::err_operator_new_dependent_param_type,
9709 diag::err_operator_new_param_type))
9710 return true;
9711
9712 // C++ [basic.stc.dynamic.allocation]p1:
9713 // The first parameter shall not have an associated default argument.
9714 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009715 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009716 diag::err_operator_new_default_arg)
9717 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9718
9719 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009720}
9721
9722static bool
Richard Smith444d3842012-10-20 08:26:51 +00009723CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009724 // C++ [basic.stc.dynamic.deallocation]p1:
9725 // A program is ill-formed if deallocation functions are declared in a
9726 // namespace scope other than global scope or declared static in global
9727 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009728 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9729 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009730
9731 // C++ [basic.stc.dynamic.deallocation]p2:
9732 // Each deallocation function shall return void and its first parameter
9733 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009734 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9735 SemaRef.Context.VoidPtrTy,
9736 diag::err_operator_delete_dependent_param_type,
9737 diag::err_operator_delete_param_type))
9738 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009739
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009740 return false;
9741}
9742
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009743/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9744/// of this overloaded operator is well-formed. If so, returns false;
9745/// otherwise, emits appropriate diagnostics and returns true.
9746bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009747 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009748 "Expected an overloaded operator declaration");
9749
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009750 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9751
Mike Stump1eb44332009-09-09 15:08:12 +00009752 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009753 // The allocation and deallocation functions, operator new,
9754 // operator new[], operator delete and operator delete[], are
9755 // described completely in 3.7.3. The attributes and restrictions
9756 // found in the rest of this subclause do not apply to them unless
9757 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009758 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009759 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009760
Anders Carlssona3ccda52009-12-12 00:26:23 +00009761 if (Op == OO_New || Op == OO_Array_New)
9762 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009763
9764 // C++ [over.oper]p6:
9765 // An operator function shall either be a non-static member
9766 // function or be a non-member function and have at least one
9767 // parameter whose type is a class, a reference to a class, an
9768 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009769 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9770 if (MethodDecl->isStatic())
9771 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009772 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009773 } else {
9774 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009775 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9776 ParamEnd = FnDecl->param_end();
9777 Param != ParamEnd; ++Param) {
9778 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009779 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9780 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009781 ClassOrEnumParam = true;
9782 break;
9783 }
9784 }
9785
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009786 if (!ClassOrEnumParam)
9787 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009788 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009789 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009790 }
9791
9792 // C++ [over.oper]p8:
9793 // An operator function cannot have default arguments (8.3.6),
9794 // except where explicitly stated below.
9795 //
Mike Stump1eb44332009-09-09 15:08:12 +00009796 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009797 // (C++ [over.call]p1).
9798 if (Op != OO_Call) {
9799 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9800 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009801 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009802 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009803 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009804 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009805 }
9806 }
9807
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009808 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9809 { false, false, false }
9810#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9811 , { Unary, Binary, MemberOnly }
9812#include "clang/Basic/OperatorKinds.def"
9813 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009814
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009815 bool CanBeUnaryOperator = OperatorUses[Op][0];
9816 bool CanBeBinaryOperator = OperatorUses[Op][1];
9817 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009818
9819 // C++ [over.oper]p8:
9820 // [...] Operator functions cannot have more or fewer parameters
9821 // than the number required for the corresponding operator, as
9822 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009823 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009824 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009825 if (Op != OO_Call &&
9826 ((NumParams == 1 && !CanBeUnaryOperator) ||
9827 (NumParams == 2 && !CanBeBinaryOperator) ||
9828 (NumParams < 1) || (NumParams > 2))) {
9829 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009830 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009831 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009832 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009833 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009834 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009835 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009836 assert(CanBeBinaryOperator &&
9837 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009838 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009839 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009840
Chris Lattner416e46f2008-11-21 07:57:12 +00009841 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009842 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009843 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009844
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009845 // Overloaded operators other than operator() cannot be variadic.
9846 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009847 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009848 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009849 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009850 }
9851
9852 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009853 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9854 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009855 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009856 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009857 }
9858
9859 // C++ [over.inc]p1:
9860 // The user-defined function called operator++ implements the
9861 // prefix and postfix ++ operator. If this function is a member
9862 // function with no parameters, or a non-member function with one
9863 // parameter of class or enumeration type, it defines the prefix
9864 // increment operator ++ for objects of that type. If the function
9865 // is a member function with one parameter (which shall be of type
9866 // int) or a non-member function with two parameters (the second
9867 // of which shall be of type int), it defines the postfix
9868 // increment operator ++ for objects of that type.
9869 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9870 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9871 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009872 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009873 ParamIsInt = BT->getKind() == BuiltinType::Int;
9874
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009875 if (!ParamIsInt)
9876 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009877 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009878 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009879 }
9880
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009881 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009882}
Chris Lattner5a003a42008-12-17 07:09:26 +00009883
Sean Hunta6c058d2010-01-13 09:01:02 +00009884/// CheckLiteralOperatorDeclaration - Check whether the declaration
9885/// of this literal operator function is well-formed. If so, returns
9886/// false; otherwise, emits appropriate diagnostics and returns true.
9887bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009888 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009889 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9890 << FnDecl->getDeclName();
9891 return true;
9892 }
9893
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009894 if (FnDecl->isExternC()) {
9895 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9896 return true;
9897 }
9898
Sean Hunta6c058d2010-01-13 09:01:02 +00009899 bool Valid = false;
9900
Richard Smith36f5cfe2012-03-09 08:00:36 +00009901 // This might be the definition of a literal operator template.
9902 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9903 // This might be a specialization of a literal operator template.
9904 if (!TpDecl)
9905 TpDecl = FnDecl->getPrimaryTemplate();
9906
Sean Hunt216c2782010-04-07 23:11:06 +00009907 // template <char...> type operator "" name() is the only valid template
9908 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009909 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009910 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009911 // Must have only one template parameter
9912 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9913 if (Params->size() == 1) {
9914 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009915 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009916
Sean Hunt216c2782010-04-07 23:11:06 +00009917 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009918 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9919 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9920 Valid = true;
9921 }
9922 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009923 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009924 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009925 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9926
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009927 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009928
Sean Hunt30019c02010-04-07 22:57:35 +00009929 // unsigned long long int, long double, and any character type are allowed
9930 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009931 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9932 Context.hasSameType(T, Context.LongDoubleTy) ||
9933 Context.hasSameType(T, Context.CharTy) ||
9934 Context.hasSameType(T, Context.WCharTy) ||
9935 Context.hasSameType(T, Context.Char16Ty) ||
9936 Context.hasSameType(T, Context.Char32Ty)) {
9937 if (++Param == FnDecl->param_end())
9938 Valid = true;
9939 goto FinishedParams;
9940 }
9941
Sean Hunt30019c02010-04-07 22:57:35 +00009942 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009943 const PointerType *PT = T->getAs<PointerType>();
9944 if (!PT)
9945 goto FinishedParams;
9946 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009947 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009948 goto FinishedParams;
9949 T = T.getUnqualifiedType();
9950
9951 // Move on to the second parameter;
9952 ++Param;
9953
9954 // If there is no second parameter, the first must be a const char *
9955 if (Param == FnDecl->param_end()) {
9956 if (Context.hasSameType(T, Context.CharTy))
9957 Valid = true;
9958 goto FinishedParams;
9959 }
9960
9961 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9962 // are allowed as the first parameter to a two-parameter function
9963 if (!(Context.hasSameType(T, Context.CharTy) ||
9964 Context.hasSameType(T, Context.WCharTy) ||
9965 Context.hasSameType(T, Context.Char16Ty) ||
9966 Context.hasSameType(T, Context.Char32Ty)))
9967 goto FinishedParams;
9968
9969 // The second and final parameter must be an std::size_t
9970 T = (*Param)->getType().getUnqualifiedType();
9971 if (Context.hasSameType(T, Context.getSizeType()) &&
9972 ++Param == FnDecl->param_end())
9973 Valid = true;
9974 }
9975
9976 // FIXME: This diagnostic is absolutely terrible.
9977FinishedParams:
9978 if (!Valid) {
9979 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9980 << FnDecl->getDeclName();
9981 return true;
9982 }
9983
Richard Smitha9e88b22012-03-09 08:16:22 +00009984 // A parameter-declaration-clause containing a default argument is not
9985 // equivalent to any of the permitted forms.
9986 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9987 ParamEnd = FnDecl->param_end();
9988 Param != ParamEnd; ++Param) {
9989 if ((*Param)->hasDefaultArg()) {
9990 Diag((*Param)->getDefaultArgRange().getBegin(),
9991 diag::err_literal_operator_default_argument)
9992 << (*Param)->getDefaultArgRange();
9993 break;
9994 }
9995 }
9996
Richard Smith2fb4ae32012-03-08 02:39:21 +00009997 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009998 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9999 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010000 // C++11 [usrlit.suffix]p1:
10001 // Literal suffix identifiers that do not start with an underscore
10002 // are reserved for future standardization.
10003 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010004 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010005
Sean Hunta6c058d2010-01-13 09:01:02 +000010006 return false;
10007}
10008
Douglas Gregor074149e2009-01-05 19:45:36 +000010009/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10010/// linkage specification, including the language and (if present)
10011/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10012/// the location of the language string literal, which is provided
10013/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10014/// the '{' brace. Otherwise, this linkage specification does not
10015/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010016Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10017 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010018 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010019 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010020 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010021 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010022 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010023 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010024 Language = LinkageSpecDecl::lang_cxx;
10025 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010026 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010027 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010028 }
Mike Stump1eb44332009-09-09 15:08:12 +000010029
Chris Lattnercc98eac2008-12-17 07:13:27 +000010030 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010031
Douglas Gregor074149e2009-01-05 19:45:36 +000010032 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010033 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010034 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010035 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010036 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010037}
10038
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010039/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010040/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10041/// valid, it's the position of the closing '}' brace in a linkage
10042/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010043Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010044 Decl *LinkageSpec,
10045 SourceLocation RBraceLoc) {
10046 if (LinkageSpec) {
10047 if (RBraceLoc.isValid()) {
10048 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10049 LSDecl->setRBraceLoc(RBraceLoc);
10050 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010051 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010052 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010053 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010054}
10055
Douglas Gregord308e622009-05-18 20:51:54 +000010056/// \brief Perform semantic analysis for the variable declaration that
10057/// occurs within a C++ catch clause, returning the newly-created
10058/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010059VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010060 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010061 SourceLocation StartLoc,
10062 SourceLocation Loc,
10063 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010064 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010065 QualType ExDeclType = TInfo->getType();
10066
Sebastian Redl4b07b292008-12-22 19:15:10 +000010067 // Arrays and functions decay.
10068 if (ExDeclType->isArrayType())
10069 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10070 else if (ExDeclType->isFunctionType())
10071 ExDeclType = Context.getPointerType(ExDeclType);
10072
10073 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10074 // The exception-declaration shall not denote a pointer or reference to an
10075 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010076 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010077 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010078 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010079 Invalid = true;
10080 }
Douglas Gregord308e622009-05-18 20:51:54 +000010081
Sebastian Redl4b07b292008-12-22 19:15:10 +000010082 QualType BaseType = ExDeclType;
10083 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010084 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010085 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010086 BaseType = Ptr->getPointeeType();
10087 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010088 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010089 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010090 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010091 BaseType = Ref->getPointeeType();
10092 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010093 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010094 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010095 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010096 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010097 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010098
Mike Stump1eb44332009-09-09 15:08:12 +000010099 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010100 RequireNonAbstractType(Loc, ExDeclType,
10101 diag::err_abstract_type_in_decl,
10102 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010103 Invalid = true;
10104
John McCall5a180392010-07-24 00:37:23 +000010105 // Only the non-fragile NeXT runtime currently supports C++ catches
10106 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010107 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010108 QualType T = ExDeclType;
10109 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10110 T = RT->getPointeeType();
10111
10112 if (T->isObjCObjectType()) {
10113 Diag(Loc, diag::err_objc_object_catch);
10114 Invalid = true;
10115 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010116 // FIXME: should this be a test for macosx-fragile specifically?
10117 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010118 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010119 }
10120 }
10121
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010122 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10123 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010124 ExDecl->setExceptionVariable(true);
10125
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010126 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010127 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010128 Invalid = true;
10129
Douglas Gregorc41b8782011-07-06 18:14:43 +000010130 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010131 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +000010132 // C++ [except.handle]p16:
10133 // The object declared in an exception-declaration or, if the
10134 // exception-declaration does not specify a name, a temporary (12.2) is
10135 // copy-initialized (8.5) from the exception object. [...]
10136 // The object is destroyed when the handler exits, after the destruction
10137 // of any automatic objects initialized within the handler.
10138 //
10139 // We just pretend to initialize the object with itself, then make sure
10140 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010141 QualType initType = ExDeclType;
10142
10143 InitializedEntity entity =
10144 InitializedEntity::InitializeVariable(ExDecl);
10145 InitializationKind initKind =
10146 InitializationKind::CreateCopy(Loc, SourceLocation());
10147
10148 Expr *opaqueValue =
10149 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10150 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10151 ExprResult result = sequence.Perform(*this, entity, initKind,
10152 MultiExprArg(&opaqueValue, 1));
10153 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010154 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010155 else {
10156 // If the constructor used was non-trivial, set this as the
10157 // "initializer".
10158 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10159 if (!construct->getConstructor()->isTrivial()) {
10160 Expr *init = MaybeCreateExprWithCleanups(construct);
10161 ExDecl->setInit(init);
10162 }
10163
10164 // And make sure it's destructable.
10165 FinalizeVarWithDestructor(ExDecl, recordType);
10166 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010167 }
10168 }
10169
Douglas Gregord308e622009-05-18 20:51:54 +000010170 if (Invalid)
10171 ExDecl->setInvalidDecl();
10172
10173 return ExDecl;
10174}
10175
10176/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10177/// handler.
John McCalld226f652010-08-21 09:40:31 +000010178Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010179 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010180 bool Invalid = D.isInvalidType();
10181
10182 // Check for unexpanded parameter packs.
10183 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10184 UPPC_ExceptionType)) {
10185 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10186 D.getIdentifierLoc());
10187 Invalid = true;
10188 }
10189
Sebastian Redl4b07b292008-12-22 19:15:10 +000010190 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010191 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010192 LookupOrdinaryName,
10193 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010194 // The scope should be freshly made just for us. There is just no way
10195 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010196 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010197 if (PrevDecl->isTemplateParameter()) {
10198 // Maybe we will complain about the shadowed template parameter.
10199 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010200 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010201 }
10202 }
10203
Chris Lattnereaaebc72009-04-25 08:06:05 +000010204 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010205 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10206 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010207 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010208 }
10209
Douglas Gregor83cb9422010-09-09 17:09:21 +000010210 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010211 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010212 D.getIdentifierLoc(),
10213 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010214 if (Invalid)
10215 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010216
Sebastian Redl4b07b292008-12-22 19:15:10 +000010217 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010218 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010219 PushOnScopeChains(ExDecl, S);
10220 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010221 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010222
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010223 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010224 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010225}
Anders Carlssonfb311762009-03-14 00:25:26 +000010226
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010227Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010228 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010229 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010230 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010231 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010232
Richard Smithe3f470a2012-07-11 22:37:56 +000010233 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10234 return 0;
10235
10236 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10237 AssertMessage, RParenLoc, false);
10238}
10239
10240Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10241 Expr *AssertExpr,
10242 StringLiteral *AssertMessage,
10243 SourceLocation RParenLoc,
10244 bool Failed) {
10245 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10246 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010247 // In a static_assert-declaration, the constant-expression shall be a
10248 // constant expression that can be contextually converted to bool.
10249 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10250 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010251 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010252
Richard Smithdaaefc52011-12-14 23:32:26 +000010253 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010254 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010255 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010256 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010257 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010258
Richard Smithe3f470a2012-07-11 22:37:56 +000010259 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010260 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010261 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010262 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010263 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010264 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010265 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010266 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010267 }
Mike Stump1eb44332009-09-09 15:08:12 +000010268
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010269 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010270 AssertExpr, AssertMessage, RParenLoc,
10271 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010272
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010273 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010274 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010275}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010276
Douglas Gregor1d869352010-04-07 16:53:43 +000010277/// \brief Perform semantic analysis of the given friend type declaration.
10278///
10279/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010280FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010281 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010282 TypeSourceInfo *TSInfo) {
10283 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10284
10285 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010286 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010287
Richard Smith6b130222011-10-18 21:39:00 +000010288 // C++03 [class.friend]p2:
10289 // An elaborated-type-specifier shall be used in a friend declaration
10290 // for a class.*
10291 //
10292 // * The class-key of the elaborated-type-specifier is required.
10293 if (!ActiveTemplateInstantiations.empty()) {
10294 // Do not complain about the form of friend template types during
10295 // template instantiation; we will already have complained when the
10296 // template was declared.
10297 } else if (!T->isElaboratedTypeSpecifier()) {
10298 // If we evaluated the type to a record type, suggest putting
10299 // a tag in front.
10300 if (const RecordType *RT = T->getAs<RecordType>()) {
10301 RecordDecl *RD = RT->getDecl();
10302
10303 std::string InsertionText = std::string(" ") + RD->getKindName();
10304
10305 Diag(TypeRange.getBegin(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010306 getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +000010307 diag::warn_cxx98_compat_unelaborated_friend_type :
10308 diag::ext_unelaborated_friend_type)
10309 << (unsigned) RD->getTagKind()
10310 << T
10311 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10312 InsertionText);
10313 } else {
10314 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010315 getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +000010316 diag::warn_cxx98_compat_nonclass_type_friend :
10317 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010318 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010319 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010320 }
Richard Smith6b130222011-10-18 21:39:00 +000010321 } else if (T->getAs<EnumType>()) {
10322 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010323 getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +000010324 diag::warn_cxx98_compat_enum_friend :
10325 diag::ext_enum_friend)
10326 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010327 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010328 }
10329
Richard Smithd6f80da2012-09-20 01:31:00 +000010330 // C++11 [class.friend]p3:
10331 // A friend declaration that does not declare a function shall have one
10332 // of the following forms:
10333 // friend elaborated-type-specifier ;
10334 // friend simple-type-specifier ;
10335 // friend typename-specifier ;
Richard Smith80ad52f2013-01-02 11:42:31 +000010336 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
Richard Smithd6f80da2012-09-20 01:31:00 +000010337 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10338
Douglas Gregor06245bf2010-04-07 17:57:12 +000010339 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010340 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010341 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010342 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010343}
10344
John McCall9a34edb2010-10-19 01:40:49 +000010345/// Handle a friend tag declaration where the scope specifier was
10346/// templated.
10347Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10348 unsigned TagSpec, SourceLocation TagLoc,
10349 CXXScopeSpec &SS,
10350 IdentifierInfo *Name, SourceLocation NameLoc,
10351 AttributeList *Attr,
10352 MultiTemplateParamsArg TempParamLists) {
10353 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10354
10355 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010356 bool Invalid = false;
10357
10358 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010359 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010360 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010361 TempParamLists.size(),
10362 /*friend*/ true,
10363 isExplicitSpecialization,
10364 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010365 if (TemplateParams->size() > 0) {
10366 // This is a declaration of a class template.
10367 if (Invalid)
10368 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010369
Eric Christopher4110e132011-07-21 05:34:24 +000010370 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10371 SS, Name, NameLoc, Attr,
10372 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010373 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010374 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010375 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010376 } else {
10377 // The "template<>" header is extraneous.
10378 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10379 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10380 isExplicitSpecialization = true;
10381 }
10382 }
10383
10384 if (Invalid) return 0;
10385
John McCall9a34edb2010-10-19 01:40:49 +000010386 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010387 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010388 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010389 isAllExplicitSpecializations = false;
10390 break;
10391 }
10392 }
10393
10394 // FIXME: don't ignore attributes.
10395
10396 // If it's explicit specializations all the way down, just forget
10397 // about the template header and build an appropriate non-templated
10398 // friend. TODO: for source fidelity, remember the headers.
10399 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010400 if (SS.isEmpty()) {
10401 bool Owned = false;
10402 bool IsDependent = false;
10403 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10404 Attr, AS_public,
10405 /*ModulePrivateLoc=*/SourceLocation(),
10406 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010407 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010408 /*ScopedEnumUsesClassTag=*/false,
10409 /*UnderlyingType=*/TypeResult());
10410 }
10411
Douglas Gregor2494dd02011-03-01 01:34:45 +000010412 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010413 ElaboratedTypeKeyword Keyword
10414 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010415 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010416 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010417 if (T.isNull())
10418 return 0;
10419
10420 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10421 if (isa<DependentNameType>(T)) {
10422 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010423 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010424 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010425 TL.setNameLoc(NameLoc);
10426 } else {
10427 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010428 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010429 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010430 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10431 }
10432
10433 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10434 TSI, FriendLoc);
10435 Friend->setAccess(AS_public);
10436 CurContext->addDecl(Friend);
10437 return Friend;
10438 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010439
10440 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10441
10442
John McCall9a34edb2010-10-19 01:40:49 +000010443
10444 // Handle the case of a templated-scope friend class. e.g.
10445 // template <class T> class A<T>::B;
10446 // FIXME: we don't support these right now.
10447 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10448 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10449 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10450 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010451 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010452 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010453 TL.setNameLoc(NameLoc);
10454
10455 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10456 TSI, FriendLoc);
10457 Friend->setAccess(AS_public);
10458 Friend->setUnsupportedFriend(true);
10459 CurContext->addDecl(Friend);
10460 return Friend;
10461}
10462
10463
John McCalldd4a3b02009-09-16 22:47:08 +000010464/// Handle a friend type declaration. This works in tandem with
10465/// ActOnTag.
10466///
10467/// Notes on friend class templates:
10468///
10469/// We generally treat friend class declarations as if they were
10470/// declaring a class. So, for example, the elaborated type specifier
10471/// in a friend declaration is required to obey the restrictions of a
10472/// class-head (i.e. no typedefs in the scope chain), template
10473/// parameters are required to match up with simple template-ids, &c.
10474/// However, unlike when declaring a template specialization, it's
10475/// okay to refer to a template specialization without an empty
10476/// template parameter declaration, e.g.
10477/// friend class A<T>::B<unsigned>;
10478/// We permit this as a special case; if there are any template
10479/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010480/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010481Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010482 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010483 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010484
10485 assert(DS.isFriendSpecified());
10486 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10487
John McCalldd4a3b02009-09-16 22:47:08 +000010488 // Try to convert the decl specifier to a type. This works for
10489 // friend templates because ActOnTag never produces a ClassTemplateDecl
10490 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010491 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010492 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10493 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010494 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010495 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010496
Douglas Gregor6ccab972010-12-16 01:14:37 +000010497 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10498 return 0;
10499
John McCalldd4a3b02009-09-16 22:47:08 +000010500 // This is definitely an error in C++98. It's probably meant to
10501 // be forbidden in C++0x, too, but the specification is just
10502 // poorly written.
10503 //
10504 // The problem is with declarations like the following:
10505 // template <T> friend A<T>::foo;
10506 // where deciding whether a class C is a friend or not now hinges
10507 // on whether there exists an instantiation of A that causes
10508 // 'foo' to equal C. There are restrictions on class-heads
10509 // (which we declare (by fiat) elaborated friend declarations to
10510 // be) that makes this tractable.
10511 //
10512 // FIXME: handle "template <> friend class A<T>;", which
10513 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010514 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010515 Diag(Loc, diag::err_tagless_friend_type_template)
10516 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010517 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010518 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010519
John McCall02cace72009-08-28 07:59:38 +000010520 // C++98 [class.friend]p1: A friend of a class is a function
10521 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010522 // This is fixed in DR77, which just barely didn't make the C++03
10523 // deadline. It's also a very silly restriction that seriously
10524 // affects inner classes and which nobody else seems to implement;
10525 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010526 //
10527 // But note that we could warn about it: it's always useless to
10528 // friend one of your own members (it's not, however, worthless to
10529 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010530
John McCalldd4a3b02009-09-16 22:47:08 +000010531 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010532 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010533 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010534 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010535 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010536 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010537 DS.getFriendSpecLoc());
10538 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010539 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010540
10541 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010542 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010543
John McCalldd4a3b02009-09-16 22:47:08 +000010544 D->setAccess(AS_public);
10545 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010546
John McCalld226f652010-08-21 09:40:31 +000010547 return D;
John McCall02cace72009-08-28 07:59:38 +000010548}
10549
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010550NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10551 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010552 const DeclSpec &DS = D.getDeclSpec();
10553
10554 assert(DS.isFriendSpecified());
10555 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10556
10557 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010558 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010559
10560 // C++ [class.friend]p1
10561 // A friend of a class is a function or class....
10562 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010563 // It *doesn't* see through dependent types, which is correct
10564 // according to [temp.arg.type]p3:
10565 // If a declaration acquires a function type through a
10566 // type dependent on a template-parameter and this causes
10567 // a declaration that does not use the syntactic form of a
10568 // function declarator to have a function type, the program
10569 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010570 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010571 Diag(Loc, diag::err_unexpected_friend);
10572
10573 // It might be worthwhile to try to recover by creating an
10574 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010575 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010576 }
10577
10578 // C++ [namespace.memdef]p3
10579 // - If a friend declaration in a non-local class first declares a
10580 // class or function, the friend class or function is a member
10581 // of the innermost enclosing namespace.
10582 // - The name of the friend is not found by simple name lookup
10583 // until a matching declaration is provided in that namespace
10584 // scope (either before or after the class declaration granting
10585 // friendship).
10586 // - If a friend function is called, its name may be found by the
10587 // name lookup that considers functions from namespaces and
10588 // classes associated with the types of the function arguments.
10589 // - When looking for a prior declaration of a class or a function
10590 // declared as a friend, scopes outside the innermost enclosing
10591 // namespace scope are not considered.
10592
John McCall337ec3d2010-10-12 23:13:28 +000010593 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010594 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10595 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010596 assert(Name);
10597
Douglas Gregor6ccab972010-12-16 01:14:37 +000010598 // Check for unexpanded parameter packs.
10599 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10600 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10601 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10602 return 0;
10603
John McCall67d1a672009-08-06 02:15:43 +000010604 // The context we found the declaration in, or in which we should
10605 // create the declaration.
10606 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010607 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010608 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010609 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010610
John McCall337ec3d2010-10-12 23:13:28 +000010611 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010612
John McCall337ec3d2010-10-12 23:13:28 +000010613 // There are four cases here.
10614 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010615 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010616 // there as appropriate.
10617 // Recover from invalid scope qualifiers as if they just weren't there.
10618 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010619 // C++0x [namespace.memdef]p3:
10620 // If the name in a friend declaration is neither qualified nor
10621 // a template-id and the declaration is a function or an
10622 // elaborated-type-specifier, the lookup to determine whether
10623 // the entity has been previously declared shall not consider
10624 // any scopes outside the innermost enclosing namespace.
10625 // C++0x [class.friend]p11:
10626 // If a friend declaration appears in a local class and the name
10627 // specified is an unqualified name, a prior declaration is
10628 // looked up without considering scopes that are outside the
10629 // innermost enclosing non-class scope. For a friend function
10630 // declaration, if there is no prior declaration, the program is
10631 // ill-formed.
10632 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010633 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010634
John McCall29ae6e52010-10-13 05:45:15 +000010635 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010636 DC = CurContext;
10637 while (true) {
10638 // Skip class contexts. If someone can cite chapter and verse
10639 // for this behavior, that would be nice --- it's what GCC and
10640 // EDG do, and it seems like a reasonable intent, but the spec
10641 // really only says that checks for unqualified existing
10642 // declarations should stop at the nearest enclosing namespace,
10643 // not that they should only consider the nearest enclosing
10644 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010645 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010646 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010647
John McCall68263142009-11-18 22:49:29 +000010648 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010649
10650 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010651 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010652 break;
John McCall29ae6e52010-10-13 05:45:15 +000010653
John McCall8a407372010-10-14 22:22:28 +000010654 if (isTemplateId) {
10655 if (isa<TranslationUnitDecl>(DC)) break;
10656 } else {
10657 if (DC->isFileContext()) break;
10658 }
John McCall67d1a672009-08-06 02:15:43 +000010659 DC = DC->getParent();
10660 }
10661
10662 // C++ [class.friend]p1: A friend of a class is a function or
10663 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010664 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010665 // Most C++ 98 compilers do seem to give an error here, so
10666 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010667 if (!Previous.empty() && DC->Equals(CurContext))
10668 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010669 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010670 diag::warn_cxx98_compat_friend_is_member :
10671 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010672
John McCall380aaa42010-10-13 06:22:15 +000010673 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010674
Douglas Gregor883af832011-10-10 01:11:59 +000010675 // C++ [class.friend]p6:
10676 // A function can be defined in a friend declaration of a class if and
10677 // only if the class is a non-local class (9.8), the function name is
10678 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010679 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010680 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10681 }
10682
John McCall337ec3d2010-10-12 23:13:28 +000010683 // - There's a non-dependent scope specifier, in which case we
10684 // compute it and do a previous lookup there for a function
10685 // or function template.
10686 } else if (!SS.getScopeRep()->isDependent()) {
10687 DC = computeDeclContext(SS);
10688 if (!DC) return 0;
10689
10690 if (RequireCompleteDeclContext(SS, DC)) return 0;
10691
10692 LookupQualifiedName(Previous, DC);
10693
10694 // Ignore things found implicitly in the wrong scope.
10695 // TODO: better diagnostics for this case. Suggesting the right
10696 // qualified scope would be nice...
10697 LookupResult::Filter F = Previous.makeFilter();
10698 while (F.hasNext()) {
10699 NamedDecl *D = F.next();
10700 if (!DC->InEnclosingNamespaceSetOf(
10701 D->getDeclContext()->getRedeclContext()))
10702 F.erase();
10703 }
10704 F.done();
10705
10706 if (Previous.empty()) {
10707 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010708 Diag(Loc, diag::err_qualified_friend_not_found)
10709 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010710 return 0;
10711 }
10712
10713 // C++ [class.friend]p1: A friend of a class is a function or
10714 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010715 if (DC->Equals(CurContext))
10716 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010717 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010718 diag::warn_cxx98_compat_friend_is_member :
10719 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010720
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010721 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010722 // C++ [class.friend]p6:
10723 // A function can be defined in a friend declaration of a class if and
10724 // only if the class is a non-local class (9.8), the function name is
10725 // unqualified, and the function has namespace scope.
10726 SemaDiagnosticBuilder DB
10727 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10728
10729 DB << SS.getScopeRep();
10730 if (DC->isFileContext())
10731 DB << FixItHint::CreateRemoval(SS.getRange());
10732 SS.clear();
10733 }
John McCall337ec3d2010-10-12 23:13:28 +000010734
10735 // - There's a scope specifier that does not match any template
10736 // parameter lists, in which case we use some arbitrary context,
10737 // create a method or method template, and wait for instantiation.
10738 // - There's a scope specifier that does match some template
10739 // parameter lists, which we don't handle right now.
10740 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010741 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010742 // C++ [class.friend]p6:
10743 // A function can be defined in a friend declaration of a class if and
10744 // only if the class is a non-local class (9.8), the function name is
10745 // unqualified, and the function has namespace scope.
10746 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10747 << SS.getScopeRep();
10748 }
10749
John McCall337ec3d2010-10-12 23:13:28 +000010750 DC = CurContext;
10751 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010752 }
Douglas Gregor883af832011-10-10 01:11:59 +000010753
John McCall29ae6e52010-10-13 05:45:15 +000010754 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010755 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010756 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10757 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10758 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010759 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010760 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10761 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010762 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010763 }
John McCall67d1a672009-08-06 02:15:43 +000010764 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010765
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010766 // FIXME: This is an egregious hack to cope with cases where the scope stack
10767 // does not contain the declaration context, i.e., in an out-of-line
10768 // definition of a class.
10769 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10770 if (!DCScope) {
10771 FakeDCScope.setEntity(DC);
10772 DCScope = &FakeDCScope;
10773 }
10774
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010775 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010776 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010777 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010778 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010779
Douglas Gregor182ddf02009-09-28 00:08:27 +000010780 assert(ND->getDeclContext() == DC);
10781 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010782
John McCallab88d972009-08-31 22:39:49 +000010783 // Add the function declaration to the appropriate lookup tables,
10784 // adjusting the redeclarations list as necessary. We don't
10785 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010786 //
John McCallab88d972009-08-31 22:39:49 +000010787 // Also update the scope-based lookup if the target context's
10788 // lookup context is in lexical scope.
10789 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010790 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010791 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010792 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010793 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010794 }
John McCall02cace72009-08-28 07:59:38 +000010795
10796 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010797 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010798 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010799 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010800 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010801
John McCall1f2e1a92012-08-10 03:15:35 +000010802 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010803 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010804 } else {
10805 if (DC->isRecord()) CheckFriendAccess(ND);
10806
John McCall6102ca12010-10-16 06:59:13 +000010807 FunctionDecl *FD;
10808 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10809 FD = FTD->getTemplatedDecl();
10810 else
10811 FD = cast<FunctionDecl>(ND);
10812
10813 // Mark templated-scope function declarations as unsupported.
10814 if (FD->getNumTemplateParameterLists())
10815 FrD->setUnsupportedFriend(true);
10816 }
John McCall337ec3d2010-10-12 23:13:28 +000010817
John McCalld226f652010-08-21 09:40:31 +000010818 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010819}
10820
John McCalld226f652010-08-21 09:40:31 +000010821void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10822 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010823
Sebastian Redl50de12f2009-03-24 22:27:57 +000010824 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10825 if (!Fn) {
10826 Diag(DelLoc, diag::err_deleted_non_function);
10827 return;
10828 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010829 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010830 // Don't consider the implicit declaration we generate for explicit
10831 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010832 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10833 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010834 Diag(DelLoc, diag::err_deleted_decl_not_first);
10835 Diag(Prev->getLocation(), diag::note_previous_declaration);
10836 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010837 // If the declaration wasn't the first, we delete the function anyway for
10838 // recovery.
10839 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010840 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010841}
Sebastian Redl13e88542009-04-27 21:33:24 +000010842
Sean Hunte4246a62011-05-12 06:15:49 +000010843void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10844 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10845
10846 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010847 if (MD->getParent()->isDependentType()) {
10848 MD->setDefaulted();
10849 MD->setExplicitlyDefaulted();
10850 return;
10851 }
10852
Sean Hunte4246a62011-05-12 06:15:49 +000010853 CXXSpecialMember Member = getSpecialMember(MD);
10854 if (Member == CXXInvalid) {
10855 Diag(DefaultLoc, diag::err_default_special_members);
10856 return;
10857 }
10858
10859 MD->setDefaulted();
10860 MD->setExplicitlyDefaulted();
10861
Sean Huntcd10dec2011-05-23 23:14:04 +000010862 // If this definition appears within the record, do the checking when
10863 // the record is complete.
10864 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010865 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010866 // Find the uninstantiated declaration that actually had the '= default'
10867 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010868 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010869
10870 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010871 return;
10872
Richard Smithb9d0b762012-07-27 04:22:15 +000010873 CheckExplicitlyDefaultedSpecialMember(MD);
10874
Richard Smith1d28caf2012-12-11 01:14:52 +000010875 // The exception specification is needed because we are defining the
10876 // function.
10877 ResolveExceptionSpec(DefaultLoc,
10878 MD->getType()->castAs<FunctionProtoType>());
10879
Sean Hunte4246a62011-05-12 06:15:49 +000010880 switch (Member) {
10881 case CXXDefaultConstructor: {
10882 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010883 if (!CD->isInvalidDecl())
10884 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10885 break;
10886 }
10887
10888 case CXXCopyConstructor: {
10889 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010890 if (!CD->isInvalidDecl())
10891 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010892 break;
10893 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010894
Sean Hunt2b188082011-05-14 05:23:28 +000010895 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010896 if (!MD->isInvalidDecl())
10897 DefineImplicitCopyAssignment(DefaultLoc, MD);
10898 break;
10899 }
10900
Sean Huntcb45a0f2011-05-12 22:46:25 +000010901 case CXXDestructor: {
10902 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010903 if (!DD->isInvalidDecl())
10904 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010905 break;
10906 }
10907
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010908 case CXXMoveConstructor: {
10909 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010910 if (!CD->isInvalidDecl())
10911 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010912 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010913 }
Sean Hunt82713172011-05-25 23:16:36 +000010914
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010915 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010916 if (!MD->isInvalidDecl())
10917 DefineImplicitMoveAssignment(DefaultLoc, MD);
10918 break;
10919 }
10920
10921 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010922 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010923 }
10924 } else {
10925 Diag(DefaultLoc, diag::err_default_special_members);
10926 }
10927}
10928
Sebastian Redl13e88542009-04-27 21:33:24 +000010929static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010930 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010931 Stmt *SubStmt = *CI;
10932 if (!SubStmt)
10933 continue;
10934 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010935 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010936 diag::err_return_in_constructor_handler);
10937 if (!isa<Expr>(SubStmt))
10938 SearchForReturnInStmt(Self, SubStmt);
10939 }
10940}
10941
10942void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10943 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10944 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10945 SearchForReturnInStmt(*this, Handler);
10946 }
10947}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010948
Aaron Ballmanfff32482012-12-09 17:45:41 +000010949bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
10950 const CXXMethodDecl *Old) {
10951 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
10952 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
10953
10954 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
10955
10956 // If the calling conventions match, everything is fine
10957 if (NewCC == OldCC)
10958 return false;
10959
10960 // If either of the calling conventions are set to "default", we need to pick
10961 // something more sensible based on the target. This supports code where the
10962 // one method explicitly sets thiscall, and another has no explicit calling
10963 // convention.
10964 CallingConv Default =
10965 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
10966 if (NewCC == CC_Default)
10967 NewCC = Default;
10968 if (OldCC == CC_Default)
10969 OldCC = Default;
10970
10971 // If the calling conventions still don't match, then report the error
10972 if (NewCC != OldCC) {
10973 Diag(New->getLocation(),
10974 diag::err_conflicting_overriding_cc_attributes)
10975 << New->getDeclName() << New->getType() << Old->getType();
10976 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10977 return true;
10978 }
10979
10980 return false;
10981}
10982
Mike Stump1eb44332009-09-09 15:08:12 +000010983bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010984 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010985 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10986 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010987
Chandler Carruth73857792010-02-15 11:53:20 +000010988 if (Context.hasSameType(NewTy, OldTy) ||
10989 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010990 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010991
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010992 // Check if the return types are covariant
10993 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010994
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010995 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010996 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10997 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010998 NewClassTy = NewPT->getPointeeType();
10999 OldClassTy = OldPT->getPointeeType();
11000 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011001 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11002 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11003 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11004 NewClassTy = NewRT->getPointeeType();
11005 OldClassTy = OldRT->getPointeeType();
11006 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011007 }
11008 }
Mike Stump1eb44332009-09-09 15:08:12 +000011009
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011010 // The return types aren't either both pointers or references to a class type.
11011 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011012 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011013 diag::err_different_return_type_for_overriding_virtual_function)
11014 << New->getDeclName() << NewTy << OldTy;
11015 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011016
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011017 return true;
11018 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011019
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011020 // C++ [class.virtual]p6:
11021 // If the return type of D::f differs from the return type of B::f, the
11022 // class type in the return type of D::f shall be complete at the point of
11023 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011024 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11025 if (!RT->isBeingDefined() &&
11026 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011027 diag::err_covariant_return_incomplete,
11028 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011029 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011030 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011031
Douglas Gregora4923eb2009-11-16 21:35:15 +000011032 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011033 // Check if the new class derives from the old class.
11034 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11035 Diag(New->getLocation(),
11036 diag::err_covariant_return_not_derived)
11037 << New->getDeclName() << NewTy << OldTy;
11038 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11039 return true;
11040 }
Mike Stump1eb44332009-09-09 15:08:12 +000011041
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011042 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011043 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011044 diag::err_covariant_return_inaccessible_base,
11045 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11046 // FIXME: Should this point to the return type?
11047 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011048 // FIXME: this note won't trigger for delayed access control
11049 // diagnostics, and it's impossible to get an undelayed error
11050 // here from access control during the original parse because
11051 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011052 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11053 return true;
11054 }
11055 }
Mike Stump1eb44332009-09-09 15:08:12 +000011056
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011057 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011058 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011059 Diag(New->getLocation(),
11060 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011061 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011062 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11063 return true;
11064 };
Mike Stump1eb44332009-09-09 15:08:12 +000011065
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011066
11067 // The new class type must have the same or less qualifiers as the old type.
11068 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11069 Diag(New->getLocation(),
11070 diag::err_covariant_return_type_class_type_more_qualified)
11071 << New->getDeclName() << NewTy << OldTy;
11072 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11073 return true;
11074 };
Mike Stump1eb44332009-09-09 15:08:12 +000011075
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011076 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011077}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011078
Douglas Gregor4ba31362009-12-01 17:24:26 +000011079/// \brief Mark the given method pure.
11080///
11081/// \param Method the method to be marked pure.
11082///
11083/// \param InitRange the source range that covers the "0" initializer.
11084bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011085 SourceLocation EndLoc = InitRange.getEnd();
11086 if (EndLoc.isValid())
11087 Method->setRangeEnd(EndLoc);
11088
Douglas Gregor4ba31362009-12-01 17:24:26 +000011089 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11090 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011091 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011092 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011093
11094 if (!Method->isInvalidDecl())
11095 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11096 << Method->getDeclName() << InitRange;
11097 return true;
11098}
11099
Douglas Gregor552e2992012-02-21 02:22:07 +000011100/// \brief Determine whether the given declaration is a static data member.
11101static bool isStaticDataMember(Decl *D) {
11102 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11103 if (!Var)
11104 return false;
11105
11106 return Var->isStaticDataMember();
11107}
John McCall731ad842009-12-19 09:28:58 +000011108/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11109/// an initializer for the out-of-line declaration 'Dcl'. The scope
11110/// is a fresh scope pushed for just this purpose.
11111///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011112/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11113/// static data member of class X, names should be looked up in the scope of
11114/// class X.
John McCalld226f652010-08-21 09:40:31 +000011115void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011116 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011117 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011118
John McCall731ad842009-12-19 09:28:58 +000011119 // We should only get called for declarations with scope specifiers, like:
11120 // int foo::bar;
11121 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011122 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011123
11124 // If we are parsing the initializer for a static data member, push a
11125 // new expression evaluation context that is associated with this static
11126 // data member.
11127 if (isStaticDataMember(D))
11128 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011129}
11130
11131/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011132/// initializer for the out-of-line declaration 'D'.
11133void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011134 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011135 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011136
Douglas Gregor552e2992012-02-21 02:22:07 +000011137 if (isStaticDataMember(D))
11138 PopExpressionEvaluationContext();
11139
John McCall731ad842009-12-19 09:28:58 +000011140 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011141 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011142}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011143
11144/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11145/// C++ if/switch/while/for statement.
11146/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011147DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011148 // C++ 6.4p2:
11149 // The declarator shall not specify a function or an array.
11150 // The type-specifier-seq shall not contain typedef and shall not declare a
11151 // new class or enumeration.
11152 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11153 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011154
11155 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011156 if (!Dcl)
11157 return true;
11158
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011159 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11160 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011161 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011162 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011163 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011164
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011165 return Dcl;
11166}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011167
Douglas Gregordfe65432011-07-28 19:11:31 +000011168void Sema::LoadExternalVTableUses() {
11169 if (!ExternalSource)
11170 return;
11171
11172 SmallVector<ExternalVTableUse, 4> VTables;
11173 ExternalSource->ReadUsedVTables(VTables);
11174 SmallVector<VTableUse, 4> NewUses;
11175 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11176 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11177 = VTablesUsed.find(VTables[I].Record);
11178 // Even if a definition wasn't required before, it may be required now.
11179 if (Pos != VTablesUsed.end()) {
11180 if (!Pos->second && VTables[I].DefinitionRequired)
11181 Pos->second = true;
11182 continue;
11183 }
11184
11185 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11186 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11187 }
11188
11189 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11190}
11191
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011192void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11193 bool DefinitionRequired) {
11194 // Ignore any vtable uses in unevaluated operands or for classes that do
11195 // not have a vtable.
11196 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11197 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011198 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011199 return;
11200
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011201 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011202 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011203 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11204 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11205 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11206 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011207 // If we already had an entry, check to see if we are promoting this vtable
11208 // to required a definition. If so, we need to reappend to the VTableUses
11209 // list, since we may have already processed the first entry.
11210 if (DefinitionRequired && !Pos.first->second) {
11211 Pos.first->second = true;
11212 } else {
11213 // Otherwise, we can early exit.
11214 return;
11215 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011216 }
11217
11218 // Local classes need to have their virtual members marked
11219 // immediately. For all other classes, we mark their virtual members
11220 // at the end of the translation unit.
11221 if (Class->isLocalClass())
11222 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011223 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011224 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011225}
11226
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011227bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011228 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011229 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011230 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011231
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011232 // Note: The VTableUses vector could grow as a result of marking
11233 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011234 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011235 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011236 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011237 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011238 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011239 if (!Class)
11240 continue;
11241
11242 SourceLocation Loc = VTableUses[I].second;
11243
Richard Smithb9d0b762012-07-27 04:22:15 +000011244 bool DefineVTable = true;
11245
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011246 // If this class has a key function, but that key function is
11247 // defined in another translation unit, we don't need to emit the
11248 // vtable even though we're using it.
11249 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011250 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011251 switch (KeyFunction->getTemplateSpecializationKind()) {
11252 case TSK_Undeclared:
11253 case TSK_ExplicitSpecialization:
11254 case TSK_ExplicitInstantiationDeclaration:
11255 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011256 DefineVTable = false;
11257 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011258
11259 case TSK_ExplicitInstantiationDefinition:
11260 case TSK_ImplicitInstantiation:
11261 // We will be instantiating the key function.
11262 break;
11263 }
11264 } else if (!KeyFunction) {
11265 // If we have a class with no key function that is the subject
11266 // of an explicit instantiation declaration, suppress the
11267 // vtable; it will live with the explicit instantiation
11268 // definition.
11269 bool IsExplicitInstantiationDeclaration
11270 = Class->getTemplateSpecializationKind()
11271 == TSK_ExplicitInstantiationDeclaration;
11272 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11273 REnd = Class->redecls_end();
11274 R != REnd; ++R) {
11275 TemplateSpecializationKind TSK
11276 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11277 if (TSK == TSK_ExplicitInstantiationDeclaration)
11278 IsExplicitInstantiationDeclaration = true;
11279 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11280 IsExplicitInstantiationDeclaration = false;
11281 break;
11282 }
11283 }
11284
11285 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011286 DefineVTable = false;
11287 }
11288
11289 // The exception specifications for all virtual members may be needed even
11290 // if we are not providing an authoritative form of the vtable in this TU.
11291 // We may choose to emit it available_externally anyway.
11292 if (!DefineVTable) {
11293 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11294 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011295 }
11296
11297 // Mark all of the virtual members of this class as referenced, so
11298 // that we can build a vtable. Then, tell the AST consumer that a
11299 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011300 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011301 MarkVirtualMembersReferenced(Loc, Class);
11302 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11303 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11304
11305 // Optionally warn if we're emitting a weak vtable.
11306 if (Class->getLinkage() == ExternalLinkage &&
11307 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011308 const FunctionDecl *KeyFunctionDef = 0;
11309 if (!KeyFunction ||
11310 (KeyFunction->hasBody(KeyFunctionDef) &&
11311 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011312 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11313 TSK_ExplicitInstantiationDefinition
11314 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11315 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011316 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011317 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011318 VTableUses.clear();
11319
Douglas Gregor78844032011-04-22 22:25:37 +000011320 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011321}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011322
Richard Smithb9d0b762012-07-27 04:22:15 +000011323void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11324 const CXXRecordDecl *RD) {
11325 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11326 E = RD->method_end(); I != E; ++I)
11327 if ((*I)->isVirtual() && !(*I)->isPure())
11328 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11329}
11330
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011331void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11332 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011333 // Mark all functions which will appear in RD's vtable as used.
11334 CXXFinalOverriderMap FinalOverriders;
11335 RD->getFinalOverriders(FinalOverriders);
11336 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11337 E = FinalOverriders.end();
11338 I != E; ++I) {
11339 for (OverridingMethods::const_iterator OI = I->second.begin(),
11340 OE = I->second.end();
11341 OI != OE; ++OI) {
11342 assert(OI->second.size() > 0 && "no final overrider");
11343 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011344
Richard Smithff817f72012-07-07 06:59:51 +000011345 // C++ [basic.def.odr]p2:
11346 // [...] A virtual member function is used if it is not pure. [...]
11347 if (!Overrider->isPure())
11348 MarkFunctionReferenced(Loc, Overrider);
11349 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011350 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011351
11352 // Only classes that have virtual bases need a VTT.
11353 if (RD->getNumVBases() == 0)
11354 return;
11355
11356 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11357 e = RD->bases_end(); i != e; ++i) {
11358 const CXXRecordDecl *Base =
11359 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011360 if (Base->getNumVBases() == 0)
11361 continue;
11362 MarkVirtualMembersReferenced(Loc, Base);
11363 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011364}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011365
11366/// SetIvarInitializers - This routine builds initialization ASTs for the
11367/// Objective-C implementation whose ivars need be initialized.
11368void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011369 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011370 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011371 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011372 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011373 CollectIvarsToConstructOrDestruct(OID, ivars);
11374 if (ivars.empty())
11375 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011376 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011377 for (unsigned i = 0; i < ivars.size(); i++) {
11378 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011379 if (Field->isInvalidDecl())
11380 continue;
11381
Sean Huntcbb67482011-01-08 20:30:50 +000011382 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011383 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11384 InitializationKind InitKind =
11385 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11386
11387 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011388 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011389 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011390 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011391 // Note, MemberInit could actually come back empty if no initialization
11392 // is required (e.g., because it would call a trivial default constructor)
11393 if (!MemberInit.get() || MemberInit.isInvalid())
11394 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011395
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011396 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011397 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11398 SourceLocation(),
11399 MemberInit.takeAs<Expr>(),
11400 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011401 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011402
11403 // Be sure that the destructor is accessible and is marked as referenced.
11404 if (const RecordType *RecordTy
11405 = Context.getBaseElementType(Field->getType())
11406 ->getAs<RecordType>()) {
11407 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011408 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011409 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011410 CheckDestructorAccess(Field->getLocation(), Destructor,
11411 PDiag(diag::err_access_dtor_ivar)
11412 << Context.getBaseElementType(Field->getType()));
11413 }
11414 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011415 }
11416 ObjCImplementation->setIvarInitializers(Context,
11417 AllToInit.data(), AllToInit.size());
11418 }
11419}
Sean Huntfe57eef2011-05-04 05:57:24 +000011420
Sean Huntebcbe1d2011-05-04 23:29:54 +000011421static
11422void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11423 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11424 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11425 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11426 Sema &S) {
11427 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11428 CE = Current.end();
11429 if (Ctor->isInvalidDecl())
11430 return;
11431
Richard Smitha8eaf002012-08-23 06:16:52 +000011432 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11433
11434 // Target may not be determinable yet, for instance if this is a dependent
11435 // call in an uninstantiated template.
11436 if (Target) {
11437 const FunctionDecl *FNTarget = 0;
11438 (void)Target->hasBody(FNTarget);
11439 Target = const_cast<CXXConstructorDecl*>(
11440 cast_or_null<CXXConstructorDecl>(FNTarget));
11441 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011442
11443 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11444 // Avoid dereferencing a null pointer here.
11445 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11446
11447 if (!Current.insert(Canonical))
11448 return;
11449
11450 // We know that beyond here, we aren't chaining into a cycle.
11451 if (!Target || !Target->isDelegatingConstructor() ||
11452 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11453 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11454 Valid.insert(*CI);
11455 Current.clear();
11456 // We've hit a cycle.
11457 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11458 Current.count(TCanonical)) {
11459 // If we haven't diagnosed this cycle yet, do so now.
11460 if (!Invalid.count(TCanonical)) {
11461 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011462 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011463 << Ctor;
11464
Richard Smitha8eaf002012-08-23 06:16:52 +000011465 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011466 if (TCanonical != Canonical)
11467 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11468
11469 CXXConstructorDecl *C = Target;
11470 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011471 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011472 (void)C->getTargetConstructor()->hasBody(FNTarget);
11473 assert(FNTarget && "Ctor cycle through bodiless function");
11474
Richard Smitha8eaf002012-08-23 06:16:52 +000011475 C = const_cast<CXXConstructorDecl*>(
11476 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011477 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11478 }
11479 }
11480
11481 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11482 Invalid.insert(*CI);
11483 Current.clear();
11484 } else {
11485 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11486 }
11487}
11488
11489
Sean Huntfe57eef2011-05-04 05:57:24 +000011490void Sema::CheckDelegatingCtorCycles() {
11491 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11492
Sean Huntebcbe1d2011-05-04 23:29:54 +000011493 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11494 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011495
Douglas Gregor0129b562011-07-27 21:57:17 +000011496 for (DelegatingCtorDeclsType::iterator
11497 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011498 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011499 I != E; ++I)
11500 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011501
11502 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11503 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011504}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011505
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011506namespace {
11507 /// \brief AST visitor that finds references to the 'this' expression.
11508 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11509 Sema &S;
11510
11511 public:
11512 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11513
11514 bool VisitCXXThisExpr(CXXThisExpr *E) {
11515 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11516 << E->isImplicit();
11517 return false;
11518 }
11519 };
11520}
11521
11522bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11523 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11524 if (!TSInfo)
11525 return false;
11526
11527 TypeLoc TL = TSInfo->getTypeLoc();
11528 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11529 if (!ProtoTL)
11530 return false;
11531
11532 // C++11 [expr.prim.general]p3:
11533 // [The expression this] shall not appear before the optional
11534 // cv-qualifier-seq and it shall not appear within the declaration of a
11535 // static member function (although its type and value category are defined
11536 // within a static member function as they are within a non-static member
11537 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011538 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011539 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11540 FindCXXThisExpr Finder(*this);
11541
11542 // If the return type came after the cv-qualifier-seq, check it now.
11543 if (Proto->hasTrailingReturn() &&
11544 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11545 return true;
11546
11547 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011548 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11549 return true;
11550
11551 return checkThisInStaticMemberFunctionAttributes(Method);
11552}
11553
11554bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11555 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11556 if (!TSInfo)
11557 return false;
11558
11559 TypeLoc TL = TSInfo->getTypeLoc();
11560 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11561 if (!ProtoTL)
11562 return false;
11563
11564 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11565 FindCXXThisExpr Finder(*this);
11566
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011567 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011568 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011569 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011570 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011571 case EST_DynamicNone:
11572 case EST_MSAny:
11573 case EST_None:
11574 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011575
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011576 case EST_ComputedNoexcept:
11577 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11578 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011579
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011580 case EST_Dynamic:
11581 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011582 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011583 E != EEnd; ++E) {
11584 if (!Finder.TraverseType(*E))
11585 return true;
11586 }
11587 break;
11588 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011589
11590 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011591}
11592
11593bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11594 FindCXXThisExpr Finder(*this);
11595
11596 // Check attributes.
11597 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11598 A != AEnd; ++A) {
11599 // FIXME: This should be emitted by tblgen.
11600 Expr *Arg = 0;
11601 ArrayRef<Expr *> Args;
11602 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11603 Arg = G->getArg();
11604 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11605 Arg = G->getArg();
11606 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11607 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11608 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11609 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11610 else if (ExclusiveLockFunctionAttr *ELF
11611 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11612 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11613 else if (SharedLockFunctionAttr *SLF
11614 = dyn_cast<SharedLockFunctionAttr>(*A))
11615 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11616 else if (ExclusiveTrylockFunctionAttr *ETLF
11617 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11618 Arg = ETLF->getSuccessValue();
11619 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11620 } else if (SharedTrylockFunctionAttr *STLF
11621 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11622 Arg = STLF->getSuccessValue();
11623 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11624 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11625 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11626 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11627 Arg = LR->getArg();
11628 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11629 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11630 else if (ExclusiveLocksRequiredAttr *ELR
11631 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11632 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11633 else if (SharedLocksRequiredAttr *SLR
11634 = dyn_cast<SharedLocksRequiredAttr>(*A))
11635 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11636
11637 if (Arg && !Finder.TraverseStmt(Arg))
11638 return true;
11639
11640 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11641 if (!Finder.TraverseStmt(Args[I]))
11642 return true;
11643 }
11644 }
11645
11646 return false;
11647}
11648
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011649void
11650Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11651 ArrayRef<ParsedType> DynamicExceptions,
11652 ArrayRef<SourceRange> DynamicExceptionRanges,
11653 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011654 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011655 FunctionProtoType::ExtProtoInfo &EPI) {
11656 Exceptions.clear();
11657 EPI.ExceptionSpecType = EST;
11658 if (EST == EST_Dynamic) {
11659 Exceptions.reserve(DynamicExceptions.size());
11660 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11661 // FIXME: Preserve type source info.
11662 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11663
11664 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11665 collectUnexpandedParameterPacks(ET, Unexpanded);
11666 if (!Unexpanded.empty()) {
11667 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11668 UPPC_ExceptionType,
11669 Unexpanded);
11670 continue;
11671 }
11672
11673 // Check that the type is valid for an exception spec, and
11674 // drop it if not.
11675 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11676 Exceptions.push_back(ET);
11677 }
11678 EPI.NumExceptions = Exceptions.size();
11679 EPI.Exceptions = Exceptions.data();
11680 return;
11681 }
11682
11683 if (EST == EST_ComputedNoexcept) {
11684 // If an error occurred, there's no expression here.
11685 if (NoexceptExpr) {
11686 assert((NoexceptExpr->isTypeDependent() ||
11687 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11688 Context.BoolTy) &&
11689 "Parser should have made sure that the expression is boolean");
11690 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11691 EPI.ExceptionSpecType = EST_BasicNoexcept;
11692 return;
11693 }
11694
11695 if (!NoexceptExpr->isValueDependent())
11696 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011697 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011698 /*AllowFold*/ false).take();
11699 EPI.NoexceptExpr = NoexceptExpr;
11700 }
11701 return;
11702 }
11703}
11704
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011705/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11706Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11707 // Implicitly declared functions (e.g. copy constructors) are
11708 // __host__ __device__
11709 if (D->isImplicit())
11710 return CFT_HostDevice;
11711
11712 if (D->hasAttr<CUDAGlobalAttr>())
11713 return CFT_Global;
11714
11715 if (D->hasAttr<CUDADeviceAttr>()) {
11716 if (D->hasAttr<CUDAHostAttr>())
11717 return CFT_HostDevice;
11718 else
11719 return CFT_Device;
11720 }
11721
11722 return CFT_Host;
11723}
11724
11725bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11726 CUDAFunctionTarget CalleeTarget) {
11727 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11728 // Callable from the device only."
11729 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11730 return true;
11731
11732 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11733 // Callable from the host only."
11734 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11735 // Callable from the host only."
11736 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11737 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11738 return true;
11739
11740 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11741 return true;
11742
11743 return false;
11744}