blob: c794d7e964afba35ad6f1de16298f49d29f3a164 [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
Richard Smith6c3af3d2013-01-17 01:17:56 +0000255 CheckCompletedExpr(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 }
Richard Smith7a614d82011-06-11 17:19:42 +00001952 }
1953
Richard Smith41956372013-01-14 22:39:08 +00001954 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00001955 // The initialization of each base and member constitutes a
1956 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00001957 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001958 if (Init.isInvalid()) {
1959 FD->setInvalidDecl();
1960 return;
1961 }
1962
1963 InitExpr = Init.release();
1964
1965 FD->setInClassInitializer(InitExpr);
1966}
1967
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001968/// \brief Find the direct and/or virtual base specifiers that
1969/// correspond to the given base type, for use in base initialization
1970/// within a constructor.
1971static bool FindBaseInitializer(Sema &SemaRef,
1972 CXXRecordDecl *ClassDecl,
1973 QualType BaseType,
1974 const CXXBaseSpecifier *&DirectBaseSpec,
1975 const CXXBaseSpecifier *&VirtualBaseSpec) {
1976 // First, check for a direct base class.
1977 DirectBaseSpec = 0;
1978 for (CXXRecordDecl::base_class_const_iterator Base
1979 = ClassDecl->bases_begin();
1980 Base != ClassDecl->bases_end(); ++Base) {
1981 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1982 // We found a direct base of this type. That's what we're
1983 // initializing.
1984 DirectBaseSpec = &*Base;
1985 break;
1986 }
1987 }
1988
1989 // Check for a virtual base class.
1990 // FIXME: We might be able to short-circuit this if we know in advance that
1991 // there are no virtual bases.
1992 VirtualBaseSpec = 0;
1993 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1994 // We haven't found a base yet; search the class hierarchy for a
1995 // virtual base class.
1996 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1997 /*DetectVirtual=*/false);
1998 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1999 BaseType, Paths)) {
2000 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2001 Path != Paths.end(); ++Path) {
2002 if (Path->back().Base->isVirtual()) {
2003 VirtualBaseSpec = Path->back().Base;
2004 break;
2005 }
2006 }
2007 }
2008 }
2009
2010 return DirectBaseSpec || VirtualBaseSpec;
2011}
2012
Sebastian Redl6df65482011-09-24 17:48:25 +00002013/// \brief Handle a C++ member initializer using braced-init-list syntax.
2014MemInitResult
2015Sema::ActOnMemInitializer(Decl *ConstructorD,
2016 Scope *S,
2017 CXXScopeSpec &SS,
2018 IdentifierInfo *MemberOrBase,
2019 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002020 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002021 SourceLocation IdLoc,
2022 Expr *InitList,
2023 SourceLocation EllipsisLoc) {
2024 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002025 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002026 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002027}
2028
2029/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002030MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002031Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002032 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002033 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002034 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002035 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002036 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002037 SourceLocation IdLoc,
2038 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002039 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002040 SourceLocation RParenLoc,
2041 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002042 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2043 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002044 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002045 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002046 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002047}
2048
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002049namespace {
2050
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002051// Callback to only accept typo corrections that can be a valid C++ member
2052// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002053class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2054 public:
2055 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2056 : ClassDecl(ClassDecl) {}
2057
2058 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2059 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2060 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2061 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2062 else
2063 return isa<TypeDecl>(ND);
2064 }
2065 return false;
2066 }
2067
2068 private:
2069 CXXRecordDecl *ClassDecl;
2070};
2071
2072}
2073
Sebastian Redl6df65482011-09-24 17:48:25 +00002074/// \brief Handle a C++ member initializer.
2075MemInitResult
2076Sema::BuildMemInitializer(Decl *ConstructorD,
2077 Scope *S,
2078 CXXScopeSpec &SS,
2079 IdentifierInfo *MemberOrBase,
2080 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002081 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002082 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002083 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002084 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002085 if (!ConstructorD)
2086 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002088 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002089
2090 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002091 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002092 if (!Constructor) {
2093 // The user wrote a constructor initializer on a function that is
2094 // not a C++ constructor. Ignore the error for now, because we may
2095 // have more member initializers coming; we'll diagnose it just
2096 // once in ActOnMemInitializers.
2097 return true;
2098 }
2099
2100 CXXRecordDecl *ClassDecl = Constructor->getParent();
2101
2102 // C++ [class.base.init]p2:
2103 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002104 // constructor's class and, if not found in that scope, are looked
2105 // up in the scope containing the constructor's definition.
2106 // [Note: if the constructor's class contains a member with the
2107 // same name as a direct or virtual base class of the class, a
2108 // mem-initializer-id naming the member or base class and composed
2109 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002110 // mem-initializer-id for the hidden base class may be specified
2111 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002112 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002113 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002114 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002115 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002116 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002117 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002118 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2119 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002120 if (EllipsisLoc.isValid())
2121 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002122 << MemberOrBase
2123 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002124
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002125 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002126 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002127 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002128 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002129 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002130 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002131 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002132
2133 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002134 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002135 } else if (DS.getTypeSpecType() == TST_decltype) {
2136 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002137 } else {
2138 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2139 LookupParsedName(R, S, &SS);
2140
2141 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2142 if (!TyD) {
2143 if (R.isAmbiguous()) return true;
2144
John McCallfd225442010-04-09 19:01:14 +00002145 // We don't want access-control diagnostics here.
2146 R.suppressDiagnostics();
2147
Douglas Gregor7a886e12010-01-19 06:46:48 +00002148 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2149 bool NotUnknownSpecialization = false;
2150 DeclContext *DC = computeDeclContext(SS, false);
2151 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2152 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2153
2154 if (!NotUnknownSpecialization) {
2155 // When the scope specifier can refer to a member of an unknown
2156 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002157 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2158 SS.getWithLocInContext(Context),
2159 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002160 if (BaseType.isNull())
2161 return true;
2162
Douglas Gregor7a886e12010-01-19 06:46:48 +00002163 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002164 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002165 }
2166 }
2167
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002168 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002169 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002170 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002171 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002172 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002173 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002174 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2175 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002176 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002177 // We have found a non-static data member with a similar
2178 // name to what was typed; complain and initialize that
2179 // member.
2180 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2181 << MemberOrBase << true << CorrectedQuotedStr
2182 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2183 Diag(Member->getLocation(), diag::note_previous_decl)
2184 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002185
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002186 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002187 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002188 const CXXBaseSpecifier *DirectBaseSpec;
2189 const CXXBaseSpecifier *VirtualBaseSpec;
2190 if (FindBaseInitializer(*this, ClassDecl,
2191 Context.getTypeDeclType(Type),
2192 DirectBaseSpec, VirtualBaseSpec)) {
2193 // We have found a direct or virtual base class with a
2194 // similar name to what was typed; complain and initialize
2195 // that base class.
2196 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002197 << MemberOrBase << false << CorrectedQuotedStr
2198 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002199
2200 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2201 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002202 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002203 diag::note_base_class_specified_here)
2204 << BaseSpec->getType()
2205 << BaseSpec->getSourceRange();
2206
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002207 TyD = Type;
2208 }
2209 }
2210 }
2211
Douglas Gregor7a886e12010-01-19 06:46:48 +00002212 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002213 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002214 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002215 return true;
2216 }
John McCall2b194412009-12-21 10:41:20 +00002217 }
2218
Douglas Gregor7a886e12010-01-19 06:46:48 +00002219 if (BaseType.isNull()) {
2220 BaseType = Context.getTypeDeclType(TyD);
2221 if (SS.isSet()) {
2222 NestedNameSpecifier *Qualifier =
2223 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002224
Douglas Gregor7a886e12010-01-19 06:46:48 +00002225 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002226 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002227 }
John McCall2b194412009-12-21 10:41:20 +00002228 }
2229 }
Mike Stump1eb44332009-09-09 15:08:12 +00002230
John McCalla93c9342009-12-07 02:54:59 +00002231 if (!TInfo)
2232 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002233
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002234 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002235}
2236
Chandler Carruth81c64772011-09-03 01:14:15 +00002237/// Checks a member initializer expression for cases where reference (or
2238/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002239static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2240 Expr *Init,
2241 SourceLocation IdLoc) {
2242 QualType MemberTy = Member->getType();
2243
2244 // We only handle pointers and references currently.
2245 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2246 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2247 return;
2248
2249 const bool IsPointer = MemberTy->isPointerType();
2250 if (IsPointer) {
2251 if (const UnaryOperator *Op
2252 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2253 // The only case we're worried about with pointers requires taking the
2254 // address.
2255 if (Op->getOpcode() != UO_AddrOf)
2256 return;
2257
2258 Init = Op->getSubExpr();
2259 } else {
2260 // We only handle address-of expression initializers for pointers.
2261 return;
2262 }
2263 }
2264
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002265 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2266 // Taking the address of a temporary will be diagnosed as a hard error.
2267 if (IsPointer)
2268 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002269
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002270 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2271 << Member << Init->getSourceRange();
2272 } else if (const DeclRefExpr *DRE
2273 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2274 // We only warn when referring to a non-reference parameter declaration.
2275 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2276 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002277 return;
2278
2279 S.Diag(Init->getExprLoc(),
2280 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2281 : diag::warn_bind_ref_member_to_parameter)
2282 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002283 } else {
2284 // Other initializers are fine.
2285 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002286 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002287
2288 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2289 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002290}
2291
John McCallf312b1e2010-08-26 23:41:50 +00002292MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002293Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002294 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002295 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2296 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2297 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002298 "Member must be a FieldDecl or IndirectFieldDecl");
2299
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002300 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002301 return true;
2302
Douglas Gregor464b2f02010-11-05 22:21:31 +00002303 if (Member->isInvalidDecl())
2304 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002305
John McCallb4190042009-11-04 23:02:40 +00002306 // Diagnose value-uses of fields to initialize themselves, e.g.
2307 // foo(foo)
2308 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002309 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002310 Expr **Args;
2311 unsigned NumArgs;
2312 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2313 Args = ParenList->getExprs();
2314 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002315 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002316 Args = InitList->getInits();
2317 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002318 } else {
2319 // Template instantiation doesn't reconstruct ParenListExprs for us.
2320 Args = &Init;
2321 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002322 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002323
Richard Trieude5e75c2012-06-14 23:11:34 +00002324 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2325 != DiagnosticsEngine::Ignored)
2326 for (unsigned i = 0; i < NumArgs; ++i)
2327 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002328 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002329 // initializing the i'th field, throw a warning if any of the >= i'th
2330 // fields are used, as they are not yet initialized.
2331 // Right now we are only handling the case where the i'th field uses
2332 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002333 // Also need to take into account that some fields may be initialized by
2334 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002335 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002336
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002337 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002338
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002339 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002340 // Can't check initialization for a member of dependent type or when
2341 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002342 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002343 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002344 bool InitList = false;
2345 if (isa<InitListExpr>(Init)) {
2346 InitList = true;
2347 Args = &Init;
2348 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002349
2350 if (isStdInitializerList(Member->getType(), 0)) {
2351 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2352 << /*at end of ctor*/1 << InitRange;
2353 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002354 }
2355
Chandler Carruth894aed92010-12-06 09:23:57 +00002356 // Initialize the member.
2357 InitializedEntity MemberEntity =
2358 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2359 : InitializedEntity::InitializeMember(IndirectMember, 0);
2360 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002361 InitList ? InitializationKind::CreateDirectList(IdLoc)
2362 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2363 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002364
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002365 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2366 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002367 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002368 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002369 if (MemberInit.isInvalid())
2370 return true;
2371
Richard Smith41956372013-01-14 22:39:08 +00002372 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002373 // The initialization of each base and member constitutes a
2374 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002375 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002376 if (MemberInit.isInvalid())
2377 return true;
2378
Richard Smithc83c2302012-12-19 01:39:02 +00002379 Init = MemberInit.get();
2380 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002381 }
2382
Chandler Carruth894aed92010-12-06 09:23:57 +00002383 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002384 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2385 InitRange.getBegin(), Init,
2386 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002387 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002388 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2389 InitRange.getBegin(), Init,
2390 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002391 }
Eli Friedman59c04372009-07-29 19:44:27 +00002392}
2393
John McCallf312b1e2010-08-26 23:41:50 +00002394MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002395Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002396 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002397 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002398 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002399 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002400 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002401 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002402
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002403 bool InitList = true;
2404 Expr **Args = &Init;
2405 unsigned NumArgs = 1;
2406 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2407 InitList = false;
2408 Args = ParenList->getExprs();
2409 NumArgs = ParenList->getNumExprs();
2410 }
2411
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002412 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002413 // Initialize the object.
2414 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2415 QualType(ClassDecl->getTypeForDecl(), 0));
2416 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002417 InitList ? InitializationKind::CreateDirectList(NameLoc)
2418 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2419 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002420 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2421 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002422 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002423 0);
Sean Hunt41717662011-02-26 19:13:13 +00002424 if (DelegationInit.isInvalid())
2425 return true;
2426
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002427 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2428 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002429
Richard Smith41956372013-01-14 22:39:08 +00002430 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002431 // The initialization of each base and member constitutes a
2432 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002433 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2434 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002435 if (DelegationInit.isInvalid())
2436 return true;
2437
Eli Friedmand21016f2012-05-19 23:35:23 +00002438 // If we are in a dependent context, template instantiation will
2439 // perform this type-checking again. Just save the arguments that we
2440 // received in a ParenListExpr.
2441 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2442 // of the information that we have about the base
2443 // initializer. However, deconstructing the ASTs is a dicey process,
2444 // and this approach is far more likely to get the corner cases right.
2445 if (CurContext->isDependentContext())
2446 DelegationInit = Owned(Init);
2447
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002448 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002449 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002450 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002451}
2452
2453MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002454Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002455 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002456 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002457 SourceLocation BaseLoc
2458 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002459
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002460 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2461 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2462 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2463
2464 // C++ [class.base.init]p2:
2465 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002466 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002467 // of that class, the mem-initializer is ill-formed. A
2468 // mem-initializer-list can initialize a base class using any
2469 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002470 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002471
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002472 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002473 if (EllipsisLoc.isValid()) {
2474 // This is a pack expansion.
2475 if (!BaseType->containsUnexpandedParameterPack()) {
2476 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002477 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002478
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002479 EllipsisLoc = SourceLocation();
2480 }
2481 } else {
2482 // Check for any unexpanded parameter packs.
2483 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2484 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002485
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002486 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002487 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002488 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002489
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002490 // Check for direct and virtual base classes.
2491 const CXXBaseSpecifier *DirectBaseSpec = 0;
2492 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2493 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002494 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2495 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002496 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002497
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002498 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2499 VirtualBaseSpec);
2500
2501 // C++ [base.class.init]p2:
2502 // Unless the mem-initializer-id names a nonstatic data member of the
2503 // constructor's class or a direct or virtual base of that class, the
2504 // mem-initializer is ill-formed.
2505 if (!DirectBaseSpec && !VirtualBaseSpec) {
2506 // If the class has any dependent bases, then it's possible that
2507 // one of those types will resolve to the same type as
2508 // BaseType. Therefore, just treat this as a dependent base
2509 // class initialization. FIXME: Should we try to check the
2510 // initialization anyway? It seems odd.
2511 if (ClassDecl->hasAnyDependentBases())
2512 Dependent = true;
2513 else
2514 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2515 << BaseType << Context.getTypeDeclType(ClassDecl)
2516 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2517 }
2518 }
2519
2520 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002521 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002522
Sebastian Redl6df65482011-09-24 17:48:25 +00002523 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2524 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002525 InitRange.getBegin(), Init,
2526 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002527 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002528
2529 // C++ [base.class.init]p2:
2530 // If a mem-initializer-id is ambiguous because it designates both
2531 // a direct non-virtual base class and an inherited virtual base
2532 // class, the mem-initializer is ill-formed.
2533 if (DirectBaseSpec && VirtualBaseSpec)
2534 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002535 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002536
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002537 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002538 if (!BaseSpec)
2539 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2540
2541 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002542 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002543 Expr **Args = &Init;
2544 unsigned NumArgs = 1;
2545 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002546 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002547 Args = ParenList->getExprs();
2548 NumArgs = ParenList->getNumExprs();
2549 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002550
2551 InitializedEntity BaseEntity =
2552 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2553 InitializationKind Kind =
2554 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2555 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2556 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002557 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2558 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002559 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002560 if (BaseInit.isInvalid())
2561 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002562
Richard Smith41956372013-01-14 22:39:08 +00002563 // C++11 [class.base.init]p7:
2564 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002565 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002566 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002567 if (BaseInit.isInvalid())
2568 return true;
2569
2570 // If we are in a dependent context, template instantiation will
2571 // perform this type-checking again. Just save the arguments that we
2572 // received in a ParenListExpr.
2573 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2574 // of the information that we have about the base
2575 // initializer. However, deconstructing the ASTs is a dicey process,
2576 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002577 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002578 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002579
Sean Huntcbb67482011-01-08 20:30:50 +00002580 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002581 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002582 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002583 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002584 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002585}
2586
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002587// Create a static_cast\<T&&>(expr).
2588static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2589 QualType ExprType = E->getType();
2590 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2591 SourceLocation ExprLoc = E->getLocStart();
2592 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2593 TargetType, ExprLoc);
2594
2595 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2596 SourceRange(ExprLoc, ExprLoc),
2597 E->getSourceRange()).take();
2598}
2599
Anders Carlssone5ef7402010-04-23 03:10:23 +00002600/// ImplicitInitializerKind - How an implicit base or member initializer should
2601/// initialize its base or member.
2602enum ImplicitInitializerKind {
2603 IIK_Default,
2604 IIK_Copy,
2605 IIK_Move
2606};
2607
Anders Carlssondefefd22010-04-23 02:00:02 +00002608static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002609BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002610 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002611 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002612 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002613 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002614 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002615 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2616 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002617
John McCall60d7b3a2010-08-24 06:29:42 +00002618 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002619
2620 switch (ImplicitInitKind) {
2621 case IIK_Default: {
2622 InitializationKind InitKind
2623 = InitializationKind::CreateDefault(Constructor->getLocation());
2624 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002625 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002626 break;
2627 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002628
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002629 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002630 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002631 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002632 ParmVarDecl *Param = Constructor->getParamDecl(0);
2633 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002634
Anders Carlssone5ef7402010-04-23 03:10:23 +00002635 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002636 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002637 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002638 Constructor->getLocation(), ParamType,
2639 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002640
Eli Friedman5f2987c2012-02-02 03:46:19 +00002641 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2642
Anders Carlssonc7957502010-04-24 22:02:54 +00002643 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002644 QualType ArgTy =
2645 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2646 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002647
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002648 if (Moving) {
2649 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2650 }
2651
John McCallf871d0c2010-08-07 06:22:56 +00002652 CXXCastPath BasePath;
2653 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002654 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2655 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002656 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002657 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002658
Anders Carlssone5ef7402010-04-23 03:10:23 +00002659 InitializationKind InitKind
2660 = InitializationKind::CreateDirect(Constructor->getLocation(),
2661 SourceLocation(), SourceLocation());
2662 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2663 &CopyCtorArg, 1);
2664 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002665 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002666 break;
2667 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002668 }
John McCall9ae2f072010-08-23 23:25:46 +00002669
Douglas Gregor53c374f2010-12-07 00:41:46 +00002670 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002671 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002672 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002673
Anders Carlssondefefd22010-04-23 02:00:02 +00002674 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002675 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002676 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2677 SourceLocation()),
2678 BaseSpec->isVirtual(),
2679 SourceLocation(),
2680 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002681 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002682 SourceLocation());
2683
Anders Carlssondefefd22010-04-23 02:00:02 +00002684 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002685}
2686
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002687static bool RefersToRValueRef(Expr *MemRef) {
2688 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2689 return Referenced->getType()->isRValueReferenceType();
2690}
2691
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002692static bool
2693BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002694 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002695 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002696 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002697 if (Field->isInvalidDecl())
2698 return true;
2699
Chandler Carruthf186b542010-06-29 23:50:44 +00002700 SourceLocation Loc = Constructor->getLocation();
2701
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002702 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2703 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002704 ParmVarDecl *Param = Constructor->getParamDecl(0);
2705 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002706
2707 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002708 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2709 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002710
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002711 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002712 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002713 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002714 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002715
Eli Friedman5f2987c2012-02-02 03:46:19 +00002716 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2717
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002718 if (Moving) {
2719 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2720 }
2721
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002722 // Build a reference to this field within the parameter.
2723 CXXScopeSpec SS;
2724 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2725 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002726 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2727 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002728 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002729 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002730 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002731 ParamType, Loc,
2732 /*IsArrow=*/false,
2733 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002734 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002735 /*FirstQualifierInScope=*/0,
2736 MemberLookup,
2737 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002738 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002739 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002740
2741 // C++11 [class.copy]p15:
2742 // - if a member m has rvalue reference type T&&, it is direct-initialized
2743 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002744 if (RefersToRValueRef(CtorArg.get())) {
2745 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002746 }
2747
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002748 // When the field we are copying is an array, create index variables for
2749 // each dimension of the array. We use these index variables to subscript
2750 // the source array, and other clients (e.g., CodeGen) will perform the
2751 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002752 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002753 QualType BaseType = Field->getType();
2754 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002755 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002756 while (const ConstantArrayType *Array
2757 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002758 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002759 // Create the iteration variable for this array index.
2760 IdentifierInfo *IterationVarName = 0;
2761 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002762 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002763 llvm::raw_svector_ostream OS(Str);
2764 OS << "__i" << IndexVariables.size();
2765 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2766 }
2767 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002768 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002769 IterationVarName, SizeType,
2770 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002771 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002772 IndexVariables.push_back(IterationVar);
2773
2774 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002775 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002776 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002777 assert(!IterationVarRef.isInvalid() &&
2778 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002779 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2780 assert(!IterationVarRef.isInvalid() &&
2781 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002782
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002783 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002784 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002785 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002786 Loc);
2787 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002788 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002789
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002790 BaseType = Array->getElementType();
2791 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002792
2793 // The array subscript expression is an lvalue, which is wrong for moving.
2794 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002795 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002796
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002797 // Construct the entity that we will be initializing. For an array, this
2798 // will be first element in the array, which may require several levels
2799 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002800 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002801 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002802 if (Indirect)
2803 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2804 else
2805 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002806 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2807 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2808 0,
2809 Entities.back()));
2810
2811 // Direct-initialize to use the copy constructor.
2812 InitializationKind InitKind =
2813 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2814
Sebastian Redl74e611a2011-09-04 18:14:28 +00002815 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002816 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002817 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002818
John McCall60d7b3a2010-08-24 06:29:42 +00002819 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002820 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002821 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002822 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002823 if (MemberInit.isInvalid())
2824 return true;
2825
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002826 if (Indirect) {
2827 assert(IndexVariables.size() == 0 &&
2828 "Indirect field improperly initialized");
2829 CXXMemberInit
2830 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2831 Loc, Loc,
2832 MemberInit.takeAs<Expr>(),
2833 Loc);
2834 } else
2835 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2836 Loc, MemberInit.takeAs<Expr>(),
2837 Loc,
2838 IndexVariables.data(),
2839 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002840 return false;
2841 }
2842
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002843 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2844
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002845 QualType FieldBaseElementType =
2846 SemaRef.Context.getBaseElementType(Field->getType());
2847
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002848 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002849 InitializedEntity InitEntity
2850 = Indirect? InitializedEntity::InitializeMember(Indirect)
2851 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002852 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002853 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002854
2855 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002856 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002857 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002858
Douglas Gregor53c374f2010-12-07 00:41:46 +00002859 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002860 if (MemberInit.isInvalid())
2861 return true;
2862
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002863 if (Indirect)
2864 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2865 Indirect, Loc,
2866 Loc,
2867 MemberInit.get(),
2868 Loc);
2869 else
2870 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2871 Field, Loc, Loc,
2872 MemberInit.get(),
2873 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002874 return false;
2875 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002876
Sean Hunt1f2f3842011-05-17 00:19:05 +00002877 if (!Field->getParent()->isUnion()) {
2878 if (FieldBaseElementType->isReferenceType()) {
2879 SemaRef.Diag(Constructor->getLocation(),
2880 diag::err_uninitialized_member_in_ctor)
2881 << (int)Constructor->isImplicit()
2882 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2883 << 0 << Field->getDeclName();
2884 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2885 return true;
2886 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002887
Sean Hunt1f2f3842011-05-17 00:19:05 +00002888 if (FieldBaseElementType.isConstQualified()) {
2889 SemaRef.Diag(Constructor->getLocation(),
2890 diag::err_uninitialized_member_in_ctor)
2891 << (int)Constructor->isImplicit()
2892 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2893 << 1 << Field->getDeclName();
2894 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2895 return true;
2896 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002897 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002898
David Blaikie4e4d0842012-03-11 07:00:24 +00002899 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002900 FieldBaseElementType->isObjCRetainableType() &&
2901 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2902 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002903 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002904 // Default-initialize Objective-C pointers to NULL.
2905 CXXMemberInit
2906 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2907 Loc, Loc,
2908 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2909 Loc);
2910 return false;
2911 }
2912
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002913 // Nothing to initialize.
2914 CXXMemberInit = 0;
2915 return false;
2916}
John McCallf1860e52010-05-20 23:23:51 +00002917
2918namespace {
2919struct BaseAndFieldInfo {
2920 Sema &S;
2921 CXXConstructorDecl *Ctor;
2922 bool AnyErrorsInInits;
2923 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002924 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002925 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002926
2927 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2928 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002929 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2930 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002931 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002932 else if (Generated && Ctor->isMoveConstructor())
2933 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002934 else
2935 IIK = IIK_Default;
2936 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002937
2938 bool isImplicitCopyOrMove() const {
2939 switch (IIK) {
2940 case IIK_Copy:
2941 case IIK_Move:
2942 return true;
2943
2944 case IIK_Default:
2945 return false;
2946 }
David Blaikie30263482012-01-20 21:50:17 +00002947
2948 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002949 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002950
2951 bool addFieldInitializer(CXXCtorInitializer *Init) {
2952 AllToInit.push_back(Init);
2953
2954 // Check whether this initializer makes the field "used".
2955 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2956 S.UnusedPrivateFields.remove(Init->getAnyMember());
2957
2958 return false;
2959 }
John McCallf1860e52010-05-20 23:23:51 +00002960};
2961}
2962
Richard Smitha4950662011-09-19 13:34:43 +00002963/// \brief Determine whether the given indirect field declaration is somewhere
2964/// within an anonymous union.
2965static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2966 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2967 CEnd = F->chain_end();
2968 C != CEnd; ++C)
2969 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2970 if (Record->isUnion())
2971 return true;
2972
2973 return false;
2974}
2975
Douglas Gregorddb21472011-11-02 23:04:16 +00002976/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2977/// array type.
2978static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2979 if (T->isIncompleteArrayType())
2980 return true;
2981
2982 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2983 if (!ArrayT->getSize())
2984 return true;
2985
2986 T = ArrayT->getElementType();
2987 }
2988
2989 return false;
2990}
2991
Richard Smith7a614d82011-06-11 17:19:42 +00002992static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002993 FieldDecl *Field,
2994 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002995
Chandler Carruthe861c602010-06-30 02:59:29 +00002996 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00002997 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
2998 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00002999
Richard Smith0b8220a2012-08-07 21:30:42 +00003000 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003001 // has a brace-or-equal-initializer, the entity is initialized as specified
3002 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003003 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003004 CXXCtorInitializer *Init;
3005 if (Indirect)
3006 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3007 SourceLocation(),
3008 SourceLocation(), 0,
3009 SourceLocation());
3010 else
3011 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3012 SourceLocation(),
3013 SourceLocation(), 0,
3014 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003015 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003016 }
3017
Richard Smithc115f632011-09-18 11:14:50 +00003018 // Don't build an implicit initializer for union members if none was
3019 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003020 if (Field->getParent()->isUnion() ||
3021 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003022 return false;
3023
Douglas Gregorddb21472011-11-02 23:04:16 +00003024 // Don't initialize incomplete or zero-length arrays.
3025 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3026 return false;
3027
John McCallf1860e52010-05-20 23:23:51 +00003028 // Don't try to build an implicit initializer if there were semantic
3029 // errors in any of the initializers (and therefore we might be
3030 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003031 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003032 return false;
3033
Sean Huntcbb67482011-01-08 20:30:50 +00003034 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003035 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3036 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003037 return true;
John McCallf1860e52010-05-20 23:23:51 +00003038
Richard Smith0b8220a2012-08-07 21:30:42 +00003039 if (!Init)
3040 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003041
Richard Smith0b8220a2012-08-07 21:30:42 +00003042 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003043}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003044
3045bool
3046Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3047 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003048 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003049 Constructor->setNumCtorInitializers(1);
3050 CXXCtorInitializer **initializer =
3051 new (Context) CXXCtorInitializer*[1];
3052 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3053 Constructor->setCtorInitializers(initializer);
3054
Sean Huntb76af9c2011-05-03 23:05:34 +00003055 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003056 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003057 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3058 }
3059
Sean Huntc1598702011-05-05 00:05:47 +00003060 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003061
Sean Hunt059ce0d2011-05-01 07:04:31 +00003062 return false;
3063}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003064
David Blaikie93c86172013-01-17 05:26:25 +00003065bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3066 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003067 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003068 // Just store the initializers as written, they will be checked during
3069 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003070 if (!Initializers.empty()) {
3071 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003072 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003073 new (Context) CXXCtorInitializer*[Initializers.size()];
3074 memcpy(baseOrMemberInitializers, Initializers.data(),
3075 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003076 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003077 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003078
3079 // Let template instantiation know whether we had errors.
3080 if (AnyErrors)
3081 Constructor->setInvalidDecl();
3082
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003083 return false;
3084 }
3085
John McCallf1860e52010-05-20 23:23:51 +00003086 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003087
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003088 // We need to build the initializer AST according to order of construction
3089 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003090 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003091 if (!ClassDecl)
3092 return true;
3093
Eli Friedman80c30da2009-11-09 19:20:36 +00003094 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003095
David Blaikie93c86172013-01-17 05:26:25 +00003096 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003097 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003098
3099 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003100 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003101 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003102 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003103 }
3104
Anders Carlsson711f34a2010-04-21 19:52:01 +00003105 // Keep track of the direct virtual bases.
3106 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3107 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3108 E = ClassDecl->bases_end(); I != E; ++I) {
3109 if (I->isVirtual())
3110 DirectVBases.insert(I);
3111 }
3112
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003113 // Push virtual bases before others.
3114 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3115 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3116
Sean Huntcbb67482011-01-08 20:30:50 +00003117 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003118 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3119 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003120 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003121 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003122 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003123 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003124 VBase, IsInheritedVirtualBase,
3125 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003126 HadError = true;
3127 continue;
3128 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003129
John McCallf1860e52010-05-20 23:23:51 +00003130 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003131 }
3132 }
Mike Stump1eb44332009-09-09 15:08:12 +00003133
John McCallf1860e52010-05-20 23:23:51 +00003134 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003135 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3136 E = ClassDecl->bases_end(); Base != E; ++Base) {
3137 // Virtuals are in the virtual base list and already constructed.
3138 if (Base->isVirtual())
3139 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003140
Sean Huntcbb67482011-01-08 20:30:50 +00003141 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003142 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3143 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003144 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003145 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003146 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003147 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003148 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003149 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003150 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003151 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003152
John McCallf1860e52010-05-20 23:23:51 +00003153 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003154 }
3155 }
Mike Stump1eb44332009-09-09 15:08:12 +00003156
John McCallf1860e52010-05-20 23:23:51 +00003157 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003158 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3159 MemEnd = ClassDecl->decls_end();
3160 Mem != MemEnd; ++Mem) {
3161 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003162 // C++ [class.bit]p2:
3163 // A declaration for a bit-field that omits the identifier declares an
3164 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3165 // initialized.
3166 if (F->isUnnamedBitfield())
3167 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003168
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003169 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003170 // handle anonymous struct/union fields based on their individual
3171 // indirect fields.
3172 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3173 continue;
3174
3175 if (CollectFieldInitializer(*this, Info, F))
3176 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003177 continue;
3178 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003179
3180 // Beyond this point, we only consider default initialization.
3181 if (Info.IIK != IIK_Default)
3182 continue;
3183
3184 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3185 if (F->getType()->isIncompleteArrayType()) {
3186 assert(ClassDecl->hasFlexibleArrayMember() &&
3187 "Incomplete array type is not valid");
3188 continue;
3189 }
3190
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003191 // Initialize each field of an anonymous struct individually.
3192 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3193 HadError = true;
3194
3195 continue;
3196 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003197 }
Mike Stump1eb44332009-09-09 15:08:12 +00003198
David Blaikie93c86172013-01-17 05:26:25 +00003199 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003200 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003201 Constructor->setNumCtorInitializers(NumInitializers);
3202 CXXCtorInitializer **baseOrMemberInitializers =
3203 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003204 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003205 NumInitializers * sizeof(CXXCtorInitializer*));
3206 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003207
John McCallef027fe2010-03-16 21:39:52 +00003208 // Constructors implicitly reference the base and member
3209 // destructors.
3210 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3211 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003212 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003213
3214 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003215}
3216
Eli Friedman6347f422009-07-21 19:28:10 +00003217static void *GetKeyForTopLevelField(FieldDecl *Field) {
3218 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003219 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003220 if (RT->getDecl()->isAnonymousStructOrUnion())
David Blaikie72190da2013-01-17 05:26:21 +00003221 return RT->getDecl();
Eli Friedman6347f422009-07-21 19:28:10 +00003222 }
David Blaikie72190da2013-01-17 05:26:21 +00003223 return Field;
Eli Friedman6347f422009-07-21 19:28:10 +00003224}
3225
Anders Carlssonea356fb2010-04-02 05:42:15 +00003226static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003227 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003228}
3229
Anders Carlssonea356fb2010-04-02 05:42:15 +00003230static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003231 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003232 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003233 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003234
Eli Friedman6347f422009-07-21 19:28:10 +00003235 // For fields injected into the class via declaration of an anonymous union,
3236 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003237 FieldDecl *Field = Member->getAnyMember();
3238
John McCall3c3ccdb2010-04-10 09:28:51 +00003239 // If the field is a member of an anonymous struct or union, our key
3240 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003241 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003242 if (RD->isAnonymousStructOrUnion()) {
3243 while (true) {
3244 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3245 if (Parent->isAnonymousStructOrUnion())
3246 RD = Parent;
3247 else
3248 break;
3249 }
3250
David Blaikie72190da2013-01-17 05:26:21 +00003251 return RD;
John McCall3c3ccdb2010-04-10 09:28:51 +00003252 }
Mike Stump1eb44332009-09-09 15:08:12 +00003253
David Blaikie72190da2013-01-17 05:26:21 +00003254 return Field;
Eli Friedman6347f422009-07-21 19:28:10 +00003255}
3256
David Blaikie93c86172013-01-17 05:26:25 +00003257static void DiagnoseBaseOrMemInitializerOrder(
3258 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3259 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003260 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003261 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003262
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003263 // Don't check initializers order unless the warning is enabled at the
3264 // location of at least one initializer.
3265 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003266 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003267 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003268 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3269 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003270 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003271 ShouldCheckOrder = true;
3272 break;
3273 }
3274 }
3275 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003276 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003277
John McCalld6ca8da2010-04-10 07:37:23 +00003278 // Build the list of bases and members in the order that they'll
3279 // actually be initialized. The explicit initializers should be in
3280 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003281 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003282
Anders Carlsson071d6102010-04-02 03:38:04 +00003283 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3284
John McCalld6ca8da2010-04-10 07:37:23 +00003285 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003286 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003287 ClassDecl->vbases_begin(),
3288 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003289 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003290
John McCalld6ca8da2010-04-10 07:37:23 +00003291 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003292 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003293 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003294 if (Base->isVirtual())
3295 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003296 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003297 }
Mike Stump1eb44332009-09-09 15:08:12 +00003298
John McCalld6ca8da2010-04-10 07:37:23 +00003299 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003300 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003301 E = ClassDecl->field_end(); Field != E; ++Field) {
3302 if (Field->isUnnamedBitfield())
3303 continue;
3304
David Blaikie581deb32012-06-06 20:45:41 +00003305 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003306 }
3307
John McCalld6ca8da2010-04-10 07:37:23 +00003308 unsigned NumIdealInits = IdealInitKeys.size();
3309 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003310
Sean Huntcbb67482011-01-08 20:30:50 +00003311 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003312 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003313 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003314 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003315
3316 // Scan forward to try to find this initializer in the idealized
3317 // initializers list.
3318 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3319 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003320 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003321
3322 // If we didn't find this initializer, it must be because we
3323 // scanned past it on a previous iteration. That can only
3324 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003325 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003326 Sema::SemaDiagnosticBuilder D =
3327 SemaRef.Diag(PrevInit->getSourceLocation(),
3328 diag::warn_initializer_out_of_order);
3329
Francois Pichet00eb3f92010-12-04 09:14:42 +00003330 if (PrevInit->isAnyMemberInitializer())
3331 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003332 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003333 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003334
Francois Pichet00eb3f92010-12-04 09:14:42 +00003335 if (Init->isAnyMemberInitializer())
3336 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003337 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003338 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003339
3340 // Move back to the initializer's location in the ideal list.
3341 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3342 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003343 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003344
3345 assert(IdealIndex != NumIdealInits &&
3346 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003347 }
John McCalld6ca8da2010-04-10 07:37:23 +00003348
3349 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003350 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003351}
3352
John McCall3c3ccdb2010-04-10 09:28:51 +00003353namespace {
3354bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003355 CXXCtorInitializer *Init,
3356 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003357 if (!PrevInit) {
3358 PrevInit = Init;
3359 return false;
3360 }
3361
3362 if (FieldDecl *Field = Init->getMember())
3363 S.Diag(Init->getSourceLocation(),
3364 diag::err_multiple_mem_initialization)
3365 << Field->getDeclName()
3366 << Init->getSourceRange();
3367 else {
John McCallf4c73712011-01-19 06:33:43 +00003368 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003369 assert(BaseClass && "neither field nor base");
3370 S.Diag(Init->getSourceLocation(),
3371 diag::err_multiple_base_initialization)
3372 << QualType(BaseClass, 0)
3373 << Init->getSourceRange();
3374 }
3375 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3376 << 0 << PrevInit->getSourceRange();
3377
3378 return true;
3379}
3380
Sean Huntcbb67482011-01-08 20:30:50 +00003381typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003382typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3383
3384bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003385 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003386 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003387 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003388 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003389 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003390
3391 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003392 if (Parent->isUnion()) {
3393 UnionEntry &En = Unions[Parent];
3394 if (En.first && En.first != Child) {
3395 S.Diag(Init->getSourceLocation(),
3396 diag::err_multiple_mem_union_initialization)
3397 << Field->getDeclName()
3398 << Init->getSourceRange();
3399 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3400 << 0 << En.second->getSourceRange();
3401 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003402 }
3403 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003404 En.first = Child;
3405 En.second = Init;
3406 }
David Blaikie6fe29652011-11-17 06:01:57 +00003407 if (!Parent->isAnonymousStructOrUnion())
3408 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003409 }
3410
3411 Child = Parent;
3412 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003413 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003414
3415 return false;
3416}
3417}
3418
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003419/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003420void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003421 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003422 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003423 bool AnyErrors) {
3424 if (!ConstructorDecl)
3425 return;
3426
3427 AdjustDeclIfTemplate(ConstructorDecl);
3428
3429 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003430 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003431
3432 if (!Constructor) {
3433 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3434 return;
3435 }
3436
John McCall3c3ccdb2010-04-10 09:28:51 +00003437 // Mapping for the duplicate initializers check.
3438 // For member initializers, this is keyed with a FieldDecl*.
3439 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003440 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003441
3442 // Mapping for the inconsistent anonymous-union initializers check.
3443 RedundantUnionMap MemberUnions;
3444
Anders Carlssonea356fb2010-04-02 05:42:15 +00003445 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003446 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003447 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003448
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003449 // Set the source order index.
3450 Init->setSourceOrder(i);
3451
Francois Pichet00eb3f92010-12-04 09:14:42 +00003452 if (Init->isAnyMemberInitializer()) {
3453 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003454 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3455 CheckRedundantUnionInit(*this, Init, MemberUnions))
3456 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003457 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003458 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3459 if (CheckRedundantInit(*this, Init, Members[Key]))
3460 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003461 } else {
3462 assert(Init->isDelegatingInitializer());
3463 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003464 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003465 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003466 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003467 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003468 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003469 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003470 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003471 // Return immediately as the initializer is set.
3472 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003473 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003474 }
3475
Anders Carlssonea356fb2010-04-02 05:42:15 +00003476 if (HadError)
3477 return;
3478
David Blaikie93c86172013-01-17 05:26:25 +00003479 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003480
David Blaikie93c86172013-01-17 05:26:25 +00003481 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003482}
3483
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003484void
John McCallef027fe2010-03-16 21:39:52 +00003485Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3486 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003487 // Ignore dependent contexts. Also ignore unions, since their members never
3488 // have destructors implicitly called.
3489 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003490 return;
John McCall58e6f342010-03-16 05:22:47 +00003491
3492 // FIXME: all the access-control diagnostics are positioned on the
3493 // field/base declaration. That's probably good; that said, the
3494 // user might reasonably want to know why the destructor is being
3495 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003496
Anders Carlsson9f853df2009-11-17 04:44:12 +00003497 // Non-static data members.
3498 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3499 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003500 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003501 if (Field->isInvalidDecl())
3502 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003503
3504 // Don't destroy incomplete or zero-length arrays.
3505 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3506 continue;
3507
Anders Carlsson9f853df2009-11-17 04:44:12 +00003508 QualType FieldType = Context.getBaseElementType(Field->getType());
3509
3510 const RecordType* RT = FieldType->getAs<RecordType>();
3511 if (!RT)
3512 continue;
3513
3514 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003515 if (FieldClassDecl->isInvalidDecl())
3516 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003517 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003518 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003519 // The destructor for an implicit anonymous union member is never invoked.
3520 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3521 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003522
Douglas Gregordb89f282010-07-01 22:47:18 +00003523 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003524 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003525 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003526 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003527 << Field->getDeclName()
3528 << FieldType);
3529
Eli Friedman5f2987c2012-02-02 03:46:19 +00003530 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003531 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003532 }
3533
John McCall58e6f342010-03-16 05:22:47 +00003534 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3535
Anders Carlsson9f853df2009-11-17 04:44:12 +00003536 // Bases.
3537 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3538 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003539 // Bases are always records in a well-formed non-dependent class.
3540 const RecordType *RT = Base->getType()->getAs<RecordType>();
3541
3542 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003543 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003544 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003545
John McCall58e6f342010-03-16 05:22:47 +00003546 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003547 // If our base class is invalid, we probably can't get its dtor anyway.
3548 if (BaseClassDecl->isInvalidDecl())
3549 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003550 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003551 continue;
John McCall58e6f342010-03-16 05:22:47 +00003552
Douglas Gregordb89f282010-07-01 22:47:18 +00003553 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003554 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003555
3556 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003557 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003558 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003559 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003560 << Base->getSourceRange(),
3561 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003562
Eli Friedman5f2987c2012-02-02 03:46:19 +00003563 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003564 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003565 }
3566
3567 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003568 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3569 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003570
3571 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003572 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003573
3574 // Ignore direct virtual bases.
3575 if (DirectVirtualBases.count(RT))
3576 continue;
3577
John McCall58e6f342010-03-16 05:22:47 +00003578 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003579 // If our base class is invalid, we probably can't get its dtor anyway.
3580 if (BaseClassDecl->isInvalidDecl())
3581 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003582 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003583 continue;
John McCall58e6f342010-03-16 05:22:47 +00003584
Douglas Gregordb89f282010-07-01 22:47:18 +00003585 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003586 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003587 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003588 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003589 << VBase->getType(),
3590 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003591
Eli Friedman5f2987c2012-02-02 03:46:19 +00003592 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003593 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003594 }
3595}
3596
John McCalld226f652010-08-21 09:40:31 +00003597void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003598 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003599 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003600
Mike Stump1eb44332009-09-09 15:08:12 +00003601 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003602 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003603 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003604}
3605
Mike Stump1eb44332009-09-09 15:08:12 +00003606bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003607 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003608 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3609 unsigned DiagID;
3610 AbstractDiagSelID SelID;
3611
3612 public:
3613 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3614 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3615
3616 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003617 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003618 if (SelID == -1)
3619 S.Diag(Loc, DiagID) << T;
3620 else
3621 S.Diag(Loc, DiagID) << SelID << T;
3622 }
3623 } Diagnoser(DiagID, SelID);
3624
3625 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003626}
3627
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003628bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003629 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003630 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003631 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003632
Anders Carlsson11f21a02009-03-23 19:10:31 +00003633 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003634 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003635
Ted Kremenek6217b802009-07-29 21:53:49 +00003636 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003637 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003638 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003639 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003640
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003641 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003642 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003643 }
Mike Stump1eb44332009-09-09 15:08:12 +00003644
Ted Kremenek6217b802009-07-29 21:53:49 +00003645 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003646 if (!RT)
3647 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003648
John McCall86ff3082010-02-04 22:26:26 +00003649 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003650
John McCall94c3b562010-08-18 09:41:07 +00003651 // We can't answer whether something is abstract until it has a
3652 // definition. If it's currently being defined, we'll walk back
3653 // over all the declarations when we have a full definition.
3654 const CXXRecordDecl *Def = RD->getDefinition();
3655 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003656 return false;
3657
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003658 if (!RD->isAbstract())
3659 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003660
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003661 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003662 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003663
John McCall94c3b562010-08-18 09:41:07 +00003664 return true;
3665}
3666
3667void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3668 // Check if we've already emitted the list of pure virtual functions
3669 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003670 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003671 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003673 CXXFinalOverriderMap FinalOverriders;
3674 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003675
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003676 // Keep a set of seen pure methods so we won't diagnose the same method
3677 // more than once.
3678 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3679
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003680 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3681 MEnd = FinalOverriders.end();
3682 M != MEnd;
3683 ++M) {
3684 for (OverridingMethods::iterator SO = M->second.begin(),
3685 SOEnd = M->second.end();
3686 SO != SOEnd; ++SO) {
3687 // C++ [class.abstract]p4:
3688 // A class is abstract if it contains or inherits at least one
3689 // pure virtual function for which the final overrider is pure
3690 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003692 //
3693 if (SO->second.size() != 1)
3694 continue;
3695
3696 if (!SO->second.front().Method->isPure())
3697 continue;
3698
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003699 if (!SeenPureMethods.insert(SO->second.front().Method))
3700 continue;
3701
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003702 Diag(SO->second.front().Method->getLocation(),
3703 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003704 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003705 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003706 }
3707
3708 if (!PureVirtualClassDiagSet)
3709 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3710 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003711}
3712
Anders Carlsson8211eff2009-03-24 01:19:16 +00003713namespace {
John McCall94c3b562010-08-18 09:41:07 +00003714struct AbstractUsageInfo {
3715 Sema &S;
3716 CXXRecordDecl *Record;
3717 CanQualType AbstractType;
3718 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003719
John McCall94c3b562010-08-18 09:41:07 +00003720 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3721 : S(S), Record(Record),
3722 AbstractType(S.Context.getCanonicalType(
3723 S.Context.getTypeDeclType(Record))),
3724 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003725
John McCall94c3b562010-08-18 09:41:07 +00003726 void DiagnoseAbstractType() {
3727 if (Invalid) return;
3728 S.DiagnoseAbstractType(Record);
3729 Invalid = true;
3730 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003731
John McCall94c3b562010-08-18 09:41:07 +00003732 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3733};
3734
3735struct CheckAbstractUsage {
3736 AbstractUsageInfo &Info;
3737 const NamedDecl *Ctx;
3738
3739 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3740 : Info(Info), Ctx(Ctx) {}
3741
3742 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3743 switch (TL.getTypeLocClass()) {
3744#define ABSTRACT_TYPELOC(CLASS, PARENT)
3745#define TYPELOC(CLASS, PARENT) \
3746 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3747#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003748 }
John McCall94c3b562010-08-18 09:41:07 +00003749 }
Mike Stump1eb44332009-09-09 15:08:12 +00003750
John McCall94c3b562010-08-18 09:41:07 +00003751 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3752 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3753 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003754 if (!TL.getArg(I))
3755 continue;
3756
John McCall94c3b562010-08-18 09:41:07 +00003757 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3758 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003759 }
John McCall94c3b562010-08-18 09:41:07 +00003760 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003761
John McCall94c3b562010-08-18 09:41:07 +00003762 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3763 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3764 }
Mike Stump1eb44332009-09-09 15:08:12 +00003765
John McCall94c3b562010-08-18 09:41:07 +00003766 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3767 // Visit the type parameters from a permissive context.
3768 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3769 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3770 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3771 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3772 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3773 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003774 }
John McCall94c3b562010-08-18 09:41:07 +00003775 }
Mike Stump1eb44332009-09-09 15:08:12 +00003776
John McCall94c3b562010-08-18 09:41:07 +00003777 // Visit pointee types from a permissive context.
3778#define CheckPolymorphic(Type) \
3779 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3780 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3781 }
3782 CheckPolymorphic(PointerTypeLoc)
3783 CheckPolymorphic(ReferenceTypeLoc)
3784 CheckPolymorphic(MemberPointerTypeLoc)
3785 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003786 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003787
John McCall94c3b562010-08-18 09:41:07 +00003788 /// Handle all the types we haven't given a more specific
3789 /// implementation for above.
3790 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3791 // Every other kind of type that we haven't called out already
3792 // that has an inner type is either (1) sugar or (2) contains that
3793 // inner type in some way as a subobject.
3794 if (TypeLoc Next = TL.getNextTypeLoc())
3795 return Visit(Next, Sel);
3796
3797 // If there's no inner type and we're in a permissive context,
3798 // don't diagnose.
3799 if (Sel == Sema::AbstractNone) return;
3800
3801 // Check whether the type matches the abstract type.
3802 QualType T = TL.getType();
3803 if (T->isArrayType()) {
3804 Sel = Sema::AbstractArrayType;
3805 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003806 }
John McCall94c3b562010-08-18 09:41:07 +00003807 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3808 if (CT != Info.AbstractType) return;
3809
3810 // It matched; do some magic.
3811 if (Sel == Sema::AbstractArrayType) {
3812 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3813 << T << TL.getSourceRange();
3814 } else {
3815 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3816 << Sel << T << TL.getSourceRange();
3817 }
3818 Info.DiagnoseAbstractType();
3819 }
3820};
3821
3822void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3823 Sema::AbstractDiagSelID Sel) {
3824 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3825}
3826
3827}
3828
3829/// Check for invalid uses of an abstract type in a method declaration.
3830static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3831 CXXMethodDecl *MD) {
3832 // No need to do the check on definitions, which require that
3833 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003834 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003835 return;
3836
3837 // For safety's sake, just ignore it if we don't have type source
3838 // information. This should never happen for non-implicit methods,
3839 // but...
3840 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3841 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3842}
3843
3844/// Check for invalid uses of an abstract type within a class definition.
3845static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3846 CXXRecordDecl *RD) {
3847 for (CXXRecordDecl::decl_iterator
3848 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3849 Decl *D = *I;
3850 if (D->isImplicit()) continue;
3851
3852 // Methods and method templates.
3853 if (isa<CXXMethodDecl>(D)) {
3854 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3855 } else if (isa<FunctionTemplateDecl>(D)) {
3856 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3857 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3858
3859 // Fields and static variables.
3860 } else if (isa<FieldDecl>(D)) {
3861 FieldDecl *FD = cast<FieldDecl>(D);
3862 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3863 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3864 } else if (isa<VarDecl>(D)) {
3865 VarDecl *VD = cast<VarDecl>(D);
3866 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3867 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3868
3869 // Nested classes and class templates.
3870 } else if (isa<CXXRecordDecl>(D)) {
3871 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3872 } else if (isa<ClassTemplateDecl>(D)) {
3873 CheckAbstractClassUsage(Info,
3874 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3875 }
3876 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003877}
3878
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003879/// \brief Perform semantic checks on a class definition that has been
3880/// completing, introducing implicitly-declared members, checking for
3881/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003882void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003883 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003884 return;
3885
John McCall94c3b562010-08-18 09:41:07 +00003886 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3887 AbstractUsageInfo Info(*this, Record);
3888 CheckAbstractClassUsage(Info, Record);
3889 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003890
3891 // If this is not an aggregate type and has no user-declared constructor,
3892 // complain about any non-static data members of reference or const scalar
3893 // type, since they will never get initializers.
3894 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003895 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3896 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003897 bool Complained = false;
3898 for (RecordDecl::field_iterator F = Record->field_begin(),
3899 FEnd = Record->field_end();
3900 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003901 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003902 continue;
3903
Douglas Gregor325e5932010-04-15 00:00:53 +00003904 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003905 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003906 if (!Complained) {
3907 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3908 << Record->getTagKind() << Record;
3909 Complained = true;
3910 }
3911
3912 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3913 << F->getType()->isReferenceType()
3914 << F->getDeclName();
3915 }
3916 }
3917 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003918
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003919 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003920 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003921
3922 if (Record->getIdentifier()) {
3923 // C++ [class.mem]p13:
3924 // If T is the name of a class, then each of the following shall have a
3925 // name different from T:
3926 // - every member of every anonymous union that is a member of class T.
3927 //
3928 // C++ [class.mem]p14:
3929 // In addition, if class T has a user-declared constructor (12.1), every
3930 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00003931 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3932 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3933 ++I) {
3934 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00003935 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3936 isa<IndirectFieldDecl>(D)) {
3937 Diag(D->getLocation(), diag::err_member_name_of_class)
3938 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003939 break;
3940 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003941 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003942 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003943
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003944 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003945 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003946 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003947 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003948 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3949 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3950 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003951
David Blaikieb6b5b972012-09-21 03:21:07 +00003952 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3953 Diag(Record->getLocation(), diag::warn_abstract_final_class);
3954 DiagnoseAbstractType(Record);
3955 }
3956
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003957 if (!Record->isDependentType()) {
3958 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3959 MEnd = Record->method_end();
3960 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00003961 // See if a method overloads virtual methods in a base
3962 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00003963 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003964 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00003965
3966 // Check whether the explicitly-defaulted special members are valid.
3967 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
3968 CheckExplicitlyDefaultedSpecialMember(*M);
3969
3970 // For an explicitly defaulted or deleted special member, we defer
3971 // determining triviality until the class is complete. That time is now!
3972 if (!M->isImplicit() && !M->isUserProvided()) {
3973 CXXSpecialMember CSM = getSpecialMember(*M);
3974 if (CSM != CXXInvalid) {
3975 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
3976
3977 // Inform the class that we've finished declaring this member.
3978 Record->finishedDefaultedOrDeletedMember(*M);
3979 }
3980 }
3981 }
3982 }
3983
3984 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
3985 // function that is not a constructor declares that member function to be
3986 // const. [...] The class of which that function is a member shall be
3987 // a literal type.
3988 //
3989 // If the class has virtual bases, any constexpr members will already have
3990 // been diagnosed by the checks performed on the member declaration, so
3991 // suppress this (less useful) diagnostic.
3992 //
3993 // We delay this until we know whether an explicitly-defaulted (or deleted)
3994 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00003995 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00003996 !Record->isLiteral() && !Record->getNumVBases()) {
3997 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3998 MEnd = Record->method_end();
3999 M != MEnd; ++M) {
4000 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4001 switch (Record->getTemplateSpecializationKind()) {
4002 case TSK_ImplicitInstantiation:
4003 case TSK_ExplicitInstantiationDeclaration:
4004 case TSK_ExplicitInstantiationDefinition:
4005 // If a template instantiates to a non-literal type, but its members
4006 // instantiate to constexpr functions, the template is technically
4007 // ill-formed, but we allow it for sanity.
4008 continue;
4009
4010 case TSK_Undeclared:
4011 case TSK_ExplicitSpecialization:
4012 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4013 diag::err_constexpr_method_non_literal);
4014 break;
4015 }
4016
4017 // Only produce one error per class.
4018 break;
4019 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004020 }
4021 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004022
4023 // Declare inherited constructors. We do this eagerly here because:
4024 // - The standard requires an eager diagnostic for conflicting inherited
4025 // constructors from different classes.
4026 // - The lazy declaration of the other implicit constructors is so as to not
4027 // waste space and performance on classes that are not meant to be
4028 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4029 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004030 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004031}
4032
Richard Smith7756afa2012-06-10 05:43:50 +00004033/// Is the special member function which would be selected to perform the
4034/// specified operation on the specified class type a constexpr constructor?
4035static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4036 Sema::CXXSpecialMember CSM,
4037 bool ConstArg) {
4038 Sema::SpecialMemberOverloadResult *SMOR =
4039 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4040 false, false, false, false);
4041 if (!SMOR || !SMOR->getMethod())
4042 // A constructor we wouldn't select can't be "involved in initializing"
4043 // anything.
4044 return true;
4045 return SMOR->getMethod()->isConstexpr();
4046}
4047
4048/// Determine whether the specified special member function would be constexpr
4049/// if it were implicitly defined.
4050static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4051 Sema::CXXSpecialMember CSM,
4052 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004053 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004054 return false;
4055
4056 // C++11 [dcl.constexpr]p4:
4057 // In the definition of a constexpr constructor [...]
4058 switch (CSM) {
4059 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004060 // Since default constructor lookup is essentially trivial (and cannot
4061 // involve, for instance, template instantiation), we compute whether a
4062 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4063 //
4064 // This is important for performance; we need to know whether the default
4065 // constructor is constexpr to determine whether the type is a literal type.
4066 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4067
Richard Smith7756afa2012-06-10 05:43:50 +00004068 case Sema::CXXCopyConstructor:
4069 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004070 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004071 break;
4072
4073 case Sema::CXXCopyAssignment:
4074 case Sema::CXXMoveAssignment:
4075 case Sema::CXXDestructor:
4076 case Sema::CXXInvalid:
4077 return false;
4078 }
4079
4080 // -- if the class is a non-empty union, or for each non-empty anonymous
4081 // union member of a non-union class, exactly one non-static data member
4082 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004083 //
4084 // If we squint, this is guaranteed, since exactly one non-static data member
4085 // will be initialized (if the constructor isn't deleted), we just don't know
4086 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004087 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004088 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004089
4090 // -- the class shall not have any virtual base classes;
4091 if (ClassDecl->getNumVBases())
4092 return false;
4093
4094 // -- every constructor involved in initializing [...] base class
4095 // sub-objects shall be a constexpr constructor;
4096 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4097 BEnd = ClassDecl->bases_end();
4098 B != BEnd; ++B) {
4099 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4100 if (!BaseType) continue;
4101
4102 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4103 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4104 return false;
4105 }
4106
4107 // -- every constructor involved in initializing non-static data members
4108 // [...] shall be a constexpr constructor;
4109 // -- every non-static data member and base class sub-object shall be
4110 // initialized
4111 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4112 FEnd = ClassDecl->field_end();
4113 F != FEnd; ++F) {
4114 if (F->isInvalidDecl())
4115 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004116 if (const RecordType *RecordTy =
4117 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004118 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4119 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4120 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004121 }
4122 }
4123
4124 // All OK, it's constexpr!
4125 return true;
4126}
4127
Richard Smithb9d0b762012-07-27 04:22:15 +00004128static Sema::ImplicitExceptionSpecification
4129computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4130 switch (S.getSpecialMember(MD)) {
4131 case Sema::CXXDefaultConstructor:
4132 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4133 case Sema::CXXCopyConstructor:
4134 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4135 case Sema::CXXCopyAssignment:
4136 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4137 case Sema::CXXMoveConstructor:
4138 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4139 case Sema::CXXMoveAssignment:
4140 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4141 case Sema::CXXDestructor:
4142 return S.ComputeDefaultedDtorExceptionSpec(MD);
4143 case Sema::CXXInvalid:
4144 break;
4145 }
4146 llvm_unreachable("only special members have implicit exception specs");
4147}
4148
Richard Smithdd25e802012-07-30 23:48:14 +00004149static void
4150updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4151 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4152 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4153 ExceptSpec.getEPI(EPI);
4154 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4155 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4156 FPT->getNumArgs(), EPI));
4157 FD->setType(QualType(NewFPT, 0));
4158}
4159
Richard Smithb9d0b762012-07-27 04:22:15 +00004160void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4161 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4162 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4163 return;
4164
Richard Smithdd25e802012-07-30 23:48:14 +00004165 // Evaluate the exception specification.
4166 ImplicitExceptionSpecification ExceptSpec =
4167 computeImplicitExceptionSpec(*this, Loc, MD);
4168
4169 // Update the type of the special member to use it.
4170 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4171
4172 // A user-provided destructor can be defined outside the class. When that
4173 // happens, be sure to update the exception specification on both
4174 // declarations.
4175 const FunctionProtoType *CanonicalFPT =
4176 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4177 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4178 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4179 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004180}
4181
Richard Smith3003e1d2012-05-15 04:39:51 +00004182void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4183 CXXRecordDecl *RD = MD->getParent();
4184 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004185
Richard Smith3003e1d2012-05-15 04:39:51 +00004186 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4187 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004188
4189 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004190 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004191 bool First = MD == MD->getCanonicalDecl();
4192
4193 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004194
4195 // C++11 [dcl.fct.def.default]p1:
4196 // A function that is explicitly defaulted shall
4197 // -- be a special member function (checked elsewhere),
4198 // -- have the same type (except for ref-qualifiers, and except that a
4199 // copy operation can take a non-const reference) as an implicit
4200 // declaration, and
4201 // -- not have default arguments.
4202 unsigned ExpectedParams = 1;
4203 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4204 ExpectedParams = 0;
4205 if (MD->getNumParams() != ExpectedParams) {
4206 // This also checks for default arguments: a copy or move constructor with a
4207 // default argument is classified as a default constructor, and assignment
4208 // operations and destructors can't have default arguments.
4209 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4210 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004211 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004212 } else if (MD->isVariadic()) {
4213 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4214 << CSM << MD->getSourceRange();
4215 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004216 }
4217
Richard Smith3003e1d2012-05-15 04:39:51 +00004218 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004219
Richard Smith7756afa2012-06-10 05:43:50 +00004220 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004221 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004222 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004223 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004224 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004225
Richard Smith3003e1d2012-05-15 04:39:51 +00004226 QualType ReturnType = Context.VoidTy;
4227 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4228 // Check for return type matching.
4229 ReturnType = Type->getResultType();
4230 QualType ExpectedReturnType =
4231 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4232 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4233 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4234 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4235 HadError = true;
4236 }
4237
4238 // A defaulted special member cannot have cv-qualifiers.
4239 if (Type->getTypeQuals()) {
4240 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4241 << (CSM == CXXMoveAssignment);
4242 HadError = true;
4243 }
4244 }
4245
4246 // Check for parameter type matching.
4247 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004248 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004249 if (ExpectedParams && ArgType->isReferenceType()) {
4250 // Argument must be reference to possibly-const T.
4251 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004252 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004253
4254 if (ReferentType.isVolatileQualified()) {
4255 Diag(MD->getLocation(),
4256 diag::err_defaulted_special_member_volatile_param) << CSM;
4257 HadError = true;
4258 }
4259
Richard Smith7756afa2012-06-10 05:43:50 +00004260 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004261 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4262 Diag(MD->getLocation(),
4263 diag::err_defaulted_special_member_copy_const_param)
4264 << (CSM == CXXCopyAssignment);
4265 // FIXME: Explain why this special member can't be const.
4266 } else {
4267 Diag(MD->getLocation(),
4268 diag::err_defaulted_special_member_move_const_param)
4269 << (CSM == CXXMoveAssignment);
4270 }
4271 HadError = true;
4272 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004273 } else if (ExpectedParams) {
4274 // A copy assignment operator can take its argument by value, but a
4275 // defaulted one cannot.
4276 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004277 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004278 HadError = true;
4279 }
Sean Huntbe631222011-05-17 20:44:43 +00004280
Richard Smith61802452011-12-22 02:22:31 +00004281 // C++11 [dcl.fct.def.default]p2:
4282 // An explicitly-defaulted function may be declared constexpr only if it
4283 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004284 // Do not apply this rule to members of class templates, since core issue 1358
4285 // makes such functions always instantiate to constexpr functions. For
4286 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004287 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4288 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004289 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4290 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4291 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004292 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004293 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004294 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004295
Richard Smith61802452011-12-22 02:22:31 +00004296 // and may have an explicit exception-specification only if it is compatible
4297 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004298 if (Type->hasExceptionSpec()) {
4299 // Delay the check if this is the first declaration of the special member,
4300 // since we may not have parsed some necessary in-class initializers yet.
4301 if (First)
4302 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4303 else
4304 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4305 }
Richard Smith61802452011-12-22 02:22:31 +00004306
4307 // If a function is explicitly defaulted on its first declaration,
4308 if (First) {
4309 // -- it is implicitly considered to be constexpr if the implicit
4310 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004311 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004312
Richard Smith3003e1d2012-05-15 04:39:51 +00004313 // -- it is implicitly considered to have the same exception-specification
4314 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004315 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4316 EPI.ExceptionSpecType = EST_Unevaluated;
4317 EPI.ExceptionSpecDecl = MD;
4318 MD->setType(Context.getFunctionType(ReturnType, &ArgType,
4319 ExpectedParams, EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004320 }
4321
Richard Smith3003e1d2012-05-15 04:39:51 +00004322 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004323 if (First) {
4324 MD->setDeletedAsWritten();
4325 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004326 // C++11 [dcl.fct.def.default]p4:
4327 // [For a] user-provided explicitly-defaulted function [...] if such a
4328 // function is implicitly defined as deleted, the program is ill-formed.
4329 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4330 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004331 }
4332 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004333
Richard Smith3003e1d2012-05-15 04:39:51 +00004334 if (HadError)
4335 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004336}
4337
Richard Smith1d28caf2012-12-11 01:14:52 +00004338/// Check whether the exception specification provided for an
4339/// explicitly-defaulted special member matches the exception specification
4340/// that would have been generated for an implicit special member, per
4341/// C++11 [dcl.fct.def.default]p2.
4342void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4343 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4344 // Compute the implicit exception specification.
4345 FunctionProtoType::ExtProtoInfo EPI;
4346 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4347 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4348 Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4349
4350 // Ensure that it matches.
4351 CheckEquivalentExceptionSpec(
4352 PDiag(diag::err_incorrect_defaulted_exception_spec)
4353 << getSpecialMember(MD), PDiag(),
4354 ImplicitType, SourceLocation(),
4355 SpecifiedType, MD->getLocation());
4356}
4357
4358void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4359 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4360 I != N; ++I)
4361 CheckExplicitlyDefaultedMemberExceptionSpec(
4362 DelayedDefaultedMemberExceptionSpecs[I].first,
4363 DelayedDefaultedMemberExceptionSpecs[I].second);
4364
4365 DelayedDefaultedMemberExceptionSpecs.clear();
4366}
4367
Richard Smith7d5088a2012-02-18 02:02:13 +00004368namespace {
4369struct SpecialMemberDeletionInfo {
4370 Sema &S;
4371 CXXMethodDecl *MD;
4372 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004373 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004374
4375 // Properties of the special member, computed for convenience.
4376 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4377 SourceLocation Loc;
4378
4379 bool AllFieldsAreConst;
4380
4381 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004382 Sema::CXXSpecialMember CSM, bool Diagnose)
4383 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004384 IsConstructor(false), IsAssignment(false), IsMove(false),
4385 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4386 AllFieldsAreConst(true) {
4387 switch (CSM) {
4388 case Sema::CXXDefaultConstructor:
4389 case Sema::CXXCopyConstructor:
4390 IsConstructor = true;
4391 break;
4392 case Sema::CXXMoveConstructor:
4393 IsConstructor = true;
4394 IsMove = true;
4395 break;
4396 case Sema::CXXCopyAssignment:
4397 IsAssignment = true;
4398 break;
4399 case Sema::CXXMoveAssignment:
4400 IsAssignment = true;
4401 IsMove = true;
4402 break;
4403 case Sema::CXXDestructor:
4404 break;
4405 case Sema::CXXInvalid:
4406 llvm_unreachable("invalid special member kind");
4407 }
4408
4409 if (MD->getNumParams()) {
4410 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4411 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4412 }
4413 }
4414
4415 bool inUnion() const { return MD->getParent()->isUnion(); }
4416
4417 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004418 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4419 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004420 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004421 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4422 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4423 Quals = 0;
4424 return S.LookupSpecialMember(Class, CSM,
4425 ConstArg || (Quals & Qualifiers::Const),
4426 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004427 MD->getRefQualifier() == RQ_RValue,
4428 TQ & Qualifiers::Const,
4429 TQ & Qualifiers::Volatile);
4430 }
4431
Richard Smith6c4c36c2012-03-30 20:53:28 +00004432 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004433
Richard Smith6c4c36c2012-03-30 20:53:28 +00004434 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004435 bool shouldDeleteForField(FieldDecl *FD);
4436 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004437
Richard Smith517bb842012-07-18 03:51:16 +00004438 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4439 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004440 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4441 Sema::SpecialMemberOverloadResult *SMOR,
4442 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004443
4444 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004445};
4446}
4447
John McCall12d8d802012-04-09 20:53:23 +00004448/// Is the given special member inaccessible when used on the given
4449/// sub-object.
4450bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4451 CXXMethodDecl *target) {
4452 /// If we're operating on a base class, the object type is the
4453 /// type of this special member.
4454 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004455 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004456 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4457 objectTy = S.Context.getTypeDeclType(MD->getParent());
4458 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4459
4460 // If we're operating on a field, the object type is the type of the field.
4461 } else {
4462 objectTy = S.Context.getTypeDeclType(target->getParent());
4463 }
4464
4465 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4466}
4467
Richard Smith6c4c36c2012-03-30 20:53:28 +00004468/// Check whether we should delete a special member due to the implicit
4469/// definition containing a call to a special member of a subobject.
4470bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4471 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4472 bool IsDtorCallInCtor) {
4473 CXXMethodDecl *Decl = SMOR->getMethod();
4474 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4475
4476 int DiagKind = -1;
4477
4478 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4479 DiagKind = !Decl ? 0 : 1;
4480 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4481 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004482 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004483 DiagKind = 3;
4484 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4485 !Decl->isTrivial()) {
4486 // A member of a union must have a trivial corresponding special member.
4487 // As a weird special case, a destructor call from a union's constructor
4488 // must be accessible and non-deleted, but need not be trivial. Such a
4489 // destructor is never actually called, but is semantically checked as
4490 // if it were.
4491 DiagKind = 4;
4492 }
4493
4494 if (DiagKind == -1)
4495 return false;
4496
4497 if (Diagnose) {
4498 if (Field) {
4499 S.Diag(Field->getLocation(),
4500 diag::note_deleted_special_member_class_subobject)
4501 << CSM << MD->getParent() << /*IsField*/true
4502 << Field << DiagKind << IsDtorCallInCtor;
4503 } else {
4504 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4505 S.Diag(Base->getLocStart(),
4506 diag::note_deleted_special_member_class_subobject)
4507 << CSM << MD->getParent() << /*IsField*/false
4508 << Base->getType() << DiagKind << IsDtorCallInCtor;
4509 }
4510
4511 if (DiagKind == 1)
4512 S.NoteDeletedFunction(Decl);
4513 // FIXME: Explain inaccessibility if DiagKind == 3.
4514 }
4515
4516 return true;
4517}
4518
Richard Smith9a561d52012-02-26 09:11:52 +00004519/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004520/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004521bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004522 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004523 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004524
4525 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004526 // -- any direct or virtual base class, or non-static data member with no
4527 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004528 // either M has no default constructor or overload resolution as applied
4529 // to M's default constructor results in an ambiguity or in a function
4530 // that is deleted or inaccessible
4531 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4532 // -- a direct or virtual base class B that cannot be copied/moved because
4533 // overload resolution, as applied to B's corresponding special member,
4534 // results in an ambiguity or a function that is deleted or inaccessible
4535 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004536 // C++11 [class.dtor]p5:
4537 // -- any direct or virtual base class [...] has a type with a destructor
4538 // that is deleted or inaccessible
4539 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004540 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004541 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004542 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004543
Richard Smith6c4c36c2012-03-30 20:53:28 +00004544 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4545 // -- any direct or virtual base class or non-static data member has a
4546 // type with a destructor that is deleted or inaccessible
4547 if (IsConstructor) {
4548 Sema::SpecialMemberOverloadResult *SMOR =
4549 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4550 false, false, false, false, false);
4551 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4552 return true;
4553 }
4554
Richard Smith9a561d52012-02-26 09:11:52 +00004555 return false;
4556}
4557
4558/// Check whether we should delete a special member function due to the class
4559/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004560bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004561 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004562 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004563}
4564
4565/// Check whether we should delete a special member function due to the class
4566/// having a particular non-static data member.
4567bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4568 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4569 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4570
4571 if (CSM == Sema::CXXDefaultConstructor) {
4572 // For a default constructor, all references must be initialized in-class
4573 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004574 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4575 if (Diagnose)
4576 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4577 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004578 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004579 }
Richard Smith79363f52012-02-27 06:07:25 +00004580 // C++11 [class.ctor]p5: any non-variant non-static data member of
4581 // const-qualified type (or array thereof) with no
4582 // brace-or-equal-initializer does not have a user-provided default
4583 // constructor.
4584 if (!inUnion() && FieldType.isConstQualified() &&
4585 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004586 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4587 if (Diagnose)
4588 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004589 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004590 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004591 }
4592
4593 if (inUnion() && !FieldType.isConstQualified())
4594 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004595 } else if (CSM == Sema::CXXCopyConstructor) {
4596 // For a copy constructor, data members must not be of rvalue reference
4597 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004598 if (FieldType->isRValueReferenceType()) {
4599 if (Diagnose)
4600 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4601 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004602 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004603 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004604 } else if (IsAssignment) {
4605 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004606 if (FieldType->isReferenceType()) {
4607 if (Diagnose)
4608 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4609 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004610 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004611 }
4612 if (!FieldRecord && FieldType.isConstQualified()) {
4613 // C++11 [class.copy]p23:
4614 // -- a non-static data member of const non-class type (or array thereof)
4615 if (Diagnose)
4616 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004617 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004618 return true;
4619 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004620 }
4621
4622 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004623 // Some additional restrictions exist on the variant members.
4624 if (!inUnion() && FieldRecord->isUnion() &&
4625 FieldRecord->isAnonymousStructOrUnion()) {
4626 bool AllVariantFieldsAreConst = true;
4627
Richard Smithdf8dc862012-03-29 19:00:10 +00004628 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004629 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4630 UE = FieldRecord->field_end();
4631 UI != UE; ++UI) {
4632 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004633
4634 if (!UnionFieldType.isConstQualified())
4635 AllVariantFieldsAreConst = false;
4636
Richard Smith9a561d52012-02-26 09:11:52 +00004637 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4638 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004639 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4640 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004641 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004642 }
4643
4644 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004645 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004646 FieldRecord->field_begin() != FieldRecord->field_end()) {
4647 if (Diagnose)
4648 S.Diag(FieldRecord->getLocation(),
4649 diag::note_deleted_default_ctor_all_const)
4650 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004651 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004652 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004653
Richard Smithdf8dc862012-03-29 19:00:10 +00004654 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004655 // This is technically non-conformant, but sanity demands it.
4656 return false;
4657 }
4658
Richard Smith517bb842012-07-18 03:51:16 +00004659 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4660 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004661 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004662 }
4663
4664 return false;
4665}
4666
4667/// C++11 [class.ctor] p5:
4668/// A defaulted default constructor for a class X is defined as deleted if
4669/// X is a union and all of its variant members are of const-qualified type.
4670bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004671 // This is a silly definition, because it gives an empty union a deleted
4672 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004673 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4674 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4675 if (Diagnose)
4676 S.Diag(MD->getParent()->getLocation(),
4677 diag::note_deleted_default_ctor_all_const)
4678 << MD->getParent() << /*not anonymous union*/0;
4679 return true;
4680 }
4681 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004682}
4683
4684/// Determine whether a defaulted special member function should be defined as
4685/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4686/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004687bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4688 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004689 if (MD->isInvalidDecl())
4690 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004691 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004692 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004693 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004694 return false;
4695
Richard Smith7d5088a2012-02-18 02:02:13 +00004696 // C++11 [expr.lambda.prim]p19:
4697 // The closure type associated with a lambda-expression has a
4698 // deleted (8.4.3) default constructor and a deleted copy
4699 // assignment operator.
4700 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004701 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4702 if (Diagnose)
4703 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004704 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004705 }
4706
Richard Smith5bdaac52012-04-02 20:59:25 +00004707 // For an anonymous struct or union, the copy and assignment special members
4708 // will never be used, so skip the check. For an anonymous union declared at
4709 // namespace scope, the constructor and destructor are used.
4710 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4711 RD->isAnonymousStructOrUnion())
4712 return false;
4713
Richard Smith6c4c36c2012-03-30 20:53:28 +00004714 // C++11 [class.copy]p7, p18:
4715 // If the class definition declares a move constructor or move assignment
4716 // operator, an implicitly declared copy constructor or copy assignment
4717 // operator is defined as deleted.
4718 if (MD->isImplicit() &&
4719 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4720 CXXMethodDecl *UserDeclaredMove = 0;
4721
4722 // In Microsoft mode, a user-declared move only causes the deletion of the
4723 // corresponding copy operation, not both copy operations.
4724 if (RD->hasUserDeclaredMoveConstructor() &&
4725 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4726 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004727
4728 // Find any user-declared move constructor.
4729 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4730 E = RD->ctor_end(); I != E; ++I) {
4731 if (I->isMoveConstructor()) {
4732 UserDeclaredMove = *I;
4733 break;
4734 }
4735 }
Richard Smith1c931be2012-04-02 18:40:40 +00004736 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004737 } else if (RD->hasUserDeclaredMoveAssignment() &&
4738 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4739 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004740
4741 // Find any user-declared move assignment operator.
4742 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4743 E = RD->method_end(); I != E; ++I) {
4744 if (I->isMoveAssignmentOperator()) {
4745 UserDeclaredMove = *I;
4746 break;
4747 }
4748 }
Richard Smith1c931be2012-04-02 18:40:40 +00004749 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004750 }
4751
4752 if (UserDeclaredMove) {
4753 Diag(UserDeclaredMove->getLocation(),
4754 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004755 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004756 << UserDeclaredMove->isMoveAssignmentOperator();
4757 return true;
4758 }
4759 }
Sean Hunte16da072011-10-10 06:18:57 +00004760
Richard Smith5bdaac52012-04-02 20:59:25 +00004761 // Do access control from the special member function
4762 ContextRAII MethodContext(*this, MD);
4763
Richard Smith9a561d52012-02-26 09:11:52 +00004764 // C++11 [class.dtor]p5:
4765 // -- for a virtual destructor, lookup of the non-array deallocation function
4766 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004767 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004768 FunctionDecl *OperatorDelete = 0;
4769 DeclarationName Name =
4770 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4771 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004772 OperatorDelete, false)) {
4773 if (Diagnose)
4774 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004775 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004776 }
Richard Smith9a561d52012-02-26 09:11:52 +00004777 }
4778
Richard Smith6c4c36c2012-03-30 20:53:28 +00004779 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004780
Sean Huntcdee3fe2011-05-11 22:34:38 +00004781 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004782 BE = RD->bases_end(); BI != BE; ++BI)
4783 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004784 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004785 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004786
4787 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004788 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004789 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004790 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004791
4792 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004793 FE = RD->field_end(); FI != FE; ++FI)
4794 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004795 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004796 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004797
Richard Smith7d5088a2012-02-18 02:02:13 +00004798 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004799 return true;
4800
4801 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004802}
4803
Richard Smithac713512012-12-08 02:53:02 +00004804/// Perform lookup for a special member of the specified kind, and determine
4805/// whether it is trivial. If the triviality can be determined without the
4806/// lookup, skip it. This is intended for use when determining whether a
4807/// special member of a containing object is trivial, and thus does not ever
4808/// perform overload resolution for default constructors.
4809///
4810/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4811/// member that was most likely to be intended to be trivial, if any.
4812static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4813 Sema::CXXSpecialMember CSM, unsigned Quals,
4814 CXXMethodDecl **Selected) {
4815 if (Selected)
4816 *Selected = 0;
4817
4818 switch (CSM) {
4819 case Sema::CXXInvalid:
4820 llvm_unreachable("not a special member");
4821
4822 case Sema::CXXDefaultConstructor:
4823 // C++11 [class.ctor]p5:
4824 // A default constructor is trivial if:
4825 // - all the [direct subobjects] have trivial default constructors
4826 //
4827 // Note, no overload resolution is performed in this case.
4828 if (RD->hasTrivialDefaultConstructor())
4829 return true;
4830
4831 if (Selected) {
4832 // If there's a default constructor which could have been trivial, dig it
4833 // out. Otherwise, if there's any user-provided default constructor, point
4834 // to that as an example of why there's not a trivial one.
4835 CXXConstructorDecl *DefCtor = 0;
4836 if (RD->needsImplicitDefaultConstructor())
4837 S.DeclareImplicitDefaultConstructor(RD);
4838 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4839 CE = RD->ctor_end(); CI != CE; ++CI) {
4840 if (!CI->isDefaultConstructor())
4841 continue;
4842 DefCtor = *CI;
4843 if (!DefCtor->isUserProvided())
4844 break;
4845 }
4846
4847 *Selected = DefCtor;
4848 }
4849
4850 return false;
4851
4852 case Sema::CXXDestructor:
4853 // C++11 [class.dtor]p5:
4854 // A destructor is trivial if:
4855 // - all the direct [subobjects] have trivial destructors
4856 if (RD->hasTrivialDestructor())
4857 return true;
4858
4859 if (Selected) {
4860 if (RD->needsImplicitDestructor())
4861 S.DeclareImplicitDestructor(RD);
4862 *Selected = RD->getDestructor();
4863 }
4864
4865 return false;
4866
4867 case Sema::CXXCopyConstructor:
4868 // C++11 [class.copy]p12:
4869 // A copy constructor is trivial if:
4870 // - the constructor selected to copy each direct [subobject] is trivial
4871 if (RD->hasTrivialCopyConstructor()) {
4872 if (Quals == Qualifiers::Const)
4873 // We must either select the trivial copy constructor or reach an
4874 // ambiguity; no need to actually perform overload resolution.
4875 return true;
4876 } else if (!Selected) {
4877 return false;
4878 }
4879 // In C++98, we are not supposed to perform overload resolution here, but we
4880 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4881 // cases like B as having a non-trivial copy constructor:
4882 // struct A { template<typename T> A(T&); };
4883 // struct B { mutable A a; };
4884 goto NeedOverloadResolution;
4885
4886 case Sema::CXXCopyAssignment:
4887 // C++11 [class.copy]p25:
4888 // A copy assignment operator is trivial if:
4889 // - the assignment operator selected to copy each direct [subobject] is
4890 // trivial
4891 if (RD->hasTrivialCopyAssignment()) {
4892 if (Quals == Qualifiers::Const)
4893 return true;
4894 } else if (!Selected) {
4895 return false;
4896 }
4897 // In C++98, we are not supposed to perform overload resolution here, but we
4898 // treat that as a language defect.
4899 goto NeedOverloadResolution;
4900
4901 case Sema::CXXMoveConstructor:
4902 case Sema::CXXMoveAssignment:
4903 NeedOverloadResolution:
4904 Sema::SpecialMemberOverloadResult *SMOR =
4905 S.LookupSpecialMember(RD, CSM,
4906 Quals & Qualifiers::Const,
4907 Quals & Qualifiers::Volatile,
4908 /*RValueThis*/false, /*ConstThis*/false,
4909 /*VolatileThis*/false);
4910
4911 // The standard doesn't describe how to behave if the lookup is ambiguous.
4912 // We treat it as not making the member non-trivial, just like the standard
4913 // mandates for the default constructor. This should rarely matter, because
4914 // the member will also be deleted.
4915 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4916 return true;
4917
4918 if (!SMOR->getMethod()) {
4919 assert(SMOR->getKind() ==
4920 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4921 return false;
4922 }
4923
4924 // We deliberately don't check if we found a deleted special member. We're
4925 // not supposed to!
4926 if (Selected)
4927 *Selected = SMOR->getMethod();
4928 return SMOR->getMethod()->isTrivial();
4929 }
4930
4931 llvm_unreachable("unknown special method kind");
4932}
4933
4934CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
4935 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
4936 CI != CE; ++CI)
4937 if (!CI->isImplicit())
4938 return *CI;
4939
4940 // Look for constructor templates.
4941 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
4942 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
4943 if (CXXConstructorDecl *CD =
4944 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
4945 return CD;
4946 }
4947
4948 return 0;
4949}
4950
4951/// The kind of subobject we are checking for triviality. The values of this
4952/// enumeration are used in diagnostics.
4953enum TrivialSubobjectKind {
4954 /// The subobject is a base class.
4955 TSK_BaseClass,
4956 /// The subobject is a non-static data member.
4957 TSK_Field,
4958 /// The object is actually the complete object.
4959 TSK_CompleteObject
4960};
4961
4962/// Check whether the special member selected for a given type would be trivial.
4963static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
4964 QualType SubType,
4965 Sema::CXXSpecialMember CSM,
4966 TrivialSubobjectKind Kind,
4967 bool Diagnose) {
4968 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
4969 if (!SubRD)
4970 return true;
4971
4972 CXXMethodDecl *Selected;
4973 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
4974 Diagnose ? &Selected : 0))
4975 return true;
4976
4977 if (Diagnose) {
4978 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
4979 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
4980 << Kind << SubType.getUnqualifiedType();
4981 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
4982 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
4983 } else if (!Selected)
4984 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
4985 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
4986 else if (Selected->isUserProvided()) {
4987 if (Kind == TSK_CompleteObject)
4988 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
4989 << Kind << SubType.getUnqualifiedType() << CSM;
4990 else {
4991 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
4992 << Kind << SubType.getUnqualifiedType() << CSM;
4993 S.Diag(Selected->getLocation(), diag::note_declared_at);
4994 }
4995 } else {
4996 if (Kind != TSK_CompleteObject)
4997 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
4998 << Kind << SubType.getUnqualifiedType() << CSM;
4999
5000 // Explain why the defaulted or deleted special member isn't trivial.
5001 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5002 }
5003 }
5004
5005 return false;
5006}
5007
5008/// Check whether the members of a class type allow a special member to be
5009/// trivial.
5010static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5011 Sema::CXXSpecialMember CSM,
5012 bool ConstArg, bool Diagnose) {
5013 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5014 FE = RD->field_end(); FI != FE; ++FI) {
5015 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5016 continue;
5017
5018 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5019
5020 // Pretend anonymous struct or union members are members of this class.
5021 if (FI->isAnonymousStructOrUnion()) {
5022 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5023 CSM, ConstArg, Diagnose))
5024 return false;
5025 continue;
5026 }
5027
5028 // C++11 [class.ctor]p5:
5029 // A default constructor is trivial if [...]
5030 // -- no non-static data member of its class has a
5031 // brace-or-equal-initializer
5032 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5033 if (Diagnose)
5034 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5035 return false;
5036 }
5037
5038 // Objective C ARC 4.3.5:
5039 // [...] nontrivally ownership-qualified types are [...] not trivially
5040 // default constructible, copy constructible, move constructible, copy
5041 // assignable, move assignable, or destructible [...]
5042 if (S.getLangOpts().ObjCAutoRefCount &&
5043 FieldType.hasNonTrivialObjCLifetime()) {
5044 if (Diagnose)
5045 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5046 << RD << FieldType.getObjCLifetime();
5047 return false;
5048 }
5049
5050 if (ConstArg && !FI->isMutable())
5051 FieldType.addConst();
5052 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5053 TSK_Field, Diagnose))
5054 return false;
5055 }
5056
5057 return true;
5058}
5059
5060/// Diagnose why the specified class does not have a trivial special member of
5061/// the given kind.
5062void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5063 QualType Ty = Context.getRecordType(RD);
5064 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5065 Ty.addConst();
5066
5067 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5068 TSK_CompleteObject, /*Diagnose*/true);
5069}
5070
5071/// Determine whether a defaulted or deleted special member function is trivial,
5072/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5073/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5074bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5075 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005076 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5077
5078 CXXRecordDecl *RD = MD->getParent();
5079
5080 bool ConstArg = false;
5081 ParmVarDecl *Param0 = MD->getNumParams() ? MD->getParamDecl(0) : 0;
5082
5083 // C++11 [class.copy]p12, p25:
5084 // A [special member] is trivial if its declared parameter type is the same
5085 // as if it had been implicitly declared [...]
5086 switch (CSM) {
5087 case CXXDefaultConstructor:
5088 case CXXDestructor:
5089 // Trivial default constructors and destructors cannot have parameters.
5090 break;
5091
5092 case CXXCopyConstructor:
5093 case CXXCopyAssignment: {
5094 // Trivial copy operations always have const, non-volatile parameter types.
5095 ConstArg = true;
5096 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5097 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5098 if (Diagnose)
5099 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5100 << Param0->getSourceRange() << Param0->getType()
5101 << Context.getLValueReferenceType(
5102 Context.getRecordType(RD).withConst());
5103 return false;
5104 }
5105 break;
5106 }
5107
5108 case CXXMoveConstructor:
5109 case CXXMoveAssignment: {
5110 // Trivial move operations always have non-cv-qualified parameters.
5111 const RValueReferenceType *RT =
5112 Param0->getType()->getAs<RValueReferenceType>();
5113 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5114 if (Diagnose)
5115 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5116 << Param0->getSourceRange() << Param0->getType()
5117 << Context.getRValueReferenceType(Context.getRecordType(RD));
5118 return false;
5119 }
5120 break;
5121 }
5122
5123 case CXXInvalid:
5124 llvm_unreachable("not a special member");
5125 }
5126
5127 // FIXME: We require that the parameter-declaration-clause is equivalent to
5128 // that of an implicit declaration, not just that the declared parameter type
5129 // matches, in order to prevent absuridities like a function simultaneously
5130 // being a trivial copy constructor and a non-trivial default constructor.
5131 // This issue has not yet been assigned a core issue number.
5132 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5133 if (Diagnose)
5134 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5135 diag::note_nontrivial_default_arg)
5136 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5137 return false;
5138 }
5139 if (MD->isVariadic()) {
5140 if (Diagnose)
5141 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5142 return false;
5143 }
5144
5145 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5146 // A copy/move [constructor or assignment operator] is trivial if
5147 // -- the [member] selected to copy/move each direct base class subobject
5148 // is trivial
5149 //
5150 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5151 // A [default constructor or destructor] is trivial if
5152 // -- all the direct base classes have trivial [default constructors or
5153 // destructors]
5154 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5155 BE = RD->bases_end(); BI != BE; ++BI)
5156 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5157 ConstArg ? BI->getType().withConst()
5158 : BI->getType(),
5159 CSM, TSK_BaseClass, Diagnose))
5160 return false;
5161
5162 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5163 // A copy/move [constructor or assignment operator] for a class X is
5164 // trivial if
5165 // -- for each non-static data member of X that is of class type (or array
5166 // thereof), the constructor selected to copy/move that member is
5167 // trivial
5168 //
5169 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5170 // A [default constructor or destructor] is trivial if
5171 // -- for all of the non-static data members of its class that are of class
5172 // type (or array thereof), each such class has a trivial [default
5173 // constructor or destructor]
5174 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5175 return false;
5176
5177 // C++11 [class.dtor]p5:
5178 // A destructor is trivial if [...]
5179 // -- the destructor is not virtual
5180 if (CSM == CXXDestructor && MD->isVirtual()) {
5181 if (Diagnose)
5182 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5183 return false;
5184 }
5185
5186 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5187 // A [special member] for class X is trivial if [...]
5188 // -- class X has no virtual functions and no virtual base classes
5189 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5190 if (!Diagnose)
5191 return false;
5192
5193 if (RD->getNumVBases()) {
5194 // Check for virtual bases. We already know that the corresponding
5195 // member in all bases is trivial, so vbases must all be direct.
5196 CXXBaseSpecifier &BS = *RD->vbases_begin();
5197 assert(BS.isVirtual());
5198 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5199 return false;
5200 }
5201
5202 // Must have a virtual method.
5203 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5204 ME = RD->method_end(); MI != ME; ++MI) {
5205 if (MI->isVirtual()) {
5206 SourceLocation MLoc = MI->getLocStart();
5207 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5208 return false;
5209 }
5210 }
5211
5212 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5213 }
5214
5215 // Looks like it's trivial!
5216 return true;
5217}
5218
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005219/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005220namespace {
5221 struct FindHiddenVirtualMethodData {
5222 Sema *S;
5223 CXXMethodDecl *Method;
5224 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005225 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005226 };
5227}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005228
David Blaikie5f750682012-10-19 00:53:08 +00005229/// \brief Check whether any most overriden method from MD in Methods
5230static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5231 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5232 if (MD->size_overridden_methods() == 0)
5233 return Methods.count(MD->getCanonicalDecl());
5234 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5235 E = MD->end_overridden_methods();
5236 I != E; ++I)
5237 if (CheckMostOverridenMethods(*I, Methods))
5238 return true;
5239 return false;
5240}
5241
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005242/// \brief Member lookup function that determines whether a given C++
5243/// method overloads virtual methods in a base class without overriding any,
5244/// to be used with CXXRecordDecl::lookupInBases().
5245static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5246 CXXBasePath &Path,
5247 void *UserData) {
5248 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5249
5250 FindHiddenVirtualMethodData &Data
5251 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5252
5253 DeclarationName Name = Data.Method->getDeclName();
5254 assert(Name.getNameKind() == DeclarationName::Identifier);
5255
5256 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005257 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005258 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005259 !Path.Decls.empty();
5260 Path.Decls = Path.Decls.slice(1)) {
5261 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005262 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005263 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005264 foundSameNameMethod = true;
5265 // Interested only in hidden virtual methods.
5266 if (!MD->isVirtual())
5267 continue;
5268 // If the method we are checking overrides a method from its base
5269 // don't warn about the other overloaded methods.
5270 if (!Data.S->IsOverload(Data.Method, MD, false))
5271 return true;
5272 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005273 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005274 overloadedMethods.push_back(MD);
5275 }
5276 }
5277
5278 if (foundSameNameMethod)
5279 Data.OverloadedMethods.append(overloadedMethods.begin(),
5280 overloadedMethods.end());
5281 return foundSameNameMethod;
5282}
5283
David Blaikie5f750682012-10-19 00:53:08 +00005284/// \brief Add the most overriden methods from MD to Methods
5285static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5286 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5287 if (MD->size_overridden_methods() == 0)
5288 Methods.insert(MD->getCanonicalDecl());
5289 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5290 E = MD->end_overridden_methods();
5291 I != E; ++I)
5292 AddMostOverridenMethods(*I, Methods);
5293}
5294
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005295/// \brief See if a method overloads virtual methods in a base class without
5296/// overriding any.
5297void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5298 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005299 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005300 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005301 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005302 return;
5303
5304 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5305 /*bool RecordPaths=*/false,
5306 /*bool DetectVirtual=*/false);
5307 FindHiddenVirtualMethodData Data;
5308 Data.Method = MD;
5309 Data.S = this;
5310
5311 // Keep the base methods that were overriden or introduced in the subclass
5312 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005313 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5314 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5315 NamedDecl *ND = *I;
5316 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005317 ND = shad->getTargetDecl();
5318 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5319 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005320 }
5321
5322 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5323 !Data.OverloadedMethods.empty()) {
5324 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5325 << MD << (Data.OverloadedMethods.size() > 1);
5326
5327 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5328 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5329 Diag(overloadedMD->getLocation(),
5330 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5331 }
5332 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005333}
5334
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005335void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005336 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005337 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005338 SourceLocation RBrac,
5339 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005340 if (!TagDecl)
5341 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005342
Douglas Gregor42af25f2009-05-11 19:58:34 +00005343 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005344
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005345 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5346 if (l->getKind() != AttributeList::AT_Visibility)
5347 continue;
5348 l->setInvalid();
5349 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5350 l->getName();
5351 }
5352
David Blaikie77b6de02011-09-22 02:58:26 +00005353 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005354 // strict aliasing violation!
5355 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005356 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005357
Douglas Gregor23c94db2010-07-02 17:43:08 +00005358 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005359 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005360}
5361
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005362/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5363/// special functions, such as the default constructor, copy
5364/// constructor, or destructor, to the given C++ class (C++
5365/// [special]p1). This routine can only be executed just before the
5366/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005367void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005368 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005369 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005370
Richard Smithbc2a35d2012-12-08 08:32:28 +00005371 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005372 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005373
Richard Smithbc2a35d2012-12-08 08:32:28 +00005374 // If the properties or semantics of the copy constructor couldn't be
5375 // determined while the class was being declared, force a declaration
5376 // of it now.
5377 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5378 DeclareImplicitCopyConstructor(ClassDecl);
5379 }
5380
Richard Smith80ad52f2013-01-02 11:42:31 +00005381 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005382 ++ASTContext::NumImplicitMoveConstructors;
5383
Richard Smithbc2a35d2012-12-08 08:32:28 +00005384 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5385 DeclareImplicitMoveConstructor(ClassDecl);
5386 }
5387
Douglas Gregora376d102010-07-02 21:50:04 +00005388 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5389 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005390
5391 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005392 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005393 // it shows up in the right place in the vtable and that we diagnose
5394 // problems with the implicit exception specification.
5395 if (ClassDecl->isDynamicClass() ||
5396 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005397 DeclareImplicitCopyAssignment(ClassDecl);
5398 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005399
Richard Smith80ad52f2013-01-02 11:42:31 +00005400 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005401 ++ASTContext::NumImplicitMoveAssignmentOperators;
5402
5403 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005404 if (ClassDecl->isDynamicClass() ||
5405 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005406 DeclareImplicitMoveAssignment(ClassDecl);
5407 }
5408
Douglas Gregor4923aa22010-07-02 20:37:36 +00005409 if (!ClassDecl->hasUserDeclaredDestructor()) {
5410 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005411
5412 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005413 // have to declare the destructor immediately. This ensures that, e.g., it
5414 // shows up in the right place in the vtable and that we diagnose problems
5415 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005416 if (ClassDecl->isDynamicClass() ||
5417 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005418 DeclareImplicitDestructor(ClassDecl);
5419 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005420}
5421
Francois Pichet8387e2a2011-04-22 22:18:13 +00005422void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5423 if (!D)
5424 return;
5425
5426 int NumParamList = D->getNumTemplateParameterLists();
5427 for (int i = 0; i < NumParamList; i++) {
5428 TemplateParameterList* Params = D->getTemplateParameterList(i);
5429 for (TemplateParameterList::iterator Param = Params->begin(),
5430 ParamEnd = Params->end();
5431 Param != ParamEnd; ++Param) {
5432 NamedDecl *Named = cast<NamedDecl>(*Param);
5433 if (Named->getDeclName()) {
5434 S->AddDecl(Named);
5435 IdResolver.AddDecl(Named);
5436 }
5437 }
5438 }
5439}
5440
John McCalld226f652010-08-21 09:40:31 +00005441void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005442 if (!D)
5443 return;
5444
5445 TemplateParameterList *Params = 0;
5446 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5447 Params = Template->getTemplateParameters();
5448 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5449 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5450 Params = PartialSpec->getTemplateParameters();
5451 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005452 return;
5453
Douglas Gregor6569d682009-05-27 23:11:45 +00005454 for (TemplateParameterList::iterator Param = Params->begin(),
5455 ParamEnd = Params->end();
5456 Param != ParamEnd; ++Param) {
5457 NamedDecl *Named = cast<NamedDecl>(*Param);
5458 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005459 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005460 IdResolver.AddDecl(Named);
5461 }
5462 }
5463}
5464
John McCalld226f652010-08-21 09:40:31 +00005465void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005466 if (!RecordD) return;
5467 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005468 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005469 PushDeclContext(S, Record);
5470}
5471
John McCalld226f652010-08-21 09:40:31 +00005472void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005473 if (!RecordD) return;
5474 PopDeclContext();
5475}
5476
Douglas Gregor72b505b2008-12-16 21:30:33 +00005477/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5478/// parsing a top-level (non-nested) C++ class, and we are now
5479/// parsing those parts of the given Method declaration that could
5480/// not be parsed earlier (C++ [class.mem]p2), such as default
5481/// arguments. This action should enter the scope of the given
5482/// Method declaration as if we had just parsed the qualified method
5483/// name. However, it should not bring the parameters into scope;
5484/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005485void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005486}
5487
5488/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5489/// C++ method declaration. We're (re-)introducing the given
5490/// function parameter into scope for use in parsing later parts of
5491/// the method declaration. For example, we could see an
5492/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005493void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005494 if (!ParamD)
5495 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005496
John McCalld226f652010-08-21 09:40:31 +00005497 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005498
5499 // If this parameter has an unparsed default argument, clear it out
5500 // to make way for the parsed default argument.
5501 if (Param->hasUnparsedDefaultArg())
5502 Param->setDefaultArg(0);
5503
John McCalld226f652010-08-21 09:40:31 +00005504 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005505 if (Param->getDeclName())
5506 IdResolver.AddDecl(Param);
5507}
5508
5509/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5510/// processing the delayed method declaration for Method. The method
5511/// declaration is now considered finished. There may be a separate
5512/// ActOnStartOfFunctionDef action later (not necessarily
5513/// immediately!) for this method, if it was also defined inside the
5514/// class body.
John McCalld226f652010-08-21 09:40:31 +00005515void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005516 if (!MethodD)
5517 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005518
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005519 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005520
John McCalld226f652010-08-21 09:40:31 +00005521 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005522
5523 // Now that we have our default arguments, check the constructor
5524 // again. It could produce additional diagnostics or affect whether
5525 // the class has implicitly-declared destructors, among other
5526 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005527 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5528 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005529
5530 // Check the default arguments, which we may have added.
5531 if (!Method->isInvalidDecl())
5532 CheckCXXDefaultArguments(Method);
5533}
5534
Douglas Gregor42a552f2008-11-05 20:51:48 +00005535/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005536/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005537/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005538/// emit diagnostics and set the invalid bit to true. In any case, the type
5539/// will be updated to reflect a well-formed type for the constructor and
5540/// returned.
5541QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005542 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005543 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005544
5545 // C++ [class.ctor]p3:
5546 // A constructor shall not be virtual (10.3) or static (9.4). A
5547 // constructor can be invoked for a const, volatile or const
5548 // volatile object. A constructor shall not be declared const,
5549 // volatile, or const volatile (9.3.2).
5550 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005551 if (!D.isInvalidType())
5552 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5553 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5554 << SourceRange(D.getIdentifierLoc());
5555 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005556 }
John McCalld931b082010-08-26 03:08:43 +00005557 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005558 if (!D.isInvalidType())
5559 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5560 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5561 << SourceRange(D.getIdentifierLoc());
5562 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005563 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005564 }
Mike Stump1eb44332009-09-09 15:08:12 +00005565
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005566 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005567 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005568 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005569 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5570 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005571 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005572 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5573 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005574 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005575 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5576 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005577 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005578 }
Mike Stump1eb44332009-09-09 15:08:12 +00005579
Douglas Gregorc938c162011-01-26 05:01:58 +00005580 // C++0x [class.ctor]p4:
5581 // A constructor shall not be declared with a ref-qualifier.
5582 if (FTI.hasRefQualifier()) {
5583 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5584 << FTI.RefQualifierIsLValueRef
5585 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5586 D.setInvalidType();
5587 }
5588
Douglas Gregor42a552f2008-11-05 20:51:48 +00005589 // Rebuild the function type "R" without any type qualifiers (in
5590 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005591 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005592 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005593 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5594 return R;
5595
5596 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5597 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005598 EPI.RefQualifier = RQ_None;
5599
Chris Lattner65401802009-04-25 08:28:21 +00005600 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005601 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005602}
5603
Douglas Gregor72b505b2008-12-16 21:30:33 +00005604/// CheckConstructor - Checks a fully-formed constructor for
5605/// well-formedness, issuing any diagnostics required. Returns true if
5606/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005607void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005608 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005609 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5610 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005611 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005612
5613 // C++ [class.copy]p3:
5614 // A declaration of a constructor for a class X is ill-formed if
5615 // its first parameter is of type (optionally cv-qualified) X and
5616 // either there are no other parameters or else all other
5617 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005618 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005619 ((Constructor->getNumParams() == 1) ||
5620 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005621 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5622 Constructor->getTemplateSpecializationKind()
5623 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005624 QualType ParamType = Constructor->getParamDecl(0)->getType();
5625 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5626 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005627 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005628 const char *ConstRef
5629 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5630 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005631 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005632 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005633
5634 // FIXME: Rather that making the constructor invalid, we should endeavor
5635 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005636 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005637 }
5638 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005639}
5640
John McCall15442822010-08-04 01:04:25 +00005641/// CheckDestructor - Checks a fully-formed destructor definition for
5642/// well-formedness, issuing any diagnostics required. Returns true
5643/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005644bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005645 CXXRecordDecl *RD = Destructor->getParent();
5646
5647 if (Destructor->isVirtual()) {
5648 SourceLocation Loc;
5649
5650 if (!Destructor->isImplicit())
5651 Loc = Destructor->getLocation();
5652 else
5653 Loc = RD->getLocation();
5654
5655 // If we have a virtual destructor, look up the deallocation function
5656 FunctionDecl *OperatorDelete = 0;
5657 DeclarationName Name =
5658 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005659 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005660 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005661
Eli Friedman5f2987c2012-02-02 03:46:19 +00005662 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005663
5664 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005665 }
Anders Carlsson37909802009-11-30 21:24:50 +00005666
5667 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005668}
5669
Mike Stump1eb44332009-09-09 15:08:12 +00005670static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005671FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5672 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5673 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005674 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005675}
5676
Douglas Gregor42a552f2008-11-05 20:51:48 +00005677/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5678/// the well-formednes of the destructor declarator @p D with type @p
5679/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005680/// emit diagnostics and set the declarator to invalid. Even if this happens,
5681/// will be updated to reflect a well-formed type for the destructor and
5682/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005683QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005684 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005685 // C++ [class.dtor]p1:
5686 // [...] A typedef-name that names a class is a class-name
5687 // (7.1.3); however, a typedef-name that names a class shall not
5688 // be used as the identifier in the declarator for a destructor
5689 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005690 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005691 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005692 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005693 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005694 else if (const TemplateSpecializationType *TST =
5695 DeclaratorType->getAs<TemplateSpecializationType>())
5696 if (TST->isTypeAlias())
5697 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5698 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005699
5700 // C++ [class.dtor]p2:
5701 // A destructor is used to destroy objects of its class type. A
5702 // destructor takes no parameters, and no return type can be
5703 // specified for it (not even void). The address of a destructor
5704 // shall not be taken. A destructor shall not be static. A
5705 // destructor can be invoked for a const, volatile or const
5706 // volatile object. A destructor shall not be declared const,
5707 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005708 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005709 if (!D.isInvalidType())
5710 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5711 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005712 << SourceRange(D.getIdentifierLoc())
5713 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5714
John McCalld931b082010-08-26 03:08:43 +00005715 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005716 }
Chris Lattner65401802009-04-25 08:28:21 +00005717 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005718 // Destructors don't have return types, but the parser will
5719 // happily parse something like:
5720 //
5721 // class X {
5722 // float ~X();
5723 // };
5724 //
5725 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005726 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5727 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5728 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005729 }
Mike Stump1eb44332009-09-09 15:08:12 +00005730
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005731 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005732 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005733 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005734 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5735 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005736 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005737 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5738 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005739 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005740 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5741 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005742 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005743 }
5744
Douglas Gregorc938c162011-01-26 05:01:58 +00005745 // C++0x [class.dtor]p2:
5746 // A destructor shall not be declared with a ref-qualifier.
5747 if (FTI.hasRefQualifier()) {
5748 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5749 << FTI.RefQualifierIsLValueRef
5750 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5751 D.setInvalidType();
5752 }
5753
Douglas Gregor42a552f2008-11-05 20:51:48 +00005754 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005755 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005756 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5757
5758 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005759 FTI.freeArgs();
5760 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005761 }
5762
Mike Stump1eb44332009-09-09 15:08:12 +00005763 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005764 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005765 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005766 D.setInvalidType();
5767 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005768
5769 // Rebuild the function type "R" without any type qualifiers or
5770 // parameters (in case any of the errors above fired) and with
5771 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005772 // types.
John McCalle23cf432010-12-14 08:05:40 +00005773 if (!D.isInvalidType())
5774 return R;
5775
Douglas Gregord92ec472010-07-01 05:10:53 +00005776 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005777 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5778 EPI.Variadic = false;
5779 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005780 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005781 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005782}
5783
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005784/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5785/// well-formednes of the conversion function declarator @p D with
5786/// type @p R. If there are any errors in the declarator, this routine
5787/// will emit diagnostics and return true. Otherwise, it will return
5788/// false. Either way, the type @p R will be updated to reflect a
5789/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005790void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005791 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005792 // C++ [class.conv.fct]p1:
5793 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005794 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005795 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005796 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005797 if (!D.isInvalidType())
5798 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5799 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5800 << SourceRange(D.getIdentifierLoc());
5801 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005802 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005803 }
John McCalla3f81372010-04-13 00:04:31 +00005804
5805 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5806
Chris Lattner6e475012009-04-25 08:35:12 +00005807 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005808 // Conversion functions don't have return types, but the parser will
5809 // happily parse something like:
5810 //
5811 // class X {
5812 // float operator bool();
5813 // };
5814 //
5815 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005816 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5817 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5818 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005819 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005820 }
5821
John McCalla3f81372010-04-13 00:04:31 +00005822 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5823
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005824 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005825 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005826 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5827
5828 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005829 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005830 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005831 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005832 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005833 D.setInvalidType();
5834 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005835
John McCalla3f81372010-04-13 00:04:31 +00005836 // Diagnose "&operator bool()" and other such nonsense. This
5837 // is actually a gcc extension which we don't support.
5838 if (Proto->getResultType() != ConvType) {
5839 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5840 << Proto->getResultType();
5841 D.setInvalidType();
5842 ConvType = Proto->getResultType();
5843 }
5844
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005845 // C++ [class.conv.fct]p4:
5846 // The conversion-type-id shall not represent a function type nor
5847 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005848 if (ConvType->isArrayType()) {
5849 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5850 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005851 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005852 } else if (ConvType->isFunctionType()) {
5853 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5854 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005855 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005856 }
5857
5858 // Rebuild the function type "R" without any parameters (in case any
5859 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005860 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005861 if (D.isInvalidType())
5862 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005863
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005864 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005865 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005866 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005867 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005868 diag::warn_cxx98_compat_explicit_conversion_functions :
5869 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005870 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005871}
5872
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005873/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5874/// the declaration of the given C++ conversion function. This routine
5875/// is responsible for recording the conversion function in the C++
5876/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005877Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005878 assert(Conversion && "Expected to receive a conversion function declaration");
5879
Douglas Gregor9d350972008-12-12 08:25:50 +00005880 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005881
5882 // Make sure we aren't redeclaring the conversion function.
5883 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005884
5885 // C++ [class.conv.fct]p1:
5886 // [...] A conversion function is never used to convert a
5887 // (possibly cv-qualified) object to the (possibly cv-qualified)
5888 // same object type (or a reference to it), to a (possibly
5889 // cv-qualified) base class of that type (or a reference to it),
5890 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005891 // FIXME: Suppress this warning if the conversion function ends up being a
5892 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005893 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005894 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005895 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005896 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005897 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5898 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005899 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005900 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005901 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5902 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005903 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005904 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005905 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005906 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005907 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005908 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005909 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005910 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005911 }
5912
Douglas Gregore80622f2010-09-29 04:25:11 +00005913 if (FunctionTemplateDecl *ConversionTemplate
5914 = Conversion->getDescribedFunctionTemplate())
5915 return ConversionTemplate;
5916
John McCalld226f652010-08-21 09:40:31 +00005917 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005918}
5919
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005920//===----------------------------------------------------------------------===//
5921// Namespace Handling
5922//===----------------------------------------------------------------------===//
5923
Richard Smithd1a55a62012-10-04 22:13:39 +00005924/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5925/// reopened.
5926static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5927 SourceLocation Loc,
5928 IdentifierInfo *II, bool *IsInline,
5929 NamespaceDecl *PrevNS) {
5930 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00005931
Richard Smithc969e6a2012-10-05 01:46:25 +00005932 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5933 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5934 // inline namespaces, with the intention of bringing names into namespace std.
5935 //
5936 // We support this just well enough to get that case working; this is not
5937 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00005938 if (*IsInline && II && II->getName().startswith("__atomic") &&
5939 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00005940 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00005941 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5942 NS = NS->getPreviousDecl())
5943 NS->setInline(*IsInline);
5944 // Patch up the lookup table for the containing namespace. This isn't really
5945 // correct, but it's good enough for this particular case.
5946 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5947 E = PrevNS->decls_end(); I != E; ++I)
5948 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5949 PrevNS->getParent()->makeDeclVisibleInContext(ND);
5950 return;
5951 }
5952
5953 if (PrevNS->isInline())
5954 // The user probably just forgot the 'inline', so suggest that it
5955 // be added back.
5956 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5957 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
5958 else
5959 S.Diag(Loc, diag::err_inline_namespace_mismatch)
5960 << IsInline;
5961
5962 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
5963 *IsInline = PrevNS->isInline();
5964}
John McCallea318642010-08-26 09:15:37 +00005965
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005966/// ActOnStartNamespaceDef - This is called at the start of a namespace
5967/// definition.
John McCalld226f652010-08-21 09:40:31 +00005968Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005969 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005970 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005971 SourceLocation IdentLoc,
5972 IdentifierInfo *II,
5973 SourceLocation LBrace,
5974 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005975 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5976 // For anonymous namespace, take the location of the left brace.
5977 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005978 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005979 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005980 bool IsStd = false;
5981 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005982 Scope *DeclRegionScope = NamespcScope->getParent();
5983
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005984 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005985 if (II) {
5986 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005987 // The identifier in an original-namespace-definition shall not
5988 // have been previously defined in the declarative region in
5989 // which the original-namespace-definition appears. The
5990 // identifier in an original-namespace-definition is the name of
5991 // the namespace. Subsequently in that declarative region, it is
5992 // treated as an original-namespace-name.
5993 //
5994 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005995 // look through using directives, just look for any ordinary names.
5996
5997 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005998 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5999 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006000 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006001 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6002 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6003 ++I) {
6004 if ((*I)->getIdentifierNamespace() & IDNS) {
6005 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006006 break;
6007 }
6008 }
6009
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006010 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6011
6012 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006013 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006014 if (IsInline != PrevNS->isInline())
6015 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6016 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006017 } else if (PrevDecl) {
6018 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006019 Diag(Loc, diag::err_redefinition_different_kind)
6020 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006021 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006022 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006023 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006024 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006025 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006026 // This is the first "real" definition of the namespace "std", so update
6027 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006028 PrevNS = getStdNamespace();
6029 IsStd = true;
6030 AddToKnown = !IsInline;
6031 } else {
6032 // We've seen this namespace for the first time.
6033 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006034 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006035 } else {
John McCall9aeed322009-10-01 00:25:31 +00006036 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006037
6038 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006039 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006040 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006041 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006042 } else {
6043 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006044 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006045 }
6046
Richard Smithd1a55a62012-10-04 22:13:39 +00006047 if (PrevNS && IsInline != PrevNS->isInline())
6048 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6049 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006050 }
6051
6052 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6053 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006054 if (IsInvalid)
6055 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006056
6057 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006058
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006059 // FIXME: Should we be merging attributes?
6060 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006061 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006062
6063 if (IsStd)
6064 StdNamespace = Namespc;
6065 if (AddToKnown)
6066 KnownNamespaces[Namespc] = false;
6067
6068 if (II) {
6069 PushOnScopeChains(Namespc, DeclRegionScope);
6070 } else {
6071 // Link the anonymous namespace into its parent.
6072 DeclContext *Parent = CurContext->getRedeclContext();
6073 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6074 TU->setAnonymousNamespace(Namespc);
6075 } else {
6076 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006077 }
John McCall9aeed322009-10-01 00:25:31 +00006078
Douglas Gregora4181472010-03-24 00:46:35 +00006079 CurContext->addDecl(Namespc);
6080
John McCall9aeed322009-10-01 00:25:31 +00006081 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6082 // behaves as if it were replaced by
6083 // namespace unique { /* empty body */ }
6084 // using namespace unique;
6085 // namespace unique { namespace-body }
6086 // where all occurrences of 'unique' in a translation unit are
6087 // replaced by the same identifier and this identifier differs
6088 // from all other identifiers in the entire program.
6089
6090 // We just create the namespace with an empty name and then add an
6091 // implicit using declaration, just like the standard suggests.
6092 //
6093 // CodeGen enforces the "universally unique" aspect by giving all
6094 // declarations semantically contained within an anonymous
6095 // namespace internal linkage.
6096
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006097 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006098 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006099 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006100 /* 'using' */ LBrace,
6101 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006102 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006103 /* identifier */ SourceLocation(),
6104 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006105 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006106 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006107 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006108 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006109 }
6110
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006111 ActOnDocumentableDecl(Namespc);
6112
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006113 // Although we could have an invalid decl (i.e. the namespace name is a
6114 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006115 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6116 // for the namespace has the declarations that showed up in that particular
6117 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006118 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006119 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006120}
6121
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006122/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6123/// is a namespace alias, returns the namespace it points to.
6124static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6125 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6126 return AD->getNamespace();
6127 return dyn_cast_or_null<NamespaceDecl>(D);
6128}
6129
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006130/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6131/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006132void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006133 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6134 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006135 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006136 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006137 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006138 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006139}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006140
John McCall384aff82010-08-25 07:42:41 +00006141CXXRecordDecl *Sema::getStdBadAlloc() const {
6142 return cast_or_null<CXXRecordDecl>(
6143 StdBadAlloc.get(Context.getExternalSource()));
6144}
6145
6146NamespaceDecl *Sema::getStdNamespace() const {
6147 return cast_or_null<NamespaceDecl>(
6148 StdNamespace.get(Context.getExternalSource()));
6149}
6150
Douglas Gregor66992202010-06-29 17:53:46 +00006151/// \brief Retrieve the special "std" namespace, which may require us to
6152/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006153NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006154 if (!StdNamespace) {
6155 // The "std" namespace has not yet been defined, so build one implicitly.
6156 StdNamespace = NamespaceDecl::Create(Context,
6157 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006158 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006159 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006160 &PP.getIdentifierTable().get("std"),
6161 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006162 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006163 }
6164
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006165 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006166}
6167
Sebastian Redl395e04d2012-01-17 22:49:33 +00006168bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006169 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006170 "Looking for std::initializer_list outside of C++.");
6171
6172 // We're looking for implicit instantiations of
6173 // template <typename E> class std::initializer_list.
6174
6175 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6176 return false;
6177
Sebastian Redl84760e32012-01-17 22:49:58 +00006178 ClassTemplateDecl *Template = 0;
6179 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006180
Sebastian Redl84760e32012-01-17 22:49:58 +00006181 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006182
Sebastian Redl84760e32012-01-17 22:49:58 +00006183 ClassTemplateSpecializationDecl *Specialization =
6184 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6185 if (!Specialization)
6186 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006187
Sebastian Redl84760e32012-01-17 22:49:58 +00006188 Template = Specialization->getSpecializedTemplate();
6189 Arguments = Specialization->getTemplateArgs().data();
6190 } else if (const TemplateSpecializationType *TST =
6191 Ty->getAs<TemplateSpecializationType>()) {
6192 Template = dyn_cast_or_null<ClassTemplateDecl>(
6193 TST->getTemplateName().getAsTemplateDecl());
6194 Arguments = TST->getArgs();
6195 }
6196 if (!Template)
6197 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006198
6199 if (!StdInitializerList) {
6200 // Haven't recognized std::initializer_list yet, maybe this is it.
6201 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6202 if (TemplateClass->getIdentifier() !=
6203 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006204 !getStdNamespace()->InEnclosingNamespaceSetOf(
6205 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006206 return false;
6207 // This is a template called std::initializer_list, but is it the right
6208 // template?
6209 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006210 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006211 return false;
6212 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6213 return false;
6214
6215 // It's the right template.
6216 StdInitializerList = Template;
6217 }
6218
6219 if (Template != StdInitializerList)
6220 return false;
6221
6222 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006223 if (Element)
6224 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006225 return true;
6226}
6227
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006228static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6229 NamespaceDecl *Std = S.getStdNamespace();
6230 if (!Std) {
6231 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6232 return 0;
6233 }
6234
6235 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6236 Loc, Sema::LookupOrdinaryName);
6237 if (!S.LookupQualifiedName(Result, Std)) {
6238 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6239 return 0;
6240 }
6241 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6242 if (!Template) {
6243 Result.suppressDiagnostics();
6244 // We found something weird. Complain about the first thing we found.
6245 NamedDecl *Found = *Result.begin();
6246 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6247 return 0;
6248 }
6249
6250 // We found some template called std::initializer_list. Now verify that it's
6251 // correct.
6252 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006253 if (Params->getMinRequiredArguments() != 1 ||
6254 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006255 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6256 return 0;
6257 }
6258
6259 return Template;
6260}
6261
6262QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6263 if (!StdInitializerList) {
6264 StdInitializerList = LookupStdInitializerList(*this, Loc);
6265 if (!StdInitializerList)
6266 return QualType();
6267 }
6268
6269 TemplateArgumentListInfo Args(Loc, Loc);
6270 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6271 Context.getTrivialTypeSourceInfo(Element,
6272 Loc)));
6273 return Context.getCanonicalType(
6274 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6275}
6276
Sebastian Redl98d36062012-01-17 22:50:14 +00006277bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6278 // C++ [dcl.init.list]p2:
6279 // A constructor is an initializer-list constructor if its first parameter
6280 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6281 // std::initializer_list<E> for some type E, and either there are no other
6282 // parameters or else all other parameters have default arguments.
6283 if (Ctor->getNumParams() < 1 ||
6284 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6285 return false;
6286
6287 QualType ArgType = Ctor->getParamDecl(0)->getType();
6288 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6289 ArgType = RT->getPointeeType().getUnqualifiedType();
6290
6291 return isStdInitializerList(ArgType, 0);
6292}
6293
Douglas Gregor9172aa62011-03-26 22:25:30 +00006294/// \brief Determine whether a using statement is in a context where it will be
6295/// apply in all contexts.
6296static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6297 switch (CurContext->getDeclKind()) {
6298 case Decl::TranslationUnit:
6299 return true;
6300 case Decl::LinkageSpec:
6301 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6302 default:
6303 return false;
6304 }
6305}
6306
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006307namespace {
6308
6309// Callback to only accept typo corrections that are namespaces.
6310class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6311 public:
6312 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6313 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6314 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6315 }
6316 return false;
6317 }
6318};
6319
6320}
6321
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006322static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6323 CXXScopeSpec &SS,
6324 SourceLocation IdentLoc,
6325 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006326 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006327 R.clear();
6328 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006329 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006330 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006331 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6332 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006333 if (DeclContext *DC = S.computeDeclContext(SS, false))
6334 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6335 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006336 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6337 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006338 else
6339 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6340 << Ident << CorrectedQuotedStr
6341 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006342
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006343 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6344 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006345
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006346 R.addDecl(Corrected.getCorrectionDecl());
6347 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006348 }
6349 return false;
6350}
6351
John McCalld226f652010-08-21 09:40:31 +00006352Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006353 SourceLocation UsingLoc,
6354 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006355 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006356 SourceLocation IdentLoc,
6357 IdentifierInfo *NamespcName,
6358 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006359 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6360 assert(NamespcName && "Invalid NamespcName.");
6361 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006362
6363 // This can only happen along a recovery path.
6364 while (S->getFlags() & Scope::TemplateParamScope)
6365 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006366 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006367
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006368 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006369 NestedNameSpecifier *Qualifier = 0;
6370 if (SS.isSet())
6371 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6372
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006373 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006374 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6375 LookupParsedName(R, S, &SS);
6376 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006377 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006378
Douglas Gregor66992202010-06-29 17:53:46 +00006379 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006380 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006381 // Allow "using namespace std;" or "using namespace ::std;" even if
6382 // "std" hasn't been defined yet, for GCC compatibility.
6383 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6384 NamespcName->isStr("std")) {
6385 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006386 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006387 R.resolveKind();
6388 }
6389 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006390 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006391 }
6392
John McCallf36e02d2009-10-09 21:13:30 +00006393 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006394 NamedDecl *Named = R.getFoundDecl();
6395 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6396 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006397 // C++ [namespace.udir]p1:
6398 // A using-directive specifies that the names in the nominated
6399 // namespace can be used in the scope in which the
6400 // using-directive appears after the using-directive. During
6401 // unqualified name lookup (3.4.1), the names appear as if they
6402 // were declared in the nearest enclosing namespace which
6403 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006404 // namespace. [Note: in this context, "contains" means "contains
6405 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006406
6407 // Find enclosing context containing both using-directive and
6408 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006409 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006410 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6411 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6412 CommonAncestor = CommonAncestor->getParent();
6413
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006414 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006415 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006416 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006417
Douglas Gregor9172aa62011-03-26 22:25:30 +00006418 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006419 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006420 Diag(IdentLoc, diag::warn_using_directive_in_header);
6421 }
6422
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006423 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006424 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006425 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006426 }
6427
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006428 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006429 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006430}
6431
6432void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006433 // If the scope has an associated entity and the using directive is at
6434 // namespace or translation unit scope, add the UsingDirectiveDecl into
6435 // its lookup structure so qualified name lookup can find it.
6436 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6437 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006438 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006439 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006440 // Otherwise, it is at block sope. The using-directives will affect lookup
6441 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006442 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006443}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006444
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006445
John McCalld226f652010-08-21 09:40:31 +00006446Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006447 AccessSpecifier AS,
6448 bool HasUsingKeyword,
6449 SourceLocation UsingLoc,
6450 CXXScopeSpec &SS,
6451 UnqualifiedId &Name,
6452 AttributeList *AttrList,
6453 bool IsTypeName,
6454 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006455 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006456
Douglas Gregor12c118a2009-11-04 16:30:06 +00006457 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006458 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006459 case UnqualifiedId::IK_Identifier:
6460 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006461 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006462 case UnqualifiedId::IK_ConversionFunctionId:
6463 break;
6464
6465 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006466 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006467 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006468 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006469 getLangOpts().CPlusPlus11 ?
Richard Smitha1366cb2012-04-27 19:33:05 +00006470 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6471 // instead once inheriting constructors work.
6472 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00006473 diag::err_using_decl_constructor)
6474 << SS.getRange();
6475
Richard Smith80ad52f2013-01-02 11:42:31 +00006476 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006477
John McCalld226f652010-08-21 09:40:31 +00006478 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006479
6480 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006481 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006482 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006483 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006484
6485 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006486 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006487 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006488 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006489 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006490
6491 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6492 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006493 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006494 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006495
John McCall60fa3cf2009-12-11 02:10:03 +00006496 // Warn about using declarations.
6497 // TODO: store that the declaration was written without 'using' and
6498 // talk about access decls instead of using decls in the
6499 // diagnostics.
6500 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006501 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006502
6503 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006504 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006505 }
6506
Douglas Gregor56c04582010-12-16 00:46:58 +00006507 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6508 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6509 return 0;
6510
John McCall9488ea12009-11-17 05:59:44 +00006511 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006512 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006513 /* IsInstantiation */ false,
6514 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006515 if (UD)
6516 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006517
John McCalld226f652010-08-21 09:40:31 +00006518 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006519}
6520
Douglas Gregor09acc982010-07-07 23:08:52 +00006521/// \brief Determine whether a using declaration considers the given
6522/// declarations as "equivalent", e.g., if they are redeclarations of
6523/// the same entity or are both typedefs of the same type.
6524static bool
6525IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6526 bool &SuppressRedeclaration) {
6527 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6528 SuppressRedeclaration = false;
6529 return true;
6530 }
6531
Richard Smith162e1c12011-04-15 14:24:37 +00006532 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6533 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006534 SuppressRedeclaration = true;
6535 return Context.hasSameType(TD1->getUnderlyingType(),
6536 TD2->getUnderlyingType());
6537 }
6538
6539 return false;
6540}
6541
6542
John McCall9f54ad42009-12-10 09:41:52 +00006543/// Determines whether to create a using shadow decl for a particular
6544/// decl, given the set of decls existing prior to this using lookup.
6545bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6546 const LookupResult &Previous) {
6547 // Diagnose finding a decl which is not from a base class of the
6548 // current class. We do this now because there are cases where this
6549 // function will silently decide not to build a shadow decl, which
6550 // will pre-empt further diagnostics.
6551 //
6552 // We don't need to do this in C++0x because we do the check once on
6553 // the qualifier.
6554 //
6555 // FIXME: diagnose the following if we care enough:
6556 // struct A { int foo; };
6557 // struct B : A { using A::foo; };
6558 // template <class T> struct C : A {};
6559 // template <class T> struct D : C<T> { using B::foo; } // <---
6560 // This is invalid (during instantiation) in C++03 because B::foo
6561 // resolves to the using decl in B, which is not a base class of D<T>.
6562 // We can't diagnose it immediately because C<T> is an unknown
6563 // specialization. The UsingShadowDecl in D<T> then points directly
6564 // to A::foo, which will look well-formed when we instantiate.
6565 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006566 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006567 DeclContext *OrigDC = Orig->getDeclContext();
6568
6569 // Handle enums and anonymous structs.
6570 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6571 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6572 while (OrigRec->isAnonymousStructOrUnion())
6573 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6574
6575 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6576 if (OrigDC == CurContext) {
6577 Diag(Using->getLocation(),
6578 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006579 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006580 Diag(Orig->getLocation(), diag::note_using_decl_target);
6581 return true;
6582 }
6583
Douglas Gregordc355712011-02-25 00:36:19 +00006584 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006585 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006586 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006587 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006588 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006589 Diag(Orig->getLocation(), diag::note_using_decl_target);
6590 return true;
6591 }
6592 }
6593
6594 if (Previous.empty()) return false;
6595
6596 NamedDecl *Target = Orig;
6597 if (isa<UsingShadowDecl>(Target))
6598 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6599
John McCalld7533ec2009-12-11 02:33:26 +00006600 // If the target happens to be one of the previous declarations, we
6601 // don't have a conflict.
6602 //
6603 // FIXME: but we might be increasing its access, in which case we
6604 // should redeclare it.
6605 NamedDecl *NonTag = 0, *Tag = 0;
6606 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6607 I != E; ++I) {
6608 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006609 bool Result;
6610 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6611 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006612
6613 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6614 }
6615
John McCall9f54ad42009-12-10 09:41:52 +00006616 if (Target->isFunctionOrFunctionTemplate()) {
6617 FunctionDecl *FD;
6618 if (isa<FunctionTemplateDecl>(Target))
6619 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6620 else
6621 FD = cast<FunctionDecl>(Target);
6622
6623 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006624 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006625 case Ovl_Overload:
6626 return false;
6627
6628 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006629 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006630 break;
6631
6632 // We found a decl with the exact signature.
6633 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006634 // If we're in a record, we want to hide the target, so we
6635 // return true (without a diagnostic) to tell the caller not to
6636 // build a shadow decl.
6637 if (CurContext->isRecord())
6638 return true;
6639
6640 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006641 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006642 break;
6643 }
6644
6645 Diag(Target->getLocation(), diag::note_using_decl_target);
6646 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6647 return true;
6648 }
6649
6650 // Target is not a function.
6651
John McCall9f54ad42009-12-10 09:41:52 +00006652 if (isa<TagDecl>(Target)) {
6653 // No conflict between a tag and a non-tag.
6654 if (!Tag) return false;
6655
John McCall41ce66f2009-12-10 19:51:03 +00006656 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006657 Diag(Target->getLocation(), diag::note_using_decl_target);
6658 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6659 return true;
6660 }
6661
6662 // No conflict between a tag and a non-tag.
6663 if (!NonTag) return false;
6664
John McCall41ce66f2009-12-10 19:51:03 +00006665 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006666 Diag(Target->getLocation(), diag::note_using_decl_target);
6667 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6668 return true;
6669}
6670
John McCall9488ea12009-11-17 05:59:44 +00006671/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006672UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006673 UsingDecl *UD,
6674 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006675
6676 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006677 NamedDecl *Target = Orig;
6678 if (isa<UsingShadowDecl>(Target)) {
6679 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6680 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006681 }
6682
6683 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006684 = UsingShadowDecl::Create(Context, CurContext,
6685 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006686 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006687
6688 Shadow->setAccess(UD->getAccess());
6689 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6690 Shadow->setInvalidDecl();
6691
John McCall9488ea12009-11-17 05:59:44 +00006692 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006693 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006694 else
John McCall604e7f12009-12-08 07:46:18 +00006695 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006696
John McCall604e7f12009-12-08 07:46:18 +00006697
John McCall9f54ad42009-12-10 09:41:52 +00006698 return Shadow;
6699}
John McCall604e7f12009-12-08 07:46:18 +00006700
John McCall9f54ad42009-12-10 09:41:52 +00006701/// Hides a using shadow declaration. This is required by the current
6702/// using-decl implementation when a resolvable using declaration in a
6703/// class is followed by a declaration which would hide or override
6704/// one or more of the using decl's targets; for example:
6705///
6706/// struct Base { void foo(int); };
6707/// struct Derived : Base {
6708/// using Base::foo;
6709/// void foo(int);
6710/// };
6711///
6712/// The governing language is C++03 [namespace.udecl]p12:
6713///
6714/// When a using-declaration brings names from a base class into a
6715/// derived class scope, member functions in the derived class
6716/// override and/or hide member functions with the same name and
6717/// parameter types in a base class (rather than conflicting).
6718///
6719/// There are two ways to implement this:
6720/// (1) optimistically create shadow decls when they're not hidden
6721/// by existing declarations, or
6722/// (2) don't create any shadow decls (or at least don't make them
6723/// visible) until we've fully parsed/instantiated the class.
6724/// The problem with (1) is that we might have to retroactively remove
6725/// a shadow decl, which requires several O(n) operations because the
6726/// decl structures are (very reasonably) not designed for removal.
6727/// (2) avoids this but is very fiddly and phase-dependent.
6728void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006729 if (Shadow->getDeclName().getNameKind() ==
6730 DeclarationName::CXXConversionFunctionName)
6731 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6732
John McCall9f54ad42009-12-10 09:41:52 +00006733 // Remove it from the DeclContext...
6734 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006735
John McCall9f54ad42009-12-10 09:41:52 +00006736 // ...and the scope, if applicable...
6737 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006738 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006739 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006740 }
6741
John McCall9f54ad42009-12-10 09:41:52 +00006742 // ...and the using decl.
6743 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6744
6745 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006746 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006747}
6748
John McCall7ba107a2009-11-18 02:36:19 +00006749/// Builds a using declaration.
6750///
6751/// \param IsInstantiation - Whether this call arises from an
6752/// instantiation of an unresolved using declaration. We treat
6753/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006754NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6755 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006756 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006757 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006758 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006759 bool IsInstantiation,
6760 bool IsTypeName,
6761 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006762 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006763 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006764 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006765
Anders Carlsson550b14b2009-08-28 05:49:21 +00006766 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006767
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006768 if (SS.isEmpty()) {
6769 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006770 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006771 }
Mike Stump1eb44332009-09-09 15:08:12 +00006772
John McCall9f54ad42009-12-10 09:41:52 +00006773 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006774 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006775 ForRedeclaration);
6776 Previous.setHideTags(false);
6777 if (S) {
6778 LookupName(Previous, S);
6779
6780 // It is really dumb that we have to do this.
6781 LookupResult::Filter F = Previous.makeFilter();
6782 while (F.hasNext()) {
6783 NamedDecl *D = F.next();
6784 if (!isDeclInScope(D, CurContext, S))
6785 F.erase();
6786 }
6787 F.done();
6788 } else {
6789 assert(IsInstantiation && "no scope in non-instantiation");
6790 assert(CurContext->isRecord() && "scope not record in instantiation");
6791 LookupQualifiedName(Previous, CurContext);
6792 }
6793
John McCall9f54ad42009-12-10 09:41:52 +00006794 // Check for invalid redeclarations.
6795 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6796 return 0;
6797
6798 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006799 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6800 return 0;
6801
John McCallaf8e6ed2009-11-12 03:15:40 +00006802 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006803 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006804 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006805 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006806 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006807 // FIXME: not all declaration name kinds are legal here
6808 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6809 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006810 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006811 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006812 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006813 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6814 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006815 }
John McCalled976492009-12-04 22:46:56 +00006816 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006817 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6818 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006819 }
John McCalled976492009-12-04 22:46:56 +00006820 D->setAccess(AS);
6821 CurContext->addDecl(D);
6822
6823 if (!LookupContext) return D;
6824 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006825
John McCall77bb1aa2010-05-01 00:40:08 +00006826 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006827 UD->setInvalidDecl();
6828 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006829 }
6830
Richard Smithc5a89a12012-04-02 01:30:27 +00006831 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006832 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006833 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006834 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006835 return UD;
6836 }
6837
6838 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006839
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006840 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006841
John McCall604e7f12009-12-08 07:46:18 +00006842 // Unlike most lookups, we don't always want to hide tag
6843 // declarations: tag names are visible through the using declaration
6844 // even if hidden by ordinary names, *except* in a dependent context
6845 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006846 if (!IsInstantiation)
6847 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006848
John McCallb9abd8722012-04-07 03:04:20 +00006849 // For the purposes of this lookup, we have a base object type
6850 // equal to that of the current context.
6851 if (CurContext->isRecord()) {
6852 R.setBaseObjectType(
6853 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6854 }
6855
John McCalla24dc2e2009-11-17 02:14:36 +00006856 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006857
John McCallf36e02d2009-10-09 21:13:30 +00006858 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006859 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006860 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006861 UD->setInvalidDecl();
6862 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006863 }
6864
John McCalled976492009-12-04 22:46:56 +00006865 if (R.isAmbiguous()) {
6866 UD->setInvalidDecl();
6867 return UD;
6868 }
Mike Stump1eb44332009-09-09 15:08:12 +00006869
John McCall7ba107a2009-11-18 02:36:19 +00006870 if (IsTypeName) {
6871 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006872 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006873 Diag(IdentLoc, diag::err_using_typename_non_type);
6874 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6875 Diag((*I)->getUnderlyingDecl()->getLocation(),
6876 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006877 UD->setInvalidDecl();
6878 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006879 }
6880 } else {
6881 // If we asked for a non-typename and we got a type, error out,
6882 // but only if this is an instantiation of an unresolved using
6883 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006884 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006885 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6886 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006887 UD->setInvalidDecl();
6888 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006889 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006890 }
6891
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006892 // C++0x N2914 [namespace.udecl]p6:
6893 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006894 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006895 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6896 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006897 UD->setInvalidDecl();
6898 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006899 }
Mike Stump1eb44332009-09-09 15:08:12 +00006900
John McCall9f54ad42009-12-10 09:41:52 +00006901 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6902 if (!CheckUsingShadowDecl(UD, *I, Previous))
6903 BuildUsingShadowDecl(S, UD, *I);
6904 }
John McCall9488ea12009-11-17 05:59:44 +00006905
6906 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006907}
6908
Sebastian Redlf677ea32011-02-05 19:23:19 +00006909/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006910bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6911 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006912
Douglas Gregordc355712011-02-25 00:36:19 +00006913 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006914 assert(SourceType &&
6915 "Using decl naming constructor doesn't have type in scope spec.");
6916 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6917
6918 // Check whether the named type is a direct base class.
6919 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6920 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6921 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6922 BaseIt != BaseE; ++BaseIt) {
6923 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6924 if (CanonicalSourceType == BaseType)
6925 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006926 if (BaseIt->getType()->isDependentType())
6927 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006928 }
6929
6930 if (BaseIt == BaseE) {
6931 // Did not find SourceType in the bases.
6932 Diag(UD->getUsingLocation(),
6933 diag::err_using_decl_constructor_not_in_direct_base)
6934 << UD->getNameInfo().getSourceRange()
6935 << QualType(SourceType, 0) << TargetClass;
6936 return true;
6937 }
6938
Richard Smithc5a89a12012-04-02 01:30:27 +00006939 if (!CurContext->isDependentContext())
6940 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006941
6942 return false;
6943}
6944
John McCall9f54ad42009-12-10 09:41:52 +00006945/// Checks that the given using declaration is not an invalid
6946/// redeclaration. Note that this is checking only for the using decl
6947/// itself, not for any ill-formedness among the UsingShadowDecls.
6948bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6949 bool isTypeName,
6950 const CXXScopeSpec &SS,
6951 SourceLocation NameLoc,
6952 const LookupResult &Prev) {
6953 // C++03 [namespace.udecl]p8:
6954 // C++0x [namespace.udecl]p10:
6955 // A using-declaration is a declaration and can therefore be used
6956 // repeatedly where (and only where) multiple declarations are
6957 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006958 //
John McCall8a726212010-11-29 18:01:58 +00006959 // That's in non-member contexts.
6960 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006961 return false;
6962
6963 NestedNameSpecifier *Qual
6964 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6965
6966 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6967 NamedDecl *D = *I;
6968
6969 bool DTypename;
6970 NestedNameSpecifier *DQual;
6971 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6972 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006973 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006974 } else if (UnresolvedUsingValueDecl *UD
6975 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6976 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006977 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006978 } else if (UnresolvedUsingTypenameDecl *UD
6979 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6980 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006981 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006982 } else continue;
6983
6984 // using decls differ if one says 'typename' and the other doesn't.
6985 // FIXME: non-dependent using decls?
6986 if (isTypeName != DTypename) continue;
6987
6988 // using decls differ if they name different scopes (but note that
6989 // template instantiation can cause this check to trigger when it
6990 // didn't before instantiation).
6991 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6992 Context.getCanonicalNestedNameSpecifier(DQual))
6993 continue;
6994
6995 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006996 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006997 return true;
6998 }
6999
7000 return false;
7001}
7002
John McCall604e7f12009-12-08 07:46:18 +00007003
John McCalled976492009-12-04 22:46:56 +00007004/// Checks that the given nested-name qualifier used in a using decl
7005/// in the current context is appropriately related to the current
7006/// scope. If an error is found, diagnoses it and returns true.
7007bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7008 const CXXScopeSpec &SS,
7009 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007010 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007011
John McCall604e7f12009-12-08 07:46:18 +00007012 if (!CurContext->isRecord()) {
7013 // C++03 [namespace.udecl]p3:
7014 // C++0x [namespace.udecl]p8:
7015 // A using-declaration for a class member shall be a member-declaration.
7016
7017 // If we weren't able to compute a valid scope, it must be a
7018 // dependent class scope.
7019 if (!NamedContext || NamedContext->isRecord()) {
7020 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7021 << SS.getRange();
7022 return true;
7023 }
7024
7025 // Otherwise, everything is known to be fine.
7026 return false;
7027 }
7028
7029 // The current scope is a record.
7030
7031 // If the named context is dependent, we can't decide much.
7032 if (!NamedContext) {
7033 // FIXME: in C++0x, we can diagnose if we can prove that the
7034 // nested-name-specifier does not refer to a base class, which is
7035 // still possible in some cases.
7036
7037 // Otherwise we have to conservatively report that things might be
7038 // okay.
7039 return false;
7040 }
7041
7042 if (!NamedContext->isRecord()) {
7043 // Ideally this would point at the last name in the specifier,
7044 // but we don't have that level of source info.
7045 Diag(SS.getRange().getBegin(),
7046 diag::err_using_decl_nested_name_specifier_is_not_class)
7047 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7048 return true;
7049 }
7050
Douglas Gregor6fb07292010-12-21 07:41:49 +00007051 if (!NamedContext->isDependentContext() &&
7052 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7053 return true;
7054
Richard Smith80ad52f2013-01-02 11:42:31 +00007055 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007056 // C++0x [namespace.udecl]p3:
7057 // In a using-declaration used as a member-declaration, the
7058 // nested-name-specifier shall name a base class of the class
7059 // being defined.
7060
7061 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7062 cast<CXXRecordDecl>(NamedContext))) {
7063 if (CurContext == NamedContext) {
7064 Diag(NameLoc,
7065 diag::err_using_decl_nested_name_specifier_is_current_class)
7066 << SS.getRange();
7067 return true;
7068 }
7069
7070 Diag(SS.getRange().getBegin(),
7071 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7072 << (NestedNameSpecifier*) SS.getScopeRep()
7073 << cast<CXXRecordDecl>(CurContext)
7074 << SS.getRange();
7075 return true;
7076 }
7077
7078 return false;
7079 }
7080
7081 // C++03 [namespace.udecl]p4:
7082 // A using-declaration used as a member-declaration shall refer
7083 // to a member of a base class of the class being defined [etc.].
7084
7085 // Salient point: SS doesn't have to name a base class as long as
7086 // lookup only finds members from base classes. Therefore we can
7087 // diagnose here only if we can prove that that can't happen,
7088 // i.e. if the class hierarchies provably don't intersect.
7089
7090 // TODO: it would be nice if "definitely valid" results were cached
7091 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7092 // need to be repeated.
7093
7094 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007095 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007096
7097 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7098 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7099 Data->Bases.insert(Base);
7100 return true;
7101 }
7102
7103 bool hasDependentBases(const CXXRecordDecl *Class) {
7104 return !Class->forallBases(collect, this);
7105 }
7106
7107 /// Returns true if the base is dependent or is one of the
7108 /// accumulated base classes.
7109 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7110 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7111 return !Data->Bases.count(Base);
7112 }
7113
7114 bool mightShareBases(const CXXRecordDecl *Class) {
7115 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7116 }
7117 };
7118
7119 UserData Data;
7120
7121 // Returns false if we find a dependent base.
7122 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7123 return false;
7124
7125 // Returns false if the class has a dependent base or if it or one
7126 // of its bases is present in the base set of the current context.
7127 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7128 return false;
7129
7130 Diag(SS.getRange().getBegin(),
7131 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7132 << (NestedNameSpecifier*) SS.getScopeRep()
7133 << cast<CXXRecordDecl>(CurContext)
7134 << SS.getRange();
7135
7136 return true;
John McCalled976492009-12-04 22:46:56 +00007137}
7138
Richard Smith162e1c12011-04-15 14:24:37 +00007139Decl *Sema::ActOnAliasDeclaration(Scope *S,
7140 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007141 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007142 SourceLocation UsingLoc,
7143 UnqualifiedId &Name,
7144 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007145 // Skip up to the relevant declaration scope.
7146 while (S->getFlags() & Scope::TemplateParamScope)
7147 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007148 assert((S->getFlags() & Scope::DeclScope) &&
7149 "got alias-declaration outside of declaration scope");
7150
7151 if (Type.isInvalid())
7152 return 0;
7153
7154 bool Invalid = false;
7155 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7156 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007157 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007158
7159 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7160 return 0;
7161
7162 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007163 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007164 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007165 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7166 TInfo->getTypeLoc().getBeginLoc());
7167 }
Richard Smith162e1c12011-04-15 14:24:37 +00007168
7169 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7170 LookupName(Previous, S);
7171
7172 // Warn about shadowing the name of a template parameter.
7173 if (Previous.isSingleResult() &&
7174 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007175 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007176 Previous.clear();
7177 }
7178
7179 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7180 "name in alias declaration must be an identifier");
7181 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7182 Name.StartLocation,
7183 Name.Identifier, TInfo);
7184
7185 NewTD->setAccess(AS);
7186
7187 if (Invalid)
7188 NewTD->setInvalidDecl();
7189
Richard Smith3e4c6c42011-05-05 21:57:07 +00007190 CheckTypedefForVariablyModifiedType(S, NewTD);
7191 Invalid |= NewTD->isInvalidDecl();
7192
Richard Smith162e1c12011-04-15 14:24:37 +00007193 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007194
7195 NamedDecl *NewND;
7196 if (TemplateParamLists.size()) {
7197 TypeAliasTemplateDecl *OldDecl = 0;
7198 TemplateParameterList *OldTemplateParams = 0;
7199
7200 if (TemplateParamLists.size() != 1) {
7201 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007202 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7203 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007204 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007205 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007206
7207 // Only consider previous declarations in the same scope.
7208 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7209 /*ExplicitInstantiationOrSpecialization*/false);
7210 if (!Previous.empty()) {
7211 Redeclaration = true;
7212
7213 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7214 if (!OldDecl && !Invalid) {
7215 Diag(UsingLoc, diag::err_redefinition_different_kind)
7216 << Name.Identifier;
7217
7218 NamedDecl *OldD = Previous.getRepresentativeDecl();
7219 if (OldD->getLocation().isValid())
7220 Diag(OldD->getLocation(), diag::note_previous_definition);
7221
7222 Invalid = true;
7223 }
7224
7225 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7226 if (TemplateParameterListsAreEqual(TemplateParams,
7227 OldDecl->getTemplateParameters(),
7228 /*Complain=*/true,
7229 TPL_TemplateMatch))
7230 OldTemplateParams = OldDecl->getTemplateParameters();
7231 else
7232 Invalid = true;
7233
7234 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7235 if (!Invalid &&
7236 !Context.hasSameType(OldTD->getUnderlyingType(),
7237 NewTD->getUnderlyingType())) {
7238 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7239 // but we can't reasonably accept it.
7240 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7241 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7242 if (OldTD->getLocation().isValid())
7243 Diag(OldTD->getLocation(), diag::note_previous_definition);
7244 Invalid = true;
7245 }
7246 }
7247 }
7248
7249 // Merge any previous default template arguments into our parameters,
7250 // and check the parameter list.
7251 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7252 TPC_TypeAliasTemplate))
7253 return 0;
7254
7255 TypeAliasTemplateDecl *NewDecl =
7256 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7257 Name.Identifier, TemplateParams,
7258 NewTD);
7259
7260 NewDecl->setAccess(AS);
7261
7262 if (Invalid)
7263 NewDecl->setInvalidDecl();
7264 else if (OldDecl)
7265 NewDecl->setPreviousDeclaration(OldDecl);
7266
7267 NewND = NewDecl;
7268 } else {
7269 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7270 NewND = NewTD;
7271 }
Richard Smith162e1c12011-04-15 14:24:37 +00007272
7273 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007274 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007275
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007276 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007277 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007278}
7279
John McCalld226f652010-08-21 09:40:31 +00007280Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007281 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007282 SourceLocation AliasLoc,
7283 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007284 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007285 SourceLocation IdentLoc,
7286 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007287
Anders Carlsson81c85c42009-03-28 23:53:49 +00007288 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007289 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7290 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007291
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007292 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007293 NamedDecl *PrevDecl
7294 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7295 ForRedeclaration);
7296 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7297 PrevDecl = 0;
7298
7299 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007300 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007301 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007302 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007303 // FIXME: At some point, we'll want to create the (redundant)
7304 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007305 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007306 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007307 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007308 }
Mike Stump1eb44332009-09-09 15:08:12 +00007309
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007310 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7311 diag::err_redefinition_different_kind;
7312 Diag(AliasLoc, DiagID) << Alias;
7313 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007314 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007315 }
7316
John McCalla24dc2e2009-11-17 02:14:36 +00007317 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007318 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007319
John McCallf36e02d2009-10-09 21:13:30 +00007320 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007321 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007322 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007323 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007324 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007325 }
Mike Stump1eb44332009-09-09 15:08:12 +00007326
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007327 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007328 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007329 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007330 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007331
John McCall3dbd3d52010-02-16 06:53:13 +00007332 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007333 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007334}
7335
Sean Hunt001cad92011-05-10 00:49:42 +00007336Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007337Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7338 CXXMethodDecl *MD) {
7339 CXXRecordDecl *ClassDecl = MD->getParent();
7340
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007341 // C++ [except.spec]p14:
7342 // An implicitly declared special member function (Clause 12) shall have an
7343 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007344 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007345 if (ClassDecl->isInvalidDecl())
7346 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007347
Sebastian Redl60618fa2011-03-12 11:50:43 +00007348 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007349 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7350 BEnd = ClassDecl->bases_end();
7351 B != BEnd; ++B) {
7352 if (B->isVirtual()) // Handled below.
7353 continue;
7354
Douglas Gregor18274032010-07-03 00:47:00 +00007355 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7356 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007357 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7358 // If this is a deleted function, add it anyway. This might be conformant
7359 // with the standard. This might not. I'm not sure. It might not matter.
7360 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007361 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007362 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007363 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007364
7365 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007366 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7367 BEnd = ClassDecl->vbases_end();
7368 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007369 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7370 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007371 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7372 // If this is a deleted function, add it anyway. This might be conformant
7373 // with the standard. This might not. I'm not sure. It might not matter.
7374 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007375 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007376 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007377 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007378
7379 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007380 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7381 FEnd = ClassDecl->field_end();
7382 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007383 if (F->hasInClassInitializer()) {
7384 if (Expr *E = F->getInClassInitializer())
7385 ExceptSpec.CalledExpr(E);
7386 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007387 // DR1351:
7388 // If the brace-or-equal-initializer of a non-static data member
7389 // invokes a defaulted default constructor of its class or of an
7390 // enclosing class in a potentially evaluated subexpression, the
7391 // program is ill-formed.
7392 //
7393 // This resolution is unworkable: the exception specification of the
7394 // default constructor can be needed in an unevaluated context, in
7395 // particular, in the operand of a noexcept-expression, and we can be
7396 // unable to compute an exception specification for an enclosed class.
7397 //
7398 // We do not allow an in-class initializer to require the evaluation
7399 // of the exception specification for any in-class initializer whose
7400 // definition is not lexically complete.
7401 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007402 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007403 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007404 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7405 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7406 // If this is a deleted function, add it anyway. This might be conformant
7407 // with the standard. This might not. I'm not sure. It might not matter.
7408 // In particular, the problem is that this function never gets called. It
7409 // might just be ill-formed because this function attempts to refer to
7410 // a deleted function here.
7411 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007412 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007413 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007414 }
John McCalle23cf432010-12-14 08:05:40 +00007415
Sean Hunt001cad92011-05-10 00:49:42 +00007416 return ExceptSpec;
7417}
7418
Richard Smithafb49182012-11-29 01:34:07 +00007419namespace {
7420/// RAII object to register a special member as being currently declared.
7421struct DeclaringSpecialMember {
7422 Sema &S;
7423 Sema::SpecialMemberDecl D;
7424 bool WasAlreadyBeingDeclared;
7425
7426 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7427 : S(S), D(RD, CSM) {
7428 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7429 if (WasAlreadyBeingDeclared)
7430 // This almost never happens, but if it does, ensure that our cache
7431 // doesn't contain a stale result.
7432 S.SpecialMemberCache.clear();
7433
7434 // FIXME: Register a note to be produced if we encounter an error while
7435 // declaring the special member.
7436 }
7437 ~DeclaringSpecialMember() {
7438 if (!WasAlreadyBeingDeclared)
7439 S.SpecialMembersBeingDeclared.erase(D);
7440 }
7441
7442 /// \brief Are we already trying to declare this special member?
7443 bool isAlreadyBeingDeclared() const {
7444 return WasAlreadyBeingDeclared;
7445 }
7446};
7447}
7448
Sean Hunt001cad92011-05-10 00:49:42 +00007449CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7450 CXXRecordDecl *ClassDecl) {
7451 // C++ [class.ctor]p5:
7452 // A default constructor for a class X is a constructor of class X
7453 // that can be called without an argument. If there is no
7454 // user-declared constructor for class X, a default constructor is
7455 // implicitly declared. An implicitly-declared default constructor
7456 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007457 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007458 "Should not build implicit default constructor!");
7459
Richard Smithafb49182012-11-29 01:34:07 +00007460 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7461 if (DSM.isAlreadyBeingDeclared())
7462 return 0;
7463
Richard Smith7756afa2012-06-10 05:43:50 +00007464 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7465 CXXDefaultConstructor,
7466 false);
7467
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007468 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007469 CanQualType ClassType
7470 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007471 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007472 DeclarationName Name
7473 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007474 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007475 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007476 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007477 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007478 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007479 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007480 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007481 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007482
7483 // Build an exception specification pointing back at this constructor.
7484 FunctionProtoType::ExtProtoInfo EPI;
7485 EPI.ExceptionSpecType = EST_Unevaluated;
7486 EPI.ExceptionSpecDecl = DefaultCon;
7487 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7488
Richard Smithbc2a35d2012-12-08 08:32:28 +00007489 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7490 // constructors is easy to compute.
7491 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7492
7493 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7494 DefaultCon->setDeletedAsWritten();
7495
Douglas Gregor18274032010-07-03 00:47:00 +00007496 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007497 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007498
Douglas Gregor23c94db2010-07-02 17:43:08 +00007499 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007500 PushOnScopeChains(DefaultCon, S, false);
7501 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007502
Douglas Gregor32df23e2010-07-01 22:02:46 +00007503 return DefaultCon;
7504}
7505
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007506void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7507 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007508 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007509 !Constructor->doesThisDeclarationHaveABody() &&
7510 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007511 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007512
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007513 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007514 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007515
Eli Friedman9a14db32012-10-18 20:14:08 +00007516 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007517 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007518 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007519 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007520 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007521 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007522 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007523 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007524 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007525
7526 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007527 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007528
7529 Constructor->setUsed();
7530 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007531
7532 if (ASTMutationListener *L = getASTMutationListener()) {
7533 L->CompletedImplicitDefinition(Constructor);
7534 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007535}
7536
Richard Smith7a614d82011-06-11 17:19:42 +00007537void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007538 // Check that any explicitly-defaulted methods have exception specifications
7539 // compatible with their implicit exception specifications.
7540 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007541}
7542
Sebastian Redlf677ea32011-02-05 19:23:19 +00007543void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7544 // We start with an initial pass over the base classes to collect those that
7545 // inherit constructors from. If there are none, we can forgo all further
7546 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007547 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007548 BasesVector BasesToInheritFrom;
7549 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7550 BaseE = ClassDecl->bases_end();
7551 BaseIt != BaseE; ++BaseIt) {
7552 if (BaseIt->getInheritConstructors()) {
7553 QualType Base = BaseIt->getType();
7554 if (Base->isDependentType()) {
7555 // If we inherit constructors from anything that is dependent, just
7556 // abort processing altogether. We'll get another chance for the
7557 // instantiations.
7558 return;
7559 }
7560 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7561 }
7562 }
7563 if (BasesToInheritFrom.empty())
7564 return;
7565
7566 // Now collect the constructors that we already have in the current class.
7567 // Those take precedence over inherited constructors.
7568 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7569 // unless there is a user-declared constructor with the same signature in
7570 // the class where the using-declaration appears.
7571 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7572 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7573 CtorE = ClassDecl->ctor_end();
7574 CtorIt != CtorE; ++CtorIt) {
7575 ExistingConstructors.insert(
7576 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7577 }
7578
Sebastian Redlf677ea32011-02-05 19:23:19 +00007579 DeclarationName CreatedCtorName =
7580 Context.DeclarationNames.getCXXConstructorName(
7581 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7582
7583 // Now comes the true work.
7584 // First, we keep a map from constructor types to the base that introduced
7585 // them. Needed for finding conflicting constructors. We also keep the
7586 // actually inserted declarations in there, for pretty diagnostics.
7587 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7588 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7589 ConstructorToSourceMap InheritedConstructors;
7590 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7591 BaseE = BasesToInheritFrom.end();
7592 BaseIt != BaseE; ++BaseIt) {
7593 const RecordType *Base = *BaseIt;
7594 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7595 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7596 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7597 CtorE = BaseDecl->ctor_end();
7598 CtorIt != CtorE; ++CtorIt) {
7599 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007600 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007601 DeclarationName Name =
7602 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007603 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7604 LookupQualifiedName(Result, CurContext);
7605 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007606 SourceLocation UsingLoc = UD ? UD->getLocation() :
7607 ClassDecl->getLocation();
7608
7609 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7610 // from the class X named in the using-declaration consists of actual
7611 // constructors and notional constructors that result from the
7612 // transformation of defaulted parameters as follows:
7613 // - all non-template default constructors of X, and
7614 // - for each non-template constructor of X that has at least one
7615 // parameter with a default argument, the set of constructors that
7616 // results from omitting any ellipsis parameter specification and
7617 // successively omitting parameters with a default argument from the
7618 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00007619 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007620 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7621 const FunctionProtoType *BaseCtorType =
7622 BaseCtor->getType()->getAs<FunctionProtoType>();
7623
7624 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7625 maxParams = BaseCtor->getNumParams();
7626 params <= maxParams; ++params) {
7627 // Skip default constructors. They're never inherited.
7628 if (params == 0)
7629 continue;
7630 // Skip copy and move constructors for the same reason.
7631 if (CanBeCopyOrMove && params == 1)
7632 continue;
7633
7634 // Build up a function type for this particular constructor.
7635 // FIXME: The working paper does not consider that the exception spec
7636 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007637 // source. This code doesn't yet, either. When it does, this code will
7638 // need to be delayed until after exception specifications and in-class
7639 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007640 const Type *NewCtorType;
7641 if (params == maxParams)
7642 NewCtorType = BaseCtorType;
7643 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007644 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007645 for (unsigned i = 0; i < params; ++i) {
7646 Args.push_back(BaseCtorType->getArgType(i));
7647 }
7648 FunctionProtoType::ExtProtoInfo ExtInfo =
7649 BaseCtorType->getExtProtoInfo();
7650 ExtInfo.Variadic = false;
7651 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7652 Args.data(), params, ExtInfo)
7653 .getTypePtr();
7654 }
7655 const Type *CanonicalNewCtorType =
7656 Context.getCanonicalType(NewCtorType);
7657
7658 // Now that we have the type, first check if the class already has a
7659 // constructor with this signature.
7660 if (ExistingConstructors.count(CanonicalNewCtorType))
7661 continue;
7662
7663 // Then we check if we have already declared an inherited constructor
7664 // with this signature.
7665 std::pair<ConstructorToSourceMap::iterator, bool> result =
7666 InheritedConstructors.insert(std::make_pair(
7667 CanonicalNewCtorType,
7668 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7669 if (!result.second) {
7670 // Already in the map. If it came from a different class, that's an
7671 // error. Not if it's from the same.
7672 CanQualType PreviousBase = result.first->second.first;
7673 if (CanonicalBase != PreviousBase) {
7674 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7675 const CXXConstructorDecl *PrevBaseCtor =
7676 PrevCtor->getInheritedConstructor();
7677 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7678
7679 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7680 Diag(BaseCtor->getLocation(),
7681 diag::note_using_decl_constructor_conflict_current_ctor);
7682 Diag(PrevBaseCtor->getLocation(),
7683 diag::note_using_decl_constructor_conflict_previous_ctor);
7684 Diag(PrevCtor->getLocation(),
7685 diag::note_using_decl_constructor_conflict_previous_using);
7686 }
7687 continue;
7688 }
7689
7690 // OK, we're there, now add the constructor.
7691 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007692 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007693 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7694 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007695 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7696 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007697 /*ImplicitlyDeclared=*/true,
7698 // FIXME: Due to a defect in the standard, we treat inherited
7699 // constructors as constexpr even if that makes them ill-formed.
7700 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007701 NewCtor->setAccess(BaseCtor->getAccess());
7702
7703 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007704 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007705 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007706 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7707 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007708 /*IdentifierInfo=*/0,
7709 BaseCtorType->getArgType(i),
7710 /*TInfo=*/0, SC_None,
7711 SC_None, /*DefaultArg=*/0));
7712 }
David Blaikie4278c652011-09-21 18:16:56 +00007713 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007714 NewCtor->setInheritedConstructor(BaseCtor);
7715
Sebastian Redlf677ea32011-02-05 19:23:19 +00007716 ClassDecl->addDecl(NewCtor);
7717 result.first->second.second = NewCtor;
7718 }
7719 }
7720 }
7721}
7722
Sean Huntcb45a0f2011-05-12 22:46:25 +00007723Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007724Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7725 CXXRecordDecl *ClassDecl = MD->getParent();
7726
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007727 // C++ [except.spec]p14:
7728 // An implicitly declared special member function (Clause 12) shall have
7729 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007730 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007731 if (ClassDecl->isInvalidDecl())
7732 return ExceptSpec;
7733
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007734 // Direct base-class destructors.
7735 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7736 BEnd = ClassDecl->bases_end();
7737 B != BEnd; ++B) {
7738 if (B->isVirtual()) // Handled below.
7739 continue;
7740
7741 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007742 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007743 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007744 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007745
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007746 // Virtual base-class destructors.
7747 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7748 BEnd = ClassDecl->vbases_end();
7749 B != BEnd; ++B) {
7750 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007751 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007752 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007753 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007754
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007755 // Field destructors.
7756 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7757 FEnd = ClassDecl->field_end();
7758 F != FEnd; ++F) {
7759 if (const RecordType *RecordTy
7760 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007761 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007762 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007763 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007764
Sean Huntcb45a0f2011-05-12 22:46:25 +00007765 return ExceptSpec;
7766}
7767
7768CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7769 // C++ [class.dtor]p2:
7770 // If a class has no user-declared destructor, a destructor is
7771 // declared implicitly. An implicitly-declared destructor is an
7772 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007773 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007774
Richard Smithafb49182012-11-29 01:34:07 +00007775 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7776 if (DSM.isAlreadyBeingDeclared())
7777 return 0;
7778
Douglas Gregor4923aa22010-07-02 20:37:36 +00007779 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007780 CanQualType ClassType
7781 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007782 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007783 DeclarationName Name
7784 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007785 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007786 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007787 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7788 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007789 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007790 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007791 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007792 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007793
7794 // Build an exception specification pointing back at this destructor.
7795 FunctionProtoType::ExtProtoInfo EPI;
7796 EPI.ExceptionSpecType = EST_Unevaluated;
7797 EPI.ExceptionSpecDecl = Destructor;
7798 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7799
Richard Smithbc2a35d2012-12-08 08:32:28 +00007800 AddOverriddenMethods(ClassDecl, Destructor);
7801
7802 // We don't need to use SpecialMemberIsTrivial here; triviality for
7803 // destructors is easy to compute.
7804 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7805
7806 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7807 Destructor->setDeletedAsWritten();
7808
Douglas Gregor4923aa22010-07-02 20:37:36 +00007809 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007810 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007811
Douglas Gregor4923aa22010-07-02 20:37:36 +00007812 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007813 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007814 PushOnScopeChains(Destructor, S, false);
7815 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007816
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007817 return Destructor;
7818}
7819
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007820void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007821 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007822 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007823 !Destructor->doesThisDeclarationHaveABody() &&
7824 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007825 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007826 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007827 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007828
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007829 if (Destructor->isInvalidDecl())
7830 return;
7831
Eli Friedman9a14db32012-10-18 20:14:08 +00007832 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007833
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007834 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007835 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7836 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007837
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007838 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007839 Diag(CurrentLocation, diag::note_member_synthesized_at)
7840 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7841
7842 Destructor->setInvalidDecl();
7843 return;
7844 }
7845
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007846 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007847 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007848 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007849 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007850 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007851
7852 if (ASTMutationListener *L = getASTMutationListener()) {
7853 L->CompletedImplicitDefinition(Destructor);
7854 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007855}
7856
Richard Smitha4156b82012-04-21 18:42:51 +00007857/// \brief Perform any semantic analysis which needs to be delayed until all
7858/// pending class member declarations have been parsed.
7859void Sema::ActOnFinishCXXMemberDecls() {
Richard Smitha4156b82012-04-21 18:42:51 +00007860 // Perform any deferred checking of exception specifications for virtual
7861 // destructors.
7862 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7863 i != e; ++i) {
7864 const CXXDestructorDecl *Dtor =
7865 DelayedDestructorExceptionSpecChecks[i].first;
7866 assert(!Dtor->getParent()->isDependentType() &&
7867 "Should not ever add destructors of templates into the list.");
7868 CheckOverridingFunctionExceptionSpec(Dtor,
7869 DelayedDestructorExceptionSpecChecks[i].second);
7870 }
7871 DelayedDestructorExceptionSpecChecks.clear();
7872}
7873
Richard Smithb9d0b762012-07-27 04:22:15 +00007874void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7875 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00007876 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00007877 "adjusting dtor exception specs was introduced in c++11");
7878
Sebastian Redl0ee33912011-05-19 05:13:44 +00007879 // C++11 [class.dtor]p3:
7880 // A declaration of a destructor that does not have an exception-
7881 // specification is implicitly considered to have the same exception-
7882 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007883 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007884 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007885 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007886 return;
7887
Chandler Carruth3f224b22011-09-20 04:55:26 +00007888 // Replace the destructor's type, building off the existing one. Fortunately,
7889 // the only thing of interest in the destructor type is its extended info.
7890 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007891 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7892 EPI.ExceptionSpecType = EST_Unevaluated;
7893 EPI.ExceptionSpecDecl = Destructor;
7894 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007895
Sebastian Redl0ee33912011-05-19 05:13:44 +00007896 // FIXME: If the destructor has a body that could throw, and the newly created
7897 // spec doesn't allow exceptions, we should emit a warning, because this
7898 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007899 // However, we don't have a body or an exception specification yet, so it
7900 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007901}
7902
Richard Smith8c889532012-11-14 00:50:40 +00007903/// When generating a defaulted copy or move assignment operator, if a field
7904/// should be copied with __builtin_memcpy rather than via explicit assignments,
7905/// do so. This optimization only applies for arrays of scalars, and for arrays
7906/// of class type where the selected copy/move-assignment operator is trivial.
7907static StmtResult
7908buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7909 Expr *To, Expr *From) {
7910 // Compute the size of the memory buffer to be copied.
7911 QualType SizeType = S.Context.getSizeType();
7912 llvm::APInt Size(S.Context.getTypeSize(SizeType),
7913 S.Context.getTypeSizeInChars(T).getQuantity());
7914
7915 // Take the address of the field references for "from" and "to". We
7916 // directly construct UnaryOperators here because semantic analysis
7917 // does not permit us to take the address of an xvalue.
7918 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7919 S.Context.getPointerType(From->getType()),
7920 VK_RValue, OK_Ordinary, Loc);
7921 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7922 S.Context.getPointerType(To->getType()),
7923 VK_RValue, OK_Ordinary, Loc);
7924
7925 const Type *E = T->getBaseElementTypeUnsafe();
7926 bool NeedsCollectableMemCpy =
7927 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7928
7929 // Create a reference to the __builtin_objc_memmove_collectable function
7930 StringRef MemCpyName = NeedsCollectableMemCpy ?
7931 "__builtin_objc_memmove_collectable" :
7932 "__builtin_memcpy";
7933 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
7934 Sema::LookupOrdinaryName);
7935 S.LookupName(R, S.TUScope, true);
7936
7937 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
7938 if (!MemCpy)
7939 // Something went horribly wrong earlier, and we will have complained
7940 // about it.
7941 return StmtError();
7942
7943 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
7944 VK_RValue, Loc, 0);
7945 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
7946
7947 Expr *CallArgs[] = {
7948 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
7949 };
7950 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
7951 Loc, CallArgs, Loc);
7952
7953 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7954 return S.Owned(Call.takeAs<Stmt>());
7955}
7956
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007957/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007958/// \c To.
7959///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007960/// This routine is used to copy/move the members of a class with an
7961/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007962/// copied are arrays, this routine builds for loops to copy them.
7963///
7964/// \param S The Sema object used for type-checking.
7965///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007966/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007967///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007968/// \param T The type of the expressions being copied/moved. Both expressions
7969/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007970///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007971/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007972///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007973/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007974///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007975/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007976/// Otherwise, it's a non-static member subobject.
7977///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007978/// \param Copying Whether we're copying or moving.
7979///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007980/// \param Depth Internal parameter recording the depth of the recursion.
7981///
Richard Smith8c889532012-11-14 00:50:40 +00007982/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
7983/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00007984static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00007985buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
7986 Expr *To, Expr *From,
7987 bool CopyingBaseSubobject, bool Copying,
7988 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00007989 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007990 // Each subobject is assigned in the manner appropriate to its type:
7991 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007992 // - if the subobject is of class type, as if by a call to operator= with
7993 // the subobject as the object expression and the corresponding
7994 // subobject of x as a single function argument (as if by explicit
7995 // qualification; that is, ignoring any possible virtual overriding
7996 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00007997 //
7998 // C++03 [class.copy]p13:
7999 // - if the subobject is of class type, the copy assignment operator for
8000 // the class is used (as if by explicit qualification; that is,
8001 // ignoring any possible virtual overriding functions in more derived
8002 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008003 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8004 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008005
Douglas Gregor06a9f362010-05-01 20:49:11 +00008006 // Look for operator=.
8007 DeclarationName Name
8008 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8009 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8010 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008011
Richard Smith044c8aa2012-11-13 00:54:12 +00008012 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8013 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008014 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008015 LookupResult::Filter F = OpLookup.makeFilter();
8016 while (F.hasNext()) {
8017 NamedDecl *D = F.next();
8018 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8019 if (Method->isCopyAssignmentOperator() ||
8020 (!Copying && Method->isMoveAssignmentOperator()))
8021 continue;
8022
8023 F.erase();
8024 }
8025 F.done();
John McCallb0207482010-03-16 06:11:48 +00008026 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008027
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008028 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008029 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008030 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008031 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008032 // ambiguities), we need to cast "this" to that subobject type; to
8033 // ensure that we don't go through the virtual call mechanism, we need
8034 // to qualify the operator= name with the base class (see below). However,
8035 // this means that if the base class has a protected copy assignment
8036 // operator, the protected member access check will fail. So, we
8037 // rewrite "protected" access to "public" access in this case, since we
8038 // know by construction that we're calling from a derived class.
8039 if (CopyingBaseSubobject) {
8040 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8041 L != LEnd; ++L) {
8042 if (L.getAccess() == AS_protected)
8043 L.setAccess(AS_public);
8044 }
8045 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008046
Douglas Gregor06a9f362010-05-01 20:49:11 +00008047 // Create the nested-name-specifier that will be used to qualify the
8048 // reference to operator=; this is required to suppress the virtual
8049 // call mechanism.
8050 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008051 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008052 SS.MakeTrivial(S.Context,
8053 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008054 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008055 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008056
Douglas Gregor06a9f362010-05-01 20:49:11 +00008057 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008058 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008059 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008060 /*TemplateKWLoc=*/SourceLocation(),
8061 /*FirstQualifierInScope=*/0,
8062 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008063 /*TemplateArgs=*/0,
8064 /*SuppressQualifierCheck=*/true);
8065 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008066 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008067
Douglas Gregor06a9f362010-05-01 20:49:11 +00008068 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008069
Richard Smith044c8aa2012-11-13 00:54:12 +00008070 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008071 OpEqualRef.takeAs<Expr>(),
8072 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008073 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008074 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008075
Richard Smith8c889532012-11-14 00:50:40 +00008076 // If we built a call to a trivial 'operator=' while copying an array,
8077 // bail out. We'll replace the whole shebang with a memcpy.
8078 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8079 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8080 return StmtResult((Stmt*)0);
8081
Richard Smith044c8aa2012-11-13 00:54:12 +00008082 // Convert to an expression-statement, and clean up any produced
8083 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008084 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008085 }
John McCallb0207482010-03-16 06:11:48 +00008086
Richard Smith044c8aa2012-11-13 00:54:12 +00008087 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008088 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008089 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008090 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008091 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008092 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008093 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008094 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008095 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008096
8097 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008098 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008099
Douglas Gregor06a9f362010-05-01 20:49:11 +00008100 // Construct a loop over the array bounds, e.g.,
8101 //
8102 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8103 //
8104 // that will copy each of the array elements.
8105 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008106
Douglas Gregor06a9f362010-05-01 20:49:11 +00008107 // Create the iteration variable.
8108 IdentifierInfo *IterationVarName = 0;
8109 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008110 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008111 llvm::raw_svector_ostream OS(Str);
8112 OS << "__i" << Depth;
8113 IterationVarName = &S.Context.Idents.get(OS.str());
8114 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008115 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008116 IterationVarName, SizeType,
8117 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00008118 SC_None, SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008119
Douglas Gregor06a9f362010-05-01 20:49:11 +00008120 // Initialize the iteration variable to zero.
8121 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008122 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008123
8124 // Create a reference to the iteration variable; we'll use this several
8125 // times throughout.
8126 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008127 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008128 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008129 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8130 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8131
Douglas Gregor06a9f362010-05-01 20:49:11 +00008132 // Create the DeclStmt that holds the iteration variable.
8133 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008134
Douglas Gregor06a9f362010-05-01 20:49:11 +00008135 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008136 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008137 IterationVarRefRVal,
8138 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008139 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008140 IterationVarRefRVal,
8141 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008142 if (!Copying) // Cast to rvalue
8143 From = CastForMoving(S, From);
8144
8145 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008146 StmtResult Copy =
8147 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8148 To, From, CopyingBaseSubobject,
8149 Copying, Depth + 1);
8150 // Bail out if copying fails or if we determined that we should use memcpy.
8151 if (Copy.isInvalid() || !Copy.get())
8152 return Copy;
8153
8154 // Create the comparison against the array bound.
8155 llvm::APInt Upper
8156 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8157 Expr *Comparison
8158 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8159 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8160 BO_NE, S.Context.BoolTy,
8161 VK_RValue, OK_Ordinary, Loc, false);
8162
8163 // Create the pre-increment of the iteration variable.
8164 Expr *Increment
8165 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8166 VK_LValue, OK_Ordinary, Loc);
8167
Douglas Gregor06a9f362010-05-01 20:49:11 +00008168 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008169 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008170 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008171 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008172 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008173}
8174
Richard Smith8c889532012-11-14 00:50:40 +00008175static StmtResult
8176buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8177 Expr *To, Expr *From,
8178 bool CopyingBaseSubobject, bool Copying) {
8179 // Maybe we should use a memcpy?
8180 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8181 T.isTriviallyCopyableType(S.Context))
8182 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8183
8184 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8185 CopyingBaseSubobject,
8186 Copying, 0));
8187
8188 // If we ended up picking a trivial assignment operator for an array of a
8189 // non-trivially-copyable class type, just emit a memcpy.
8190 if (!Result.isInvalid() && !Result.get())
8191 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8192
8193 return Result;
8194}
8195
Richard Smithb9d0b762012-07-27 04:22:15 +00008196Sema::ImplicitExceptionSpecification
8197Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8198 CXXRecordDecl *ClassDecl = MD->getParent();
8199
8200 ImplicitExceptionSpecification ExceptSpec(*this);
8201 if (ClassDecl->isInvalidDecl())
8202 return ExceptSpec;
8203
8204 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8205 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8206 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8207
Douglas Gregorb87786f2010-07-01 17:48:08 +00008208 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008209 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008210 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008211
8212 // It is unspecified whether or not an implicit copy assignment operator
8213 // attempts to deduplicate calls to assignment operators of virtual bases are
8214 // made. As such, this exception specification is effectively unspecified.
8215 // Based on a similar decision made for constness in C++0x, we're erring on
8216 // the side of assuming such calls to be made regardless of whether they
8217 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008218 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8219 BaseEnd = ClassDecl->bases_end();
8220 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008221 if (Base->isVirtual())
8222 continue;
8223
Douglas Gregora376d102010-07-02 21:50:04 +00008224 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008225 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008226 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8227 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008228 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008229 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008230
8231 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8232 BaseEnd = ClassDecl->vbases_end();
8233 Base != BaseEnd; ++Base) {
8234 CXXRecordDecl *BaseClassDecl
8235 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8236 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8237 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008238 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008239 }
8240
Douglas Gregorb87786f2010-07-01 17:48:08 +00008241 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8242 FieldEnd = ClassDecl->field_end();
8243 Field != FieldEnd;
8244 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008245 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008246 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8247 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008248 LookupCopyingAssignment(FieldClassDecl,
8249 ArgQuals | FieldType.getCVRQualifiers(),
8250 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008251 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008252 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008253 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008254
Richard Smithb9d0b762012-07-27 04:22:15 +00008255 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008256}
8257
8258CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8259 // Note: The following rules are largely analoguous to the copy
8260 // constructor rules. Note that virtual bases are not taken into account
8261 // for determining the argument type of the operator. Note also that
8262 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008263 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008264
Richard Smithafb49182012-11-29 01:34:07 +00008265 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8266 if (DSM.isAlreadyBeingDeclared())
8267 return 0;
8268
Sean Hunt30de05c2011-05-14 05:23:20 +00008269 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8270 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008271 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008272 ArgType = ArgType.withConst();
8273 ArgType = Context.getLValueReferenceType(ArgType);
8274
Douglas Gregord3c35902010-07-01 16:36:15 +00008275 // An implicitly-declared copy assignment operator is an inline public
8276 // member of its class.
8277 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008278 SourceLocation ClassLoc = ClassDecl->getLocation();
8279 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008280 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008281 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00008282 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00008283 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008284 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008285 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008286 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008287 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008288 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008289
8290 // Build an exception specification pointing back at this member.
8291 FunctionProtoType::ExtProtoInfo EPI;
8292 EPI.ExceptionSpecType = EST_Unevaluated;
8293 EPI.ExceptionSpecDecl = CopyAssignment;
8294 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8295
Douglas Gregord3c35902010-07-01 16:36:15 +00008296 // Add the parameter to the operator.
8297 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008298 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008299 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008300 SC_None,
8301 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008302 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008303
Richard Smithbc2a35d2012-12-08 08:32:28 +00008304 AddOverriddenMethods(ClassDecl, CopyAssignment);
8305
8306 CopyAssignment->setTrivial(
8307 ClassDecl->needsOverloadResolutionForCopyAssignment()
8308 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8309 : ClassDecl->hasTrivialCopyAssignment());
8310
Nico Weberafcc96a2012-01-23 03:19:29 +00008311 // C++0x [class.copy]p19:
8312 // .... If the class definition does not explicitly declare a copy
8313 // assignment operator, there is no user-declared move constructor, and
8314 // there is no user-declared move assignment operator, a copy assignment
8315 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008316 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00008317 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008318
Richard Smithbc2a35d2012-12-08 08:32:28 +00008319 // Note that we have added this copy-assignment operator.
8320 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8321
8322 if (Scope *S = getScopeForContext(ClassDecl))
8323 PushOnScopeChains(CopyAssignment, S, false);
8324 ClassDecl->addDecl(CopyAssignment);
8325
Douglas Gregord3c35902010-07-01 16:36:15 +00008326 return CopyAssignment;
8327}
8328
Douglas Gregor06a9f362010-05-01 20:49:11 +00008329void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8330 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008331 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008332 CopyAssignOperator->isOverloadedOperator() &&
8333 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008334 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8335 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008336 "DefineImplicitCopyAssignment called for wrong function");
8337
8338 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8339
8340 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8341 CopyAssignOperator->setInvalidDecl();
8342 return;
8343 }
8344
8345 CopyAssignOperator->setUsed();
8346
Eli Friedman9a14db32012-10-18 20:14:08 +00008347 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008348 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008349
8350 // C++0x [class.copy]p30:
8351 // The implicitly-defined or explicitly-defaulted copy assignment operator
8352 // for a non-union class X performs memberwise copy assignment of its
8353 // subobjects. The direct base classes of X are assigned first, in the
8354 // order of their declaration in the base-specifier-list, and then the
8355 // immediate non-static data members of X are assigned, in the order in
8356 // which they were declared in the class definition.
8357
8358 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008359 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008360
8361 // The parameter for the "other" object, which we are copying from.
8362 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8363 Qualifiers OtherQuals = Other->getType().getQualifiers();
8364 QualType OtherRefType = Other->getType();
8365 if (const LValueReferenceType *OtherRef
8366 = OtherRefType->getAs<LValueReferenceType>()) {
8367 OtherRefType = OtherRef->getPointeeType();
8368 OtherQuals = OtherRefType.getQualifiers();
8369 }
8370
8371 // Our location for everything implicitly-generated.
8372 SourceLocation Loc = CopyAssignOperator->getLocation();
8373
8374 // Construct a reference to the "other" object. We'll be using this
8375 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008376 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008377 assert(OtherRef && "Reference to parameter cannot fail!");
8378
8379 // Construct the "this" pointer. We'll be using this throughout the generated
8380 // ASTs.
8381 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8382 assert(This && "Reference to this cannot fail!");
8383
8384 // Assign base classes.
8385 bool Invalid = false;
8386 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8387 E = ClassDecl->bases_end(); Base != E; ++Base) {
8388 // Form the assignment:
8389 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8390 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008391 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008392 Invalid = true;
8393 continue;
8394 }
8395
John McCallf871d0c2010-08-07 06:22:56 +00008396 CXXCastPath BasePath;
8397 BasePath.push_back(Base);
8398
Douglas Gregor06a9f362010-05-01 20:49:11 +00008399 // Construct the "from" expression, which is an implicit cast to the
8400 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008401 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008402 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8403 CK_UncheckedDerivedToBase,
8404 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008405
8406 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008407 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008408
8409 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008410 To = ImpCastExprToType(To.take(),
8411 Context.getCVRQualifiedType(BaseType,
8412 CopyAssignOperator->getTypeQualifiers()),
8413 CK_UncheckedDerivedToBase,
8414 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008415
8416 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008417 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008418 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008419 /*CopyingBaseSubobject=*/true,
8420 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008421 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008422 Diag(CurrentLocation, diag::note_member_synthesized_at)
8423 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8424 CopyAssignOperator->setInvalidDecl();
8425 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008426 }
8427
8428 // Success! Record the copy.
8429 Statements.push_back(Copy.takeAs<Expr>());
8430 }
8431
Douglas Gregor06a9f362010-05-01 20:49:11 +00008432 // Assign non-static members.
8433 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8434 FieldEnd = ClassDecl->field_end();
8435 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008436 if (Field->isUnnamedBitfield())
8437 continue;
8438
Douglas Gregor06a9f362010-05-01 20:49:11 +00008439 // Check for members of reference type; we can't copy those.
8440 if (Field->getType()->isReferenceType()) {
8441 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8442 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8443 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008444 Diag(CurrentLocation, diag::note_member_synthesized_at)
8445 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008446 Invalid = true;
8447 continue;
8448 }
8449
8450 // Check for members of const-qualified, non-class type.
8451 QualType BaseType = Context.getBaseElementType(Field->getType());
8452 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8453 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8454 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8455 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008456 Diag(CurrentLocation, diag::note_member_synthesized_at)
8457 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008458 Invalid = true;
8459 continue;
8460 }
John McCallb77115d2011-06-17 00:18:42 +00008461
8462 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008463 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8464 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008465
8466 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008467 if (FieldType->isIncompleteArrayType()) {
8468 assert(ClassDecl->hasFlexibleArrayMember() &&
8469 "Incomplete array type is not valid");
8470 continue;
8471 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008472
8473 // Build references to the field in the object we're copying from and to.
8474 CXXScopeSpec SS; // Intentionally empty
8475 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8476 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008477 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008478 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008479 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008480 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008481 SS, SourceLocation(), 0,
8482 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008483 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008484 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008485 SS, SourceLocation(), 0,
8486 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008487 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8488 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008489
Douglas Gregor06a9f362010-05-01 20:49:11 +00008490 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008491 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008492 To.get(), From.get(),
8493 /*CopyingBaseSubobject=*/false,
8494 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008495 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008496 Diag(CurrentLocation, diag::note_member_synthesized_at)
8497 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8498 CopyAssignOperator->setInvalidDecl();
8499 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008500 }
8501
8502 // Success! Record the copy.
8503 Statements.push_back(Copy.takeAs<Stmt>());
8504 }
8505
8506 if (!Invalid) {
8507 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008508 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008509
John McCall60d7b3a2010-08-24 06:29:42 +00008510 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008511 if (Return.isInvalid())
8512 Invalid = true;
8513 else {
8514 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008515
8516 if (Trap.hasErrorOccurred()) {
8517 Diag(CurrentLocation, diag::note_member_synthesized_at)
8518 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8519 Invalid = true;
8520 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008521 }
8522 }
8523
8524 if (Invalid) {
8525 CopyAssignOperator->setInvalidDecl();
8526 return;
8527 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008528
8529 StmtResult Body;
8530 {
8531 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008532 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008533 /*isStmtExpr=*/false);
8534 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8535 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008536 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008537
8538 if (ASTMutationListener *L = getASTMutationListener()) {
8539 L->CompletedImplicitDefinition(CopyAssignOperator);
8540 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008541}
8542
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008543Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008544Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8545 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008546
Richard Smithb9d0b762012-07-27 04:22:15 +00008547 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008548 if (ClassDecl->isInvalidDecl())
8549 return ExceptSpec;
8550
8551 // C++0x [except.spec]p14:
8552 // An implicitly declared special member function (Clause 12) shall have an
8553 // exception-specification. [...]
8554
8555 // It is unspecified whether or not an implicit move assignment operator
8556 // attempts to deduplicate calls to assignment operators of virtual bases are
8557 // made. As such, this exception specification is effectively unspecified.
8558 // Based on a similar decision made for constness in C++0x, we're erring on
8559 // the side of assuming such calls to be made regardless of whether they
8560 // actually happen.
8561 // Note that a move constructor is not implicitly declared when there are
8562 // virtual bases, but it can still be user-declared and explicitly defaulted.
8563 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8564 BaseEnd = ClassDecl->bases_end();
8565 Base != BaseEnd; ++Base) {
8566 if (Base->isVirtual())
8567 continue;
8568
8569 CXXRecordDecl *BaseClassDecl
8570 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8571 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008572 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008573 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008574 }
8575
8576 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8577 BaseEnd = ClassDecl->vbases_end();
8578 Base != BaseEnd; ++Base) {
8579 CXXRecordDecl *BaseClassDecl
8580 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8581 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008582 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008583 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008584 }
8585
8586 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8587 FieldEnd = ClassDecl->field_end();
8588 Field != FieldEnd;
8589 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008590 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008591 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008592 if (CXXMethodDecl *MoveAssign =
8593 LookupMovingAssignment(FieldClassDecl,
8594 FieldType.getCVRQualifiers(),
8595 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008596 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008597 }
8598 }
8599
8600 return ExceptSpec;
8601}
8602
Richard Smith1c931be2012-04-02 18:40:40 +00008603/// Determine whether the class type has any direct or indirect virtual base
8604/// classes which have a non-trivial move assignment operator.
8605static bool
8606hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8607 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8608 BaseEnd = ClassDecl->vbases_end();
8609 Base != BaseEnd; ++Base) {
8610 CXXRecordDecl *BaseClass =
8611 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8612
8613 // Try to declare the move assignment. If it would be deleted, then the
8614 // class does not have a non-trivial move assignment.
8615 if (BaseClass->needsImplicitMoveAssignment())
8616 S.DeclareImplicitMoveAssignment(BaseClass);
8617
Richard Smith426391c2012-11-16 00:53:38 +00008618 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008619 return true;
8620 }
8621
8622 return false;
8623}
8624
8625/// Determine whether the given type either has a move constructor or is
8626/// trivially copyable.
8627static bool
8628hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8629 Type = S.Context.getBaseElementType(Type);
8630
8631 // FIXME: Technically, non-trivially-copyable non-class types, such as
8632 // reference types, are supposed to return false here, but that appears
8633 // to be a standard defect.
8634 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008635 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008636 return true;
8637
8638 if (Type.isTriviallyCopyableType(S.Context))
8639 return true;
8640
8641 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008642 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8643 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008644 if (ClassDecl->needsImplicitMoveConstructor())
8645 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008646 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008647 }
8648
Richard Smithe5411b72012-12-01 02:35:44 +00008649 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8650 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008651 if (ClassDecl->needsImplicitMoveAssignment())
8652 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008653 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008654}
8655
8656/// Determine whether all non-static data members and direct or virtual bases
8657/// of class \p ClassDecl have either a move operation, or are trivially
8658/// copyable.
8659static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8660 bool IsConstructor) {
8661 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8662 BaseEnd = ClassDecl->bases_end();
8663 Base != BaseEnd; ++Base) {
8664 if (Base->isVirtual())
8665 continue;
8666
8667 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8668 return false;
8669 }
8670
8671 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8672 BaseEnd = ClassDecl->vbases_end();
8673 Base != BaseEnd; ++Base) {
8674 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8675 return false;
8676 }
8677
8678 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8679 FieldEnd = ClassDecl->field_end();
8680 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008681 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008682 return false;
8683 }
8684
8685 return true;
8686}
8687
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008688CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008689 // C++11 [class.copy]p20:
8690 // If the definition of a class X does not explicitly declare a move
8691 // assignment operator, one will be implicitly declared as defaulted
8692 // if and only if:
8693 //
8694 // - [first 4 bullets]
8695 assert(ClassDecl->needsImplicitMoveAssignment());
8696
Richard Smithafb49182012-11-29 01:34:07 +00008697 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8698 if (DSM.isAlreadyBeingDeclared())
8699 return 0;
8700
Richard Smith1c931be2012-04-02 18:40:40 +00008701 // [Checked after we build the declaration]
8702 // - the move assignment operator would not be implicitly defined as
8703 // deleted,
8704
8705 // [DR1402]:
8706 // - X has no direct or indirect virtual base class with a non-trivial
8707 // move assignment operator, and
8708 // - each of X's non-static data members and direct or virtual base classes
8709 // has a type that either has a move assignment operator or is trivially
8710 // copyable.
8711 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8712 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8713 ClassDecl->setFailedImplicitMoveAssignment();
8714 return 0;
8715 }
8716
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008717 // Note: The following rules are largely analoguous to the move
8718 // constructor rules.
8719
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008720 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8721 QualType RetType = Context.getLValueReferenceType(ArgType);
8722 ArgType = Context.getRValueReferenceType(ArgType);
8723
8724 // An implicitly-declared move assignment operator is an inline public
8725 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008726 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8727 SourceLocation ClassLoc = ClassDecl->getLocation();
8728 DeclarationNameInfo NameInfo(Name, ClassLoc);
8729 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008730 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008731 /*TInfo=*/0, /*isStatic=*/false,
8732 /*StorageClassAsWritten=*/SC_None,
8733 /*isInline=*/true,
8734 /*isConstexpr=*/false,
8735 SourceLocation());
8736 MoveAssignment->setAccess(AS_public);
8737 MoveAssignment->setDefaulted();
8738 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008739
Richard Smithb9d0b762012-07-27 04:22:15 +00008740 // Build an exception specification pointing back at this member.
8741 FunctionProtoType::ExtProtoInfo EPI;
8742 EPI.ExceptionSpecType = EST_Unevaluated;
8743 EPI.ExceptionSpecDecl = MoveAssignment;
8744 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8745
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008746 // Add the parameter to the operator.
8747 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8748 ClassLoc, ClassLoc, /*Id=*/0,
8749 ArgType, /*TInfo=*/0,
8750 SC_None,
8751 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008752 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008753
Richard Smithbc2a35d2012-12-08 08:32:28 +00008754 AddOverriddenMethods(ClassDecl, MoveAssignment);
8755
8756 MoveAssignment->setTrivial(
8757 ClassDecl->needsOverloadResolutionForMoveAssignment()
8758 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8759 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008760
8761 // C++0x [class.copy]p9:
8762 // If the definition of a class X does not explicitly declare a move
8763 // assignment operator, one will be implicitly declared as defaulted if and
8764 // only if:
8765 // [...]
8766 // - the move assignment operator would not be implicitly defined as
8767 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008768 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008769 // Cache this result so that we don't try to generate this over and over
8770 // on every lookup, leaking memory and wasting time.
8771 ClassDecl->setFailedImplicitMoveAssignment();
8772 return 0;
8773 }
8774
Richard Smithbc2a35d2012-12-08 08:32:28 +00008775 // Note that we have added this copy-assignment operator.
8776 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8777
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008778 if (Scope *S = getScopeForContext(ClassDecl))
8779 PushOnScopeChains(MoveAssignment, S, false);
8780 ClassDecl->addDecl(MoveAssignment);
8781
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008782 return MoveAssignment;
8783}
8784
8785void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8786 CXXMethodDecl *MoveAssignOperator) {
8787 assert((MoveAssignOperator->isDefaulted() &&
8788 MoveAssignOperator->isOverloadedOperator() &&
8789 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008790 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8791 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008792 "DefineImplicitMoveAssignment called for wrong function");
8793
8794 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8795
8796 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8797 MoveAssignOperator->setInvalidDecl();
8798 return;
8799 }
8800
8801 MoveAssignOperator->setUsed();
8802
Eli Friedman9a14db32012-10-18 20:14:08 +00008803 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008804 DiagnosticErrorTrap Trap(Diags);
8805
8806 // C++0x [class.copy]p28:
8807 // The implicitly-defined or move assignment operator for a non-union class
8808 // X performs memberwise move assignment of its subobjects. The direct base
8809 // classes of X are assigned first, in the order of their declaration in the
8810 // base-specifier-list, and then the immediate non-static data members of X
8811 // are assigned, in the order in which they were declared in the class
8812 // definition.
8813
8814 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008815 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008816
8817 // The parameter for the "other" object, which we are move from.
8818 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8819 QualType OtherRefType = Other->getType()->
8820 getAs<RValueReferenceType>()->getPointeeType();
8821 assert(OtherRefType.getQualifiers() == 0 &&
8822 "Bad argument type of defaulted move assignment");
8823
8824 // Our location for everything implicitly-generated.
8825 SourceLocation Loc = MoveAssignOperator->getLocation();
8826
8827 // Construct a reference to the "other" object. We'll be using this
8828 // throughout the generated ASTs.
8829 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8830 assert(OtherRef && "Reference to parameter cannot fail!");
8831 // Cast to rvalue.
8832 OtherRef = CastForMoving(*this, OtherRef);
8833
8834 // Construct the "this" pointer. We'll be using this throughout the generated
8835 // ASTs.
8836 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8837 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008838
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008839 // Assign base classes.
8840 bool Invalid = false;
8841 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8842 E = ClassDecl->bases_end(); Base != E; ++Base) {
8843 // Form the assignment:
8844 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8845 QualType BaseType = Base->getType().getUnqualifiedType();
8846 if (!BaseType->isRecordType()) {
8847 Invalid = true;
8848 continue;
8849 }
8850
8851 CXXCastPath BasePath;
8852 BasePath.push_back(Base);
8853
8854 // Construct the "from" expression, which is an implicit cast to the
8855 // appropriately-qualified base type.
8856 Expr *From = OtherRef;
8857 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008858 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008859
8860 // Dereference "this".
8861 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8862
8863 // Implicitly cast "this" to the appropriately-qualified base type.
8864 To = ImpCastExprToType(To.take(),
8865 Context.getCVRQualifiedType(BaseType,
8866 MoveAssignOperator->getTypeQualifiers()),
8867 CK_UncheckedDerivedToBase,
8868 VK_LValue, &BasePath);
8869
8870 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00008871 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008872 To.get(), From,
8873 /*CopyingBaseSubobject=*/true,
8874 /*Copying=*/false);
8875 if (Move.isInvalid()) {
8876 Diag(CurrentLocation, diag::note_member_synthesized_at)
8877 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8878 MoveAssignOperator->setInvalidDecl();
8879 return;
8880 }
8881
8882 // Success! Record the move.
8883 Statements.push_back(Move.takeAs<Expr>());
8884 }
8885
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008886 // Assign non-static members.
8887 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8888 FieldEnd = ClassDecl->field_end();
8889 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008890 if (Field->isUnnamedBitfield())
8891 continue;
8892
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008893 // Check for members of reference type; we can't move those.
8894 if (Field->getType()->isReferenceType()) {
8895 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8896 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8897 Diag(Field->getLocation(), diag::note_declared_at);
8898 Diag(CurrentLocation, diag::note_member_synthesized_at)
8899 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8900 Invalid = true;
8901 continue;
8902 }
8903
8904 // Check for members of const-qualified, non-class type.
8905 QualType BaseType = Context.getBaseElementType(Field->getType());
8906 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8907 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8908 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8909 Diag(Field->getLocation(), diag::note_declared_at);
8910 Diag(CurrentLocation, diag::note_member_synthesized_at)
8911 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8912 Invalid = true;
8913 continue;
8914 }
8915
8916 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008917 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8918 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008919
8920 QualType FieldType = Field->getType().getNonReferenceType();
8921 if (FieldType->isIncompleteArrayType()) {
8922 assert(ClassDecl->hasFlexibleArrayMember() &&
8923 "Incomplete array type is not valid");
8924 continue;
8925 }
8926
8927 // Build references to the field in the object we're copying from and to.
8928 CXXScopeSpec SS; // Intentionally empty
8929 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8930 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008931 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008932 MemberLookup.resolveKind();
8933 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8934 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008935 SS, SourceLocation(), 0,
8936 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008937 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8938 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008939 SS, SourceLocation(), 0,
8940 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008941 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8942 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8943
8944 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8945 "Member reference with rvalue base must be rvalue except for reference "
8946 "members, which aren't allowed for move assignment.");
8947
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008948 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008949 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008950 To.get(), From.get(),
8951 /*CopyingBaseSubobject=*/false,
8952 /*Copying=*/false);
8953 if (Move.isInvalid()) {
8954 Diag(CurrentLocation, diag::note_member_synthesized_at)
8955 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8956 MoveAssignOperator->setInvalidDecl();
8957 return;
8958 }
Richard Smithe7ce7092012-11-12 23:33:00 +00008959
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008960 // Success! Record the copy.
8961 Statements.push_back(Move.takeAs<Stmt>());
8962 }
8963
8964 if (!Invalid) {
8965 // Add a "return *this;"
8966 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8967
8968 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8969 if (Return.isInvalid())
8970 Invalid = true;
8971 else {
8972 Statements.push_back(Return.takeAs<Stmt>());
8973
8974 if (Trap.hasErrorOccurred()) {
8975 Diag(CurrentLocation, diag::note_member_synthesized_at)
8976 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8977 Invalid = true;
8978 }
8979 }
8980 }
8981
8982 if (Invalid) {
8983 MoveAssignOperator->setInvalidDecl();
8984 return;
8985 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008986
8987 StmtResult Body;
8988 {
8989 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008990 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008991 /*isStmtExpr=*/false);
8992 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8993 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008994 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8995
8996 if (ASTMutationListener *L = getASTMutationListener()) {
8997 L->CompletedImplicitDefinition(MoveAssignOperator);
8998 }
8999}
9000
Richard Smithb9d0b762012-07-27 04:22:15 +00009001Sema::ImplicitExceptionSpecification
9002Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9003 CXXRecordDecl *ClassDecl = MD->getParent();
9004
9005 ImplicitExceptionSpecification ExceptSpec(*this);
9006 if (ClassDecl->isInvalidDecl())
9007 return ExceptSpec;
9008
9009 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9010 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9011 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9012
Douglas Gregor0d405db2010-07-01 20:59:04 +00009013 // C++ [except.spec]p14:
9014 // An implicitly declared special member function (Clause 12) shall have an
9015 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009016 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9017 BaseEnd = ClassDecl->bases_end();
9018 Base != BaseEnd;
9019 ++Base) {
9020 // Virtual bases are handled below.
9021 if (Base->isVirtual())
9022 continue;
9023
Douglas Gregor22584312010-07-02 23:41:54 +00009024 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009025 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009026 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009027 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009028 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009029 }
9030 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9031 BaseEnd = ClassDecl->vbases_end();
9032 Base != BaseEnd;
9033 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009034 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009035 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009036 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009037 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009038 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009039 }
9040 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9041 FieldEnd = ClassDecl->field_end();
9042 Field != FieldEnd;
9043 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009044 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009045 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9046 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009047 LookupCopyingConstructor(FieldClassDecl,
9048 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009049 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009050 }
9051 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009052
Richard Smithb9d0b762012-07-27 04:22:15 +00009053 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009054}
9055
9056CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9057 CXXRecordDecl *ClassDecl) {
9058 // C++ [class.copy]p4:
9059 // If the class definition does not explicitly declare a copy
9060 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009061 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009062
Richard Smithafb49182012-11-29 01:34:07 +00009063 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9064 if (DSM.isAlreadyBeingDeclared())
9065 return 0;
9066
Sean Hunt49634cf2011-05-13 06:10:58 +00009067 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9068 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009069 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009070 if (Const)
9071 ArgType = ArgType.withConst();
9072 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009073
Richard Smith7756afa2012-06-10 05:43:50 +00009074 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9075 CXXCopyConstructor,
9076 Const);
9077
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009078 DeclarationName Name
9079 = Context.DeclarationNames.getCXXConstructorName(
9080 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009081 SourceLocation ClassLoc = ClassDecl->getLocation();
9082 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009083
9084 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009085 // member of its class.
9086 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009087 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009088 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009089 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009090 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009091 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009092
Richard Smithb9d0b762012-07-27 04:22:15 +00009093 // Build an exception specification pointing back at this member.
9094 FunctionProtoType::ExtProtoInfo EPI;
9095 EPI.ExceptionSpecType = EST_Unevaluated;
9096 EPI.ExceptionSpecDecl = CopyConstructor;
9097 CopyConstructor->setType(
9098 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9099
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009100 // Add the parameter to the constructor.
9101 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009102 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009103 /*IdentifierInfo=*/0,
9104 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009105 SC_None,
9106 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009107 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009108
Richard Smithbc2a35d2012-12-08 08:32:28 +00009109 CopyConstructor->setTrivial(
9110 ClassDecl->needsOverloadResolutionForCopyConstructor()
9111 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9112 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009113
Nico Weberafcc96a2012-01-23 03:19:29 +00009114 // C++11 [class.copy]p8:
9115 // ... If the class definition does not explicitly declare a copy
9116 // constructor, there is no user-declared move constructor, and there is no
9117 // user-declared move assignment operator, a copy constructor is implicitly
9118 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009119 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00009120 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00009121
Richard Smithbc2a35d2012-12-08 08:32:28 +00009122 // Note that we have declared this constructor.
9123 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9124
9125 if (Scope *S = getScopeForContext(ClassDecl))
9126 PushOnScopeChains(CopyConstructor, S, false);
9127 ClassDecl->addDecl(CopyConstructor);
9128
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009129 return CopyConstructor;
9130}
9131
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009132void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009133 CXXConstructorDecl *CopyConstructor) {
9134 assert((CopyConstructor->isDefaulted() &&
9135 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009136 !CopyConstructor->doesThisDeclarationHaveABody() &&
9137 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009138 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009139
Anders Carlsson63010a72010-04-23 16:24:12 +00009140 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009141 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009142
Eli Friedman9a14db32012-10-18 20:14:08 +00009143 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009144 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009145
David Blaikie93c86172013-01-17 05:26:25 +00009146 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009147 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009148 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009149 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009150 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009151 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009152 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009153 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9154 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009155 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009156 /*isStmtExpr=*/false)
9157 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009158 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009159 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009160
9161 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009162 if (ASTMutationListener *L = getASTMutationListener()) {
9163 L->CompletedImplicitDefinition(CopyConstructor);
9164 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009165}
9166
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009167Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009168Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9169 CXXRecordDecl *ClassDecl = MD->getParent();
9170
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009171 // C++ [except.spec]p14:
9172 // An implicitly declared special member function (Clause 12) shall have an
9173 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009174 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009175 if (ClassDecl->isInvalidDecl())
9176 return ExceptSpec;
9177
9178 // Direct base-class constructors.
9179 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9180 BEnd = ClassDecl->bases_end();
9181 B != BEnd; ++B) {
9182 if (B->isVirtual()) // Handled below.
9183 continue;
9184
9185 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9186 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009187 CXXConstructorDecl *Constructor =
9188 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009189 // If this is a deleted function, add it anyway. This might be conformant
9190 // with the standard. This might not. I'm not sure. It might not matter.
9191 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009192 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009193 }
9194 }
9195
9196 // Virtual base-class constructors.
9197 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9198 BEnd = ClassDecl->vbases_end();
9199 B != BEnd; ++B) {
9200 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9201 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009202 CXXConstructorDecl *Constructor =
9203 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009204 // If this is a deleted function, add it anyway. This might be conformant
9205 // with the standard. This might not. I'm not sure. It might not matter.
9206 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009207 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009208 }
9209 }
9210
9211 // Field constructors.
9212 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9213 FEnd = ClassDecl->field_end();
9214 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009215 QualType FieldType = Context.getBaseElementType(F->getType());
9216 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9217 CXXConstructorDecl *Constructor =
9218 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009219 // If this is a deleted function, add it anyway. This might be conformant
9220 // with the standard. This might not. I'm not sure. It might not matter.
9221 // In particular, the problem is that this function never gets called. It
9222 // might just be ill-formed because this function attempts to refer to
9223 // a deleted function here.
9224 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009225 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009226 }
9227 }
9228
9229 return ExceptSpec;
9230}
9231
9232CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9233 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009234 // C++11 [class.copy]p9:
9235 // If the definition of a class X does not explicitly declare a move
9236 // constructor, one will be implicitly declared as defaulted if and only if:
9237 //
9238 // - [first 4 bullets]
9239 assert(ClassDecl->needsImplicitMoveConstructor());
9240
Richard Smithafb49182012-11-29 01:34:07 +00009241 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9242 if (DSM.isAlreadyBeingDeclared())
9243 return 0;
9244
Richard Smith1c931be2012-04-02 18:40:40 +00009245 // [Checked after we build the declaration]
9246 // - the move assignment operator would not be implicitly defined as
9247 // deleted,
9248
9249 // [DR1402]:
9250 // - each of X's non-static data members and direct or virtual base classes
9251 // has a type that either has a move constructor or is trivially copyable.
9252 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9253 ClassDecl->setFailedImplicitMoveConstructor();
9254 return 0;
9255 }
9256
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009257 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9258 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009259
Richard Smith7756afa2012-06-10 05:43:50 +00009260 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9261 CXXMoveConstructor,
9262 false);
9263
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009264 DeclarationName Name
9265 = Context.DeclarationNames.getCXXConstructorName(
9266 Context.getCanonicalType(ClassType));
9267 SourceLocation ClassLoc = ClassDecl->getLocation();
9268 DeclarationNameInfo NameInfo(Name, ClassLoc);
9269
9270 // C++0x [class.copy]p11:
9271 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009272 // member of its class.
9273 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009274 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009275 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009276 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009277 MoveConstructor->setAccess(AS_public);
9278 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009279
Richard Smithb9d0b762012-07-27 04:22:15 +00009280 // Build an exception specification pointing back at this member.
9281 FunctionProtoType::ExtProtoInfo EPI;
9282 EPI.ExceptionSpecType = EST_Unevaluated;
9283 EPI.ExceptionSpecDecl = MoveConstructor;
9284 MoveConstructor->setType(
9285 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9286
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009287 // Add the parameter to the constructor.
9288 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9289 ClassLoc, ClassLoc,
9290 /*IdentifierInfo=*/0,
9291 ArgType, /*TInfo=*/0,
9292 SC_None,
9293 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009294 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009295
Richard Smithbc2a35d2012-12-08 08:32:28 +00009296 MoveConstructor->setTrivial(
9297 ClassDecl->needsOverloadResolutionForMoveConstructor()
9298 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9299 : ClassDecl->hasTrivialMoveConstructor());
9300
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009301 // C++0x [class.copy]p9:
9302 // If the definition of a class X does not explicitly declare a move
9303 // constructor, one will be implicitly declared as defaulted if and only if:
9304 // [...]
9305 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009306 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009307 // Cache this result so that we don't try to generate this over and over
9308 // on every lookup, leaking memory and wasting time.
9309 ClassDecl->setFailedImplicitMoveConstructor();
9310 return 0;
9311 }
9312
9313 // Note that we have declared this constructor.
9314 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9315
9316 if (Scope *S = getScopeForContext(ClassDecl))
9317 PushOnScopeChains(MoveConstructor, S, false);
9318 ClassDecl->addDecl(MoveConstructor);
9319
9320 return MoveConstructor;
9321}
9322
9323void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9324 CXXConstructorDecl *MoveConstructor) {
9325 assert((MoveConstructor->isDefaulted() &&
9326 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009327 !MoveConstructor->doesThisDeclarationHaveABody() &&
9328 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009329 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9330
9331 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9332 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9333
Eli Friedman9a14db32012-10-18 20:14:08 +00009334 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009335 DiagnosticErrorTrap Trap(Diags);
9336
David Blaikie93c86172013-01-17 05:26:25 +00009337 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009338 Trap.hasErrorOccurred()) {
9339 Diag(CurrentLocation, diag::note_member_synthesized_at)
9340 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9341 MoveConstructor->setInvalidDecl();
9342 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009343 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009344 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9345 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009346 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009347 /*isStmtExpr=*/false)
9348 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009349 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009350 }
9351
9352 MoveConstructor->setUsed();
9353
9354 if (ASTMutationListener *L = getASTMutationListener()) {
9355 L->CompletedImplicitDefinition(MoveConstructor);
9356 }
9357}
9358
Douglas Gregore4e68d42012-02-15 19:33:52 +00009359bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9360 return FD->isDeleted() &&
9361 (FD->isDefaulted() || FD->isImplicit()) &&
9362 isa<CXXMethodDecl>(FD);
9363}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009364
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009365/// \brief Mark the call operator of the given lambda closure type as "used".
9366static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9367 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009368 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009369 Lambda->lookup(
9370 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009371 CallOperator->setReferenced();
9372 CallOperator->setUsed();
9373}
9374
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009375void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9376 SourceLocation CurrentLocation,
9377 CXXConversionDecl *Conv)
9378{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009379 CXXRecordDecl *Lambda = Conv->getParent();
9380
9381 // Make sure that the lambda call operator is marked used.
9382 markLambdaCallOperatorUsed(*this, Lambda);
9383
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009384 Conv->setUsed();
9385
Eli Friedman9a14db32012-10-18 20:14:08 +00009386 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009387 DiagnosticErrorTrap Trap(Diags);
9388
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009389 // Return the address of the __invoke function.
9390 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9391 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009392 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009393 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9394 VK_LValue, Conv->getLocation()).take();
9395 assert(FunctionRef && "Can't refer to __invoke function?");
9396 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009397 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009398 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009399 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009400
9401 // Fill in the __invoke function with a dummy implementation. IR generation
9402 // will fill in the actual details.
9403 Invoke->setUsed();
9404 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009405 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009406
9407 if (ASTMutationListener *L = getASTMutationListener()) {
9408 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009409 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009410 }
9411}
9412
9413void Sema::DefineImplicitLambdaToBlockPointerConversion(
9414 SourceLocation CurrentLocation,
9415 CXXConversionDecl *Conv)
9416{
9417 Conv->setUsed();
9418
Eli Friedman9a14db32012-10-18 20:14:08 +00009419 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009420 DiagnosticErrorTrap Trap(Diags);
9421
Douglas Gregorac1303e2012-02-22 05:02:47 +00009422 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009423 Expr *This = ActOnCXXThis(CurrentLocation).take();
9424 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009425
Eli Friedman23f02672012-03-01 04:01:32 +00009426 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9427 Conv->getLocation(),
9428 Conv, DerefThis);
9429
9430 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9431 // behavior. Note that only the general conversion function does this
9432 // (since it's unusable otherwise); in the case where we inline the
9433 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009434 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009435 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9436 CK_CopyAndAutoreleaseBlockObject,
9437 BuildBlock.get(), 0, VK_RValue);
9438
9439 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009440 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009441 Conv->setInvalidDecl();
9442 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009443 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009444
Douglas Gregorac1303e2012-02-22 05:02:47 +00009445 // Create the return statement that returns the block from the conversion
9446 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009447 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009448 if (Return.isInvalid()) {
9449 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9450 Conv->setInvalidDecl();
9451 return;
9452 }
9453
9454 // Set the body of the conversion function.
9455 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009456 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009457 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009458 Conv->getLocation()));
9459
Douglas Gregorac1303e2012-02-22 05:02:47 +00009460 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009461 if (ASTMutationListener *L = getASTMutationListener()) {
9462 L->CompletedImplicitDefinition(Conv);
9463 }
9464}
9465
Douglas Gregorf52757d2012-03-10 06:53:13 +00009466/// \brief Determine whether the given list arguments contains exactly one
9467/// "real" (non-default) argument.
9468static bool hasOneRealArgument(MultiExprArg Args) {
9469 switch (Args.size()) {
9470 case 0:
9471 return false;
9472
9473 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009474 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009475 return false;
9476
9477 // fall through
9478 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009479 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009480 }
9481
9482 return false;
9483}
9484
John McCall60d7b3a2010-08-24 06:29:42 +00009485ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009486Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009487 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009488 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009489 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009490 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009491 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009492 unsigned ConstructKind,
9493 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009494 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009495
Douglas Gregor2f599792010-04-02 18:24:57 +00009496 // C++0x [class.copy]p34:
9497 // When certain criteria are met, an implementation is allowed to
9498 // omit the copy/move construction of a class object, even if the
9499 // copy/move constructor and/or destructor for the object have
9500 // side effects. [...]
9501 // - when a temporary class object that has not been bound to a
9502 // reference (12.2) would be copied/moved to a class object
9503 // with the same cv-unqualified type, the copy/move operation
9504 // can be omitted by constructing the temporary object
9505 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009506 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009507 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009508 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009509 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009510 }
Mike Stump1eb44332009-09-09 15:08:12 +00009511
9512 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009513 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009514 IsListInitialization, RequiresZeroInit,
9515 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009516}
9517
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009518/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9519/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009520ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009521Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9522 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009523 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009524 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009525 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009526 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009527 unsigned ConstructKind,
9528 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009529 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009530 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009531 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009532 HadMultipleCandidates,
9533 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009534 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9535 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009536}
9537
John McCall68c6c9a2010-02-02 09:10:11 +00009538void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009539 if (VD->isInvalidDecl()) return;
9540
John McCall68c6c9a2010-02-02 09:10:11 +00009541 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009542 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009543 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009544 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009545
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009546 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009547 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009548 CheckDestructorAccess(VD->getLocation(), Destructor,
9549 PDiag(diag::err_access_dtor_var)
9550 << VD->getDeclName()
9551 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009552 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009553
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009554 if (!VD->hasGlobalStorage()) return;
9555
9556 // Emit warning for non-trivial dtor in global scope (a real global,
9557 // class-static, function-static).
9558 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9559
9560 // TODO: this should be re-enabled for static locals by !CXAAtExit
9561 if (!VD->isStaticLocal())
9562 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009563}
9564
Douglas Gregor39da0b82009-09-09 23:08:42 +00009565/// \brief Given a constructor and the set of arguments provided for the
9566/// constructor, convert the arguments and add any required default arguments
9567/// to form a proper call to this constructor.
9568///
9569/// \returns true if an error occurred, false otherwise.
9570bool
9571Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9572 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009573 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009574 SmallVectorImpl<Expr*> &ConvertedArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009575 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009576 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9577 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009578 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009579
9580 const FunctionProtoType *Proto
9581 = Constructor->getType()->getAs<FunctionProtoType>();
9582 assert(Proto && "Constructor without a prototype?");
9583 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009584
9585 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009586 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009587 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009588 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009589 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009590
9591 VariadicCallType CallType =
9592 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009593 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009594 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9595 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009596 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009597 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009598
9599 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9600
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00009601 CheckConstructorCall(Constructor,
9602 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9603 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +00009604 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009605
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009606 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009607}
9608
Anders Carlsson20d45d22009-12-12 00:32:00 +00009609static inline bool
9610CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9611 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009612 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009613 if (isa<NamespaceDecl>(DC)) {
9614 return SemaRef.Diag(FnDecl->getLocation(),
9615 diag::err_operator_new_delete_declared_in_namespace)
9616 << FnDecl->getDeclName();
9617 }
9618
9619 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009620 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009621 return SemaRef.Diag(FnDecl->getLocation(),
9622 diag::err_operator_new_delete_declared_static)
9623 << FnDecl->getDeclName();
9624 }
9625
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009626 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009627}
9628
Anders Carlsson156c78e2009-12-13 17:53:43 +00009629static inline bool
9630CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9631 CanQualType ExpectedResultType,
9632 CanQualType ExpectedFirstParamType,
9633 unsigned DependentParamTypeDiag,
9634 unsigned InvalidParamTypeDiag) {
9635 QualType ResultType =
9636 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9637
9638 // Check that the result type is not dependent.
9639 if (ResultType->isDependentType())
9640 return SemaRef.Diag(FnDecl->getLocation(),
9641 diag::err_operator_new_delete_dependent_result_type)
9642 << FnDecl->getDeclName() << ExpectedResultType;
9643
9644 // Check that the result type is what we expect.
9645 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9646 return SemaRef.Diag(FnDecl->getLocation(),
9647 diag::err_operator_new_delete_invalid_result_type)
9648 << FnDecl->getDeclName() << ExpectedResultType;
9649
9650 // A function template must have at least 2 parameters.
9651 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9652 return SemaRef.Diag(FnDecl->getLocation(),
9653 diag::err_operator_new_delete_template_too_few_parameters)
9654 << FnDecl->getDeclName();
9655
9656 // The function decl must have at least 1 parameter.
9657 if (FnDecl->getNumParams() == 0)
9658 return SemaRef.Diag(FnDecl->getLocation(),
9659 diag::err_operator_new_delete_too_few_parameters)
9660 << FnDecl->getDeclName();
9661
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009662 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009663 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9664 if (FirstParamType->isDependentType())
9665 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9666 << FnDecl->getDeclName() << ExpectedFirstParamType;
9667
9668 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009669 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009670 ExpectedFirstParamType)
9671 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9672 << FnDecl->getDeclName() << ExpectedFirstParamType;
9673
9674 return false;
9675}
9676
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009677static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009678CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009679 // C++ [basic.stc.dynamic.allocation]p1:
9680 // A program is ill-formed if an allocation function is declared in a
9681 // namespace scope other than global scope or declared static in global
9682 // scope.
9683 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9684 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009685
9686 CanQualType SizeTy =
9687 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9688
9689 // C++ [basic.stc.dynamic.allocation]p1:
9690 // The return type shall be void*. The first parameter shall have type
9691 // std::size_t.
9692 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9693 SizeTy,
9694 diag::err_operator_new_dependent_param_type,
9695 diag::err_operator_new_param_type))
9696 return true;
9697
9698 // C++ [basic.stc.dynamic.allocation]p1:
9699 // The first parameter shall not have an associated default argument.
9700 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009701 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009702 diag::err_operator_new_default_arg)
9703 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9704
9705 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009706}
9707
9708static bool
Richard Smith444d3842012-10-20 08:26:51 +00009709CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009710 // C++ [basic.stc.dynamic.deallocation]p1:
9711 // A program is ill-formed if deallocation functions are declared in a
9712 // namespace scope other than global scope or declared static in global
9713 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009714 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9715 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009716
9717 // C++ [basic.stc.dynamic.deallocation]p2:
9718 // Each deallocation function shall return void and its first parameter
9719 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009720 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9721 SemaRef.Context.VoidPtrTy,
9722 diag::err_operator_delete_dependent_param_type,
9723 diag::err_operator_delete_param_type))
9724 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009725
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009726 return false;
9727}
9728
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009729/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9730/// of this overloaded operator is well-formed. If so, returns false;
9731/// otherwise, emits appropriate diagnostics and returns true.
9732bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009733 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009734 "Expected an overloaded operator declaration");
9735
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009736 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9737
Mike Stump1eb44332009-09-09 15:08:12 +00009738 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009739 // The allocation and deallocation functions, operator new,
9740 // operator new[], operator delete and operator delete[], are
9741 // described completely in 3.7.3. The attributes and restrictions
9742 // found in the rest of this subclause do not apply to them unless
9743 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009744 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009745 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009746
Anders Carlssona3ccda52009-12-12 00:26:23 +00009747 if (Op == OO_New || Op == OO_Array_New)
9748 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009749
9750 // C++ [over.oper]p6:
9751 // An operator function shall either be a non-static member
9752 // function or be a non-member function and have at least one
9753 // parameter whose type is a class, a reference to a class, an
9754 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009755 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9756 if (MethodDecl->isStatic())
9757 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009758 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009759 } else {
9760 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009761 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9762 ParamEnd = FnDecl->param_end();
9763 Param != ParamEnd; ++Param) {
9764 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009765 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9766 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009767 ClassOrEnumParam = true;
9768 break;
9769 }
9770 }
9771
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009772 if (!ClassOrEnumParam)
9773 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009774 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009775 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009776 }
9777
9778 // C++ [over.oper]p8:
9779 // An operator function cannot have default arguments (8.3.6),
9780 // except where explicitly stated below.
9781 //
Mike Stump1eb44332009-09-09 15:08:12 +00009782 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009783 // (C++ [over.call]p1).
9784 if (Op != OO_Call) {
9785 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9786 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009787 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009788 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009789 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009790 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009791 }
9792 }
9793
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009794 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9795 { false, false, false }
9796#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9797 , { Unary, Binary, MemberOnly }
9798#include "clang/Basic/OperatorKinds.def"
9799 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009800
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009801 bool CanBeUnaryOperator = OperatorUses[Op][0];
9802 bool CanBeBinaryOperator = OperatorUses[Op][1];
9803 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009804
9805 // C++ [over.oper]p8:
9806 // [...] Operator functions cannot have more or fewer parameters
9807 // than the number required for the corresponding operator, as
9808 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009809 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009810 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009811 if (Op != OO_Call &&
9812 ((NumParams == 1 && !CanBeUnaryOperator) ||
9813 (NumParams == 2 && !CanBeBinaryOperator) ||
9814 (NumParams < 1) || (NumParams > 2))) {
9815 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009816 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009817 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009818 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009819 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009820 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009821 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009822 assert(CanBeBinaryOperator &&
9823 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009824 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009825 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009826
Chris Lattner416e46f2008-11-21 07:57:12 +00009827 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009828 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009829 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009830
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009831 // Overloaded operators other than operator() cannot be variadic.
9832 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009833 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009834 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009835 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009836 }
9837
9838 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009839 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9840 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009841 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009842 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009843 }
9844
9845 // C++ [over.inc]p1:
9846 // The user-defined function called operator++ implements the
9847 // prefix and postfix ++ operator. If this function is a member
9848 // function with no parameters, or a non-member function with one
9849 // parameter of class or enumeration type, it defines the prefix
9850 // increment operator ++ for objects of that type. If the function
9851 // is a member function with one parameter (which shall be of type
9852 // int) or a non-member function with two parameters (the second
9853 // of which shall be of type int), it defines the postfix
9854 // increment operator ++ for objects of that type.
9855 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9856 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9857 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009858 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009859 ParamIsInt = BT->getKind() == BuiltinType::Int;
9860
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009861 if (!ParamIsInt)
9862 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009863 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009864 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009865 }
9866
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009867 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009868}
Chris Lattner5a003a42008-12-17 07:09:26 +00009869
Sean Hunta6c058d2010-01-13 09:01:02 +00009870/// CheckLiteralOperatorDeclaration - Check whether the declaration
9871/// of this literal operator function is well-formed. If so, returns
9872/// false; otherwise, emits appropriate diagnostics and returns true.
9873bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009874 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009875 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9876 << FnDecl->getDeclName();
9877 return true;
9878 }
9879
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009880 if (FnDecl->isExternC()) {
9881 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9882 return true;
9883 }
9884
Sean Hunta6c058d2010-01-13 09:01:02 +00009885 bool Valid = false;
9886
Richard Smith36f5cfe2012-03-09 08:00:36 +00009887 // This might be the definition of a literal operator template.
9888 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9889 // This might be a specialization of a literal operator template.
9890 if (!TpDecl)
9891 TpDecl = FnDecl->getPrimaryTemplate();
9892
Sean Hunt216c2782010-04-07 23:11:06 +00009893 // template <char...> type operator "" name() is the only valid template
9894 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009895 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009896 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009897 // Must have only one template parameter
9898 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9899 if (Params->size() == 1) {
9900 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009901 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009902
Sean Hunt216c2782010-04-07 23:11:06 +00009903 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009904 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9905 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9906 Valid = true;
9907 }
9908 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009909 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009910 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009911 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9912
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009913 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009914
Sean Hunt30019c02010-04-07 22:57:35 +00009915 // unsigned long long int, long double, and any character type are allowed
9916 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009917 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9918 Context.hasSameType(T, Context.LongDoubleTy) ||
9919 Context.hasSameType(T, Context.CharTy) ||
9920 Context.hasSameType(T, Context.WCharTy) ||
9921 Context.hasSameType(T, Context.Char16Ty) ||
9922 Context.hasSameType(T, Context.Char32Ty)) {
9923 if (++Param == FnDecl->param_end())
9924 Valid = true;
9925 goto FinishedParams;
9926 }
9927
Sean Hunt30019c02010-04-07 22:57:35 +00009928 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009929 const PointerType *PT = T->getAs<PointerType>();
9930 if (!PT)
9931 goto FinishedParams;
9932 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009933 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009934 goto FinishedParams;
9935 T = T.getUnqualifiedType();
9936
9937 // Move on to the second parameter;
9938 ++Param;
9939
9940 // If there is no second parameter, the first must be a const char *
9941 if (Param == FnDecl->param_end()) {
9942 if (Context.hasSameType(T, Context.CharTy))
9943 Valid = true;
9944 goto FinishedParams;
9945 }
9946
9947 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9948 // are allowed as the first parameter to a two-parameter function
9949 if (!(Context.hasSameType(T, Context.CharTy) ||
9950 Context.hasSameType(T, Context.WCharTy) ||
9951 Context.hasSameType(T, Context.Char16Ty) ||
9952 Context.hasSameType(T, Context.Char32Ty)))
9953 goto FinishedParams;
9954
9955 // The second and final parameter must be an std::size_t
9956 T = (*Param)->getType().getUnqualifiedType();
9957 if (Context.hasSameType(T, Context.getSizeType()) &&
9958 ++Param == FnDecl->param_end())
9959 Valid = true;
9960 }
9961
9962 // FIXME: This diagnostic is absolutely terrible.
9963FinishedParams:
9964 if (!Valid) {
9965 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9966 << FnDecl->getDeclName();
9967 return true;
9968 }
9969
Richard Smitha9e88b22012-03-09 08:16:22 +00009970 // A parameter-declaration-clause containing a default argument is not
9971 // equivalent to any of the permitted forms.
9972 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9973 ParamEnd = FnDecl->param_end();
9974 Param != ParamEnd; ++Param) {
9975 if ((*Param)->hasDefaultArg()) {
9976 Diag((*Param)->getDefaultArgRange().getBegin(),
9977 diag::err_literal_operator_default_argument)
9978 << (*Param)->getDefaultArgRange();
9979 break;
9980 }
9981 }
9982
Richard Smith2fb4ae32012-03-08 02:39:21 +00009983 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009984 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9985 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009986 // C++11 [usrlit.suffix]p1:
9987 // Literal suffix identifiers that do not start with an underscore
9988 // are reserved for future standardization.
9989 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009990 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009991
Sean Hunta6c058d2010-01-13 09:01:02 +00009992 return false;
9993}
9994
Douglas Gregor074149e2009-01-05 19:45:36 +00009995/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9996/// linkage specification, including the language and (if present)
9997/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9998/// the location of the language string literal, which is provided
9999/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10000/// the '{' brace. Otherwise, this linkage specification does not
10001/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010002Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10003 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010004 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010005 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010006 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010007 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010008 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010009 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010010 Language = LinkageSpecDecl::lang_cxx;
10011 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010012 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010013 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010014 }
Mike Stump1eb44332009-09-09 15:08:12 +000010015
Chris Lattnercc98eac2008-12-17 07:13:27 +000010016 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010017
Douglas Gregor074149e2009-01-05 19:45:36 +000010018 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010019 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010020 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010021 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010022 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010023}
10024
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010025/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010026/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10027/// valid, it's the position of the closing '}' brace in a linkage
10028/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010029Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010030 Decl *LinkageSpec,
10031 SourceLocation RBraceLoc) {
10032 if (LinkageSpec) {
10033 if (RBraceLoc.isValid()) {
10034 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10035 LSDecl->setRBraceLoc(RBraceLoc);
10036 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010037 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010038 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010039 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010040}
10041
Douglas Gregord308e622009-05-18 20:51:54 +000010042/// \brief Perform semantic analysis for the variable declaration that
10043/// occurs within a C++ catch clause, returning the newly-created
10044/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010045VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010046 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010047 SourceLocation StartLoc,
10048 SourceLocation Loc,
10049 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010050 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010051 QualType ExDeclType = TInfo->getType();
10052
Sebastian Redl4b07b292008-12-22 19:15:10 +000010053 // Arrays and functions decay.
10054 if (ExDeclType->isArrayType())
10055 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10056 else if (ExDeclType->isFunctionType())
10057 ExDeclType = Context.getPointerType(ExDeclType);
10058
10059 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10060 // The exception-declaration shall not denote a pointer or reference to an
10061 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010062 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010063 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010064 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010065 Invalid = true;
10066 }
Douglas Gregord308e622009-05-18 20:51:54 +000010067
Sebastian Redl4b07b292008-12-22 19:15:10 +000010068 QualType BaseType = ExDeclType;
10069 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010070 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010071 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010072 BaseType = Ptr->getPointeeType();
10073 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010074 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010075 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010076 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010077 BaseType = Ref->getPointeeType();
10078 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010079 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010080 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010081 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010082 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010083 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010084
Mike Stump1eb44332009-09-09 15:08:12 +000010085 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010086 RequireNonAbstractType(Loc, ExDeclType,
10087 diag::err_abstract_type_in_decl,
10088 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010089 Invalid = true;
10090
John McCall5a180392010-07-24 00:37:23 +000010091 // Only the non-fragile NeXT runtime currently supports C++ catches
10092 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010093 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010094 QualType T = ExDeclType;
10095 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10096 T = RT->getPointeeType();
10097
10098 if (T->isObjCObjectType()) {
10099 Diag(Loc, diag::err_objc_object_catch);
10100 Invalid = true;
10101 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010102 // FIXME: should this be a test for macosx-fragile specifically?
10103 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010104 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010105 }
10106 }
10107
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010108 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10109 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010110 ExDecl->setExceptionVariable(true);
10111
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010112 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010113 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010114 Invalid = true;
10115
Douglas Gregorc41b8782011-07-06 18:14:43 +000010116 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010117 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +000010118 // C++ [except.handle]p16:
10119 // The object declared in an exception-declaration or, if the
10120 // exception-declaration does not specify a name, a temporary (12.2) is
10121 // copy-initialized (8.5) from the exception object. [...]
10122 // The object is destroyed when the handler exits, after the destruction
10123 // of any automatic objects initialized within the handler.
10124 //
10125 // We just pretend to initialize the object with itself, then make sure
10126 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010127 QualType initType = ExDeclType;
10128
10129 InitializedEntity entity =
10130 InitializedEntity::InitializeVariable(ExDecl);
10131 InitializationKind initKind =
10132 InitializationKind::CreateCopy(Loc, SourceLocation());
10133
10134 Expr *opaqueValue =
10135 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10136 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10137 ExprResult result = sequence.Perform(*this, entity, initKind,
10138 MultiExprArg(&opaqueValue, 1));
10139 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010140 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010141 else {
10142 // If the constructor used was non-trivial, set this as the
10143 // "initializer".
10144 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10145 if (!construct->getConstructor()->isTrivial()) {
10146 Expr *init = MaybeCreateExprWithCleanups(construct);
10147 ExDecl->setInit(init);
10148 }
10149
10150 // And make sure it's destructable.
10151 FinalizeVarWithDestructor(ExDecl, recordType);
10152 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010153 }
10154 }
10155
Douglas Gregord308e622009-05-18 20:51:54 +000010156 if (Invalid)
10157 ExDecl->setInvalidDecl();
10158
10159 return ExDecl;
10160}
10161
10162/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10163/// handler.
John McCalld226f652010-08-21 09:40:31 +000010164Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010165 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010166 bool Invalid = D.isInvalidType();
10167
10168 // Check for unexpanded parameter packs.
10169 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10170 UPPC_ExceptionType)) {
10171 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10172 D.getIdentifierLoc());
10173 Invalid = true;
10174 }
10175
Sebastian Redl4b07b292008-12-22 19:15:10 +000010176 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010177 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010178 LookupOrdinaryName,
10179 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010180 // The scope should be freshly made just for us. There is just no way
10181 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010182 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010183 if (PrevDecl->isTemplateParameter()) {
10184 // Maybe we will complain about the shadowed template parameter.
10185 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010186 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010187 }
10188 }
10189
Chris Lattnereaaebc72009-04-25 08:06:05 +000010190 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010191 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10192 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010193 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010194 }
10195
Douglas Gregor83cb9422010-09-09 17:09:21 +000010196 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010197 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010198 D.getIdentifierLoc(),
10199 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010200 if (Invalid)
10201 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010202
Sebastian Redl4b07b292008-12-22 19:15:10 +000010203 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010204 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010205 PushOnScopeChains(ExDecl, S);
10206 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010207 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010208
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010209 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010210 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010211}
Anders Carlssonfb311762009-03-14 00:25:26 +000010212
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010213Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010214 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010215 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010216 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010217 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010218
Richard Smithe3f470a2012-07-11 22:37:56 +000010219 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10220 return 0;
10221
10222 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10223 AssertMessage, RParenLoc, false);
10224}
10225
10226Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10227 Expr *AssertExpr,
10228 StringLiteral *AssertMessage,
10229 SourceLocation RParenLoc,
10230 bool Failed) {
10231 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10232 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010233 // In a static_assert-declaration, the constant-expression shall be a
10234 // constant expression that can be contextually converted to bool.
10235 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10236 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010237 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010238
Richard Smithdaaefc52011-12-14 23:32:26 +000010239 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010240 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010241 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010242 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010243 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010244
Richard Smithe3f470a2012-07-11 22:37:56 +000010245 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010246 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010247 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010248 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010249 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010250 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010251 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010252 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010253 }
Mike Stump1eb44332009-09-09 15:08:12 +000010254
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010255 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010256 AssertExpr, AssertMessage, RParenLoc,
10257 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010258
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010259 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010260 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010261}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010262
Douglas Gregor1d869352010-04-07 16:53:43 +000010263/// \brief Perform semantic analysis of the given friend type declaration.
10264///
10265/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010266FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010267 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010268 TypeSourceInfo *TSInfo) {
10269 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10270
10271 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010272 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010273
Richard Smith6b130222011-10-18 21:39:00 +000010274 // C++03 [class.friend]p2:
10275 // An elaborated-type-specifier shall be used in a friend declaration
10276 // for a class.*
10277 //
10278 // * The class-key of the elaborated-type-specifier is required.
10279 if (!ActiveTemplateInstantiations.empty()) {
10280 // Do not complain about the form of friend template types during
10281 // template instantiation; we will already have complained when the
10282 // template was declared.
10283 } else if (!T->isElaboratedTypeSpecifier()) {
10284 // If we evaluated the type to a record type, suggest putting
10285 // a tag in front.
10286 if (const RecordType *RT = T->getAs<RecordType>()) {
10287 RecordDecl *RD = RT->getDecl();
10288
10289 std::string InsertionText = std::string(" ") + RD->getKindName();
10290
10291 Diag(TypeRange.getBegin(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010292 getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +000010293 diag::warn_cxx98_compat_unelaborated_friend_type :
10294 diag::ext_unelaborated_friend_type)
10295 << (unsigned) RD->getTagKind()
10296 << T
10297 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10298 InsertionText);
10299 } else {
10300 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010301 getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +000010302 diag::warn_cxx98_compat_nonclass_type_friend :
10303 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010304 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010305 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010306 }
Richard Smith6b130222011-10-18 21:39:00 +000010307 } else if (T->getAs<EnumType>()) {
10308 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010309 getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +000010310 diag::warn_cxx98_compat_enum_friend :
10311 diag::ext_enum_friend)
10312 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010313 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010314 }
10315
Richard Smithd6f80da2012-09-20 01:31:00 +000010316 // C++11 [class.friend]p3:
10317 // A friend declaration that does not declare a function shall have one
10318 // of the following forms:
10319 // friend elaborated-type-specifier ;
10320 // friend simple-type-specifier ;
10321 // friend typename-specifier ;
Richard Smith80ad52f2013-01-02 11:42:31 +000010322 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
Richard Smithd6f80da2012-09-20 01:31:00 +000010323 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10324
Douglas Gregor06245bf2010-04-07 17:57:12 +000010325 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010326 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010327 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010328 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010329}
10330
John McCall9a34edb2010-10-19 01:40:49 +000010331/// Handle a friend tag declaration where the scope specifier was
10332/// templated.
10333Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10334 unsigned TagSpec, SourceLocation TagLoc,
10335 CXXScopeSpec &SS,
10336 IdentifierInfo *Name, SourceLocation NameLoc,
10337 AttributeList *Attr,
10338 MultiTemplateParamsArg TempParamLists) {
10339 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10340
10341 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010342 bool Invalid = false;
10343
10344 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010345 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010346 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010347 TempParamLists.size(),
10348 /*friend*/ true,
10349 isExplicitSpecialization,
10350 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010351 if (TemplateParams->size() > 0) {
10352 // This is a declaration of a class template.
10353 if (Invalid)
10354 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010355
Eric Christopher4110e132011-07-21 05:34:24 +000010356 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10357 SS, Name, NameLoc, Attr,
10358 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010359 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010360 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010361 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010362 } else {
10363 // The "template<>" header is extraneous.
10364 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10365 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10366 isExplicitSpecialization = true;
10367 }
10368 }
10369
10370 if (Invalid) return 0;
10371
John McCall9a34edb2010-10-19 01:40:49 +000010372 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010373 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010374 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010375 isAllExplicitSpecializations = false;
10376 break;
10377 }
10378 }
10379
10380 // FIXME: don't ignore attributes.
10381
10382 // If it's explicit specializations all the way down, just forget
10383 // about the template header and build an appropriate non-templated
10384 // friend. TODO: for source fidelity, remember the headers.
10385 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010386 if (SS.isEmpty()) {
10387 bool Owned = false;
10388 bool IsDependent = false;
10389 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10390 Attr, AS_public,
10391 /*ModulePrivateLoc=*/SourceLocation(),
10392 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010393 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010394 /*ScopedEnumUsesClassTag=*/false,
10395 /*UnderlyingType=*/TypeResult());
10396 }
10397
Douglas Gregor2494dd02011-03-01 01:34:45 +000010398 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010399 ElaboratedTypeKeyword Keyword
10400 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010401 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010402 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010403 if (T.isNull())
10404 return 0;
10405
10406 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10407 if (isa<DependentNameType>(T)) {
10408 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010409 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010410 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010411 TL.setNameLoc(NameLoc);
10412 } else {
10413 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010414 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010415 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010416 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10417 }
10418
10419 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10420 TSI, FriendLoc);
10421 Friend->setAccess(AS_public);
10422 CurContext->addDecl(Friend);
10423 return Friend;
10424 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010425
10426 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10427
10428
John McCall9a34edb2010-10-19 01:40:49 +000010429
10430 // Handle the case of a templated-scope friend class. e.g.
10431 // template <class T> class A<T>::B;
10432 // FIXME: we don't support these right now.
10433 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10434 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10435 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10436 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010437 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010438 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010439 TL.setNameLoc(NameLoc);
10440
10441 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10442 TSI, FriendLoc);
10443 Friend->setAccess(AS_public);
10444 Friend->setUnsupportedFriend(true);
10445 CurContext->addDecl(Friend);
10446 return Friend;
10447}
10448
10449
John McCalldd4a3b02009-09-16 22:47:08 +000010450/// Handle a friend type declaration. This works in tandem with
10451/// ActOnTag.
10452///
10453/// Notes on friend class templates:
10454///
10455/// We generally treat friend class declarations as if they were
10456/// declaring a class. So, for example, the elaborated type specifier
10457/// in a friend declaration is required to obey the restrictions of a
10458/// class-head (i.e. no typedefs in the scope chain), template
10459/// parameters are required to match up with simple template-ids, &c.
10460/// However, unlike when declaring a template specialization, it's
10461/// okay to refer to a template specialization without an empty
10462/// template parameter declaration, e.g.
10463/// friend class A<T>::B<unsigned>;
10464/// We permit this as a special case; if there are any template
10465/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010466/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010467Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010468 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010469 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010470
10471 assert(DS.isFriendSpecified());
10472 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10473
John McCalldd4a3b02009-09-16 22:47:08 +000010474 // Try to convert the decl specifier to a type. This works for
10475 // friend templates because ActOnTag never produces a ClassTemplateDecl
10476 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010477 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010478 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10479 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010480 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010481 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010482
Douglas Gregor6ccab972010-12-16 01:14:37 +000010483 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10484 return 0;
10485
John McCalldd4a3b02009-09-16 22:47:08 +000010486 // This is definitely an error in C++98. It's probably meant to
10487 // be forbidden in C++0x, too, but the specification is just
10488 // poorly written.
10489 //
10490 // The problem is with declarations like the following:
10491 // template <T> friend A<T>::foo;
10492 // where deciding whether a class C is a friend or not now hinges
10493 // on whether there exists an instantiation of A that causes
10494 // 'foo' to equal C. There are restrictions on class-heads
10495 // (which we declare (by fiat) elaborated friend declarations to
10496 // be) that makes this tractable.
10497 //
10498 // FIXME: handle "template <> friend class A<T>;", which
10499 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010500 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010501 Diag(Loc, diag::err_tagless_friend_type_template)
10502 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010503 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010504 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010505
John McCall02cace72009-08-28 07:59:38 +000010506 // C++98 [class.friend]p1: A friend of a class is a function
10507 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010508 // This is fixed in DR77, which just barely didn't make the C++03
10509 // deadline. It's also a very silly restriction that seriously
10510 // affects inner classes and which nobody else seems to implement;
10511 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010512 //
10513 // But note that we could warn about it: it's always useless to
10514 // friend one of your own members (it's not, however, worthless to
10515 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010516
John McCalldd4a3b02009-09-16 22:47:08 +000010517 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010518 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010519 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010520 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010521 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010522 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010523 DS.getFriendSpecLoc());
10524 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010525 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010526
10527 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010528 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010529
John McCalldd4a3b02009-09-16 22:47:08 +000010530 D->setAccess(AS_public);
10531 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010532
John McCalld226f652010-08-21 09:40:31 +000010533 return D;
John McCall02cace72009-08-28 07:59:38 +000010534}
10535
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010536NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10537 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010538 const DeclSpec &DS = D.getDeclSpec();
10539
10540 assert(DS.isFriendSpecified());
10541 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10542
10543 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010544 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010545
10546 // C++ [class.friend]p1
10547 // A friend of a class is a function or class....
10548 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010549 // It *doesn't* see through dependent types, which is correct
10550 // according to [temp.arg.type]p3:
10551 // If a declaration acquires a function type through a
10552 // type dependent on a template-parameter and this causes
10553 // a declaration that does not use the syntactic form of a
10554 // function declarator to have a function type, the program
10555 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010556 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010557 Diag(Loc, diag::err_unexpected_friend);
10558
10559 // It might be worthwhile to try to recover by creating an
10560 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010561 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010562 }
10563
10564 // C++ [namespace.memdef]p3
10565 // - If a friend declaration in a non-local class first declares a
10566 // class or function, the friend class or function is a member
10567 // of the innermost enclosing namespace.
10568 // - The name of the friend is not found by simple name lookup
10569 // until a matching declaration is provided in that namespace
10570 // scope (either before or after the class declaration granting
10571 // friendship).
10572 // - If a friend function is called, its name may be found by the
10573 // name lookup that considers functions from namespaces and
10574 // classes associated with the types of the function arguments.
10575 // - When looking for a prior declaration of a class or a function
10576 // declared as a friend, scopes outside the innermost enclosing
10577 // namespace scope are not considered.
10578
John McCall337ec3d2010-10-12 23:13:28 +000010579 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010580 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10581 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010582 assert(Name);
10583
Douglas Gregor6ccab972010-12-16 01:14:37 +000010584 // Check for unexpanded parameter packs.
10585 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10586 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10587 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10588 return 0;
10589
John McCall67d1a672009-08-06 02:15:43 +000010590 // The context we found the declaration in, or in which we should
10591 // create the declaration.
10592 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010593 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010594 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010595 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010596
John McCall337ec3d2010-10-12 23:13:28 +000010597 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010598
John McCall337ec3d2010-10-12 23:13:28 +000010599 // There are four cases here.
10600 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010601 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010602 // there as appropriate.
10603 // Recover from invalid scope qualifiers as if they just weren't there.
10604 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010605 // C++0x [namespace.memdef]p3:
10606 // If the name in a friend declaration is neither qualified nor
10607 // a template-id and the declaration is a function or an
10608 // elaborated-type-specifier, the lookup to determine whether
10609 // the entity has been previously declared shall not consider
10610 // any scopes outside the innermost enclosing namespace.
10611 // C++0x [class.friend]p11:
10612 // If a friend declaration appears in a local class and the name
10613 // specified is an unqualified name, a prior declaration is
10614 // looked up without considering scopes that are outside the
10615 // innermost enclosing non-class scope. For a friend function
10616 // declaration, if there is no prior declaration, the program is
10617 // ill-formed.
10618 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010619 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010620
John McCall29ae6e52010-10-13 05:45:15 +000010621 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010622 DC = CurContext;
10623 while (true) {
10624 // Skip class contexts. If someone can cite chapter and verse
10625 // for this behavior, that would be nice --- it's what GCC and
10626 // EDG do, and it seems like a reasonable intent, but the spec
10627 // really only says that checks for unqualified existing
10628 // declarations should stop at the nearest enclosing namespace,
10629 // not that they should only consider the nearest enclosing
10630 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010631 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010632 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010633
John McCall68263142009-11-18 22:49:29 +000010634 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010635
10636 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010637 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010638 break;
John McCall29ae6e52010-10-13 05:45:15 +000010639
John McCall8a407372010-10-14 22:22:28 +000010640 if (isTemplateId) {
10641 if (isa<TranslationUnitDecl>(DC)) break;
10642 } else {
10643 if (DC->isFileContext()) break;
10644 }
John McCall67d1a672009-08-06 02:15:43 +000010645 DC = DC->getParent();
10646 }
10647
10648 // C++ [class.friend]p1: A friend of a class is a function or
10649 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010650 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010651 // Most C++ 98 compilers do seem to give an error here, so
10652 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010653 if (!Previous.empty() && DC->Equals(CurContext))
10654 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010655 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010656 diag::warn_cxx98_compat_friend_is_member :
10657 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010658
John McCall380aaa42010-10-13 06:22:15 +000010659 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010660
Douglas Gregor883af832011-10-10 01:11:59 +000010661 // C++ [class.friend]p6:
10662 // A function can be defined in a friend declaration of a class if and
10663 // only if the class is a non-local class (9.8), the function name is
10664 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010665 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010666 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10667 }
10668
John McCall337ec3d2010-10-12 23:13:28 +000010669 // - There's a non-dependent scope specifier, in which case we
10670 // compute it and do a previous lookup there for a function
10671 // or function template.
10672 } else if (!SS.getScopeRep()->isDependent()) {
10673 DC = computeDeclContext(SS);
10674 if (!DC) return 0;
10675
10676 if (RequireCompleteDeclContext(SS, DC)) return 0;
10677
10678 LookupQualifiedName(Previous, DC);
10679
10680 // Ignore things found implicitly in the wrong scope.
10681 // TODO: better diagnostics for this case. Suggesting the right
10682 // qualified scope would be nice...
10683 LookupResult::Filter F = Previous.makeFilter();
10684 while (F.hasNext()) {
10685 NamedDecl *D = F.next();
10686 if (!DC->InEnclosingNamespaceSetOf(
10687 D->getDeclContext()->getRedeclContext()))
10688 F.erase();
10689 }
10690 F.done();
10691
10692 if (Previous.empty()) {
10693 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010694 Diag(Loc, diag::err_qualified_friend_not_found)
10695 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010696 return 0;
10697 }
10698
10699 // C++ [class.friend]p1: A friend of a class is a function or
10700 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010701 if (DC->Equals(CurContext))
10702 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010703 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010704 diag::warn_cxx98_compat_friend_is_member :
10705 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010706
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010707 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010708 // C++ [class.friend]p6:
10709 // A function can be defined in a friend declaration of a class if and
10710 // only if the class is a non-local class (9.8), the function name is
10711 // unqualified, and the function has namespace scope.
10712 SemaDiagnosticBuilder DB
10713 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10714
10715 DB << SS.getScopeRep();
10716 if (DC->isFileContext())
10717 DB << FixItHint::CreateRemoval(SS.getRange());
10718 SS.clear();
10719 }
John McCall337ec3d2010-10-12 23:13:28 +000010720
10721 // - There's a scope specifier that does not match any template
10722 // parameter lists, in which case we use some arbitrary context,
10723 // create a method or method template, and wait for instantiation.
10724 // - There's a scope specifier that does match some template
10725 // parameter lists, which we don't handle right now.
10726 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010727 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010728 // C++ [class.friend]p6:
10729 // A function can be defined in a friend declaration of a class if and
10730 // only if the class is a non-local class (9.8), the function name is
10731 // unqualified, and the function has namespace scope.
10732 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10733 << SS.getScopeRep();
10734 }
10735
John McCall337ec3d2010-10-12 23:13:28 +000010736 DC = CurContext;
10737 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010738 }
Douglas Gregor883af832011-10-10 01:11:59 +000010739
John McCall29ae6e52010-10-13 05:45:15 +000010740 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010741 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010742 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10743 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10744 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010745 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010746 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10747 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010748 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010749 }
John McCall67d1a672009-08-06 02:15:43 +000010750 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010751
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010752 // FIXME: This is an egregious hack to cope with cases where the scope stack
10753 // does not contain the declaration context, i.e., in an out-of-line
10754 // definition of a class.
10755 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10756 if (!DCScope) {
10757 FakeDCScope.setEntity(DC);
10758 DCScope = &FakeDCScope;
10759 }
10760
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010761 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010762 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010763 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010764 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010765
Douglas Gregor182ddf02009-09-28 00:08:27 +000010766 assert(ND->getDeclContext() == DC);
10767 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010768
John McCallab88d972009-08-31 22:39:49 +000010769 // Add the function declaration to the appropriate lookup tables,
10770 // adjusting the redeclarations list as necessary. We don't
10771 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010772 //
John McCallab88d972009-08-31 22:39:49 +000010773 // Also update the scope-based lookup if the target context's
10774 // lookup context is in lexical scope.
10775 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010776 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010777 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010778 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010779 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010780 }
John McCall02cace72009-08-28 07:59:38 +000010781
10782 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010783 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010784 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010785 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010786 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010787
John McCall1f2e1a92012-08-10 03:15:35 +000010788 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010789 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010790 } else {
10791 if (DC->isRecord()) CheckFriendAccess(ND);
10792
John McCall6102ca12010-10-16 06:59:13 +000010793 FunctionDecl *FD;
10794 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10795 FD = FTD->getTemplatedDecl();
10796 else
10797 FD = cast<FunctionDecl>(ND);
10798
10799 // Mark templated-scope function declarations as unsupported.
10800 if (FD->getNumTemplateParameterLists())
10801 FrD->setUnsupportedFriend(true);
10802 }
John McCall337ec3d2010-10-12 23:13:28 +000010803
John McCalld226f652010-08-21 09:40:31 +000010804 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010805}
10806
John McCalld226f652010-08-21 09:40:31 +000010807void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10808 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010809
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010810 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000010811 if (!Fn) {
10812 Diag(DelLoc, diag::err_deleted_non_function);
10813 return;
10814 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010815 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010816 // Don't consider the implicit declaration we generate for explicit
10817 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010818 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10819 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010820 Diag(DelLoc, diag::err_deleted_decl_not_first);
10821 Diag(Prev->getLocation(), diag::note_previous_declaration);
10822 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010823 // If the declaration wasn't the first, we delete the function anyway for
10824 // recovery.
10825 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010826 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010827}
Sebastian Redl13e88542009-04-27 21:33:24 +000010828
Sean Hunte4246a62011-05-12 06:15:49 +000010829void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010830 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000010831
10832 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010833 if (MD->getParent()->isDependentType()) {
10834 MD->setDefaulted();
10835 MD->setExplicitlyDefaulted();
10836 return;
10837 }
10838
Sean Hunte4246a62011-05-12 06:15:49 +000010839 CXXSpecialMember Member = getSpecialMember(MD);
10840 if (Member == CXXInvalid) {
10841 Diag(DefaultLoc, diag::err_default_special_members);
10842 return;
10843 }
10844
10845 MD->setDefaulted();
10846 MD->setExplicitlyDefaulted();
10847
Sean Huntcd10dec2011-05-23 23:14:04 +000010848 // If this definition appears within the record, do the checking when
10849 // the record is complete.
10850 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010851 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010852 // Find the uninstantiated declaration that actually had the '= default'
10853 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010854 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010855
10856 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010857 return;
10858
Richard Smithb9d0b762012-07-27 04:22:15 +000010859 CheckExplicitlyDefaultedSpecialMember(MD);
10860
Richard Smith1d28caf2012-12-11 01:14:52 +000010861 // The exception specification is needed because we are defining the
10862 // function.
10863 ResolveExceptionSpec(DefaultLoc,
10864 MD->getType()->castAs<FunctionProtoType>());
10865
Sean Hunte4246a62011-05-12 06:15:49 +000010866 switch (Member) {
10867 case CXXDefaultConstructor: {
10868 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010869 if (!CD->isInvalidDecl())
10870 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10871 break;
10872 }
10873
10874 case CXXCopyConstructor: {
10875 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010876 if (!CD->isInvalidDecl())
10877 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010878 break;
10879 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010880
Sean Hunt2b188082011-05-14 05:23:28 +000010881 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010882 if (!MD->isInvalidDecl())
10883 DefineImplicitCopyAssignment(DefaultLoc, MD);
10884 break;
10885 }
10886
Sean Huntcb45a0f2011-05-12 22:46:25 +000010887 case CXXDestructor: {
10888 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010889 if (!DD->isInvalidDecl())
10890 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010891 break;
10892 }
10893
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010894 case CXXMoveConstructor: {
10895 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010896 if (!CD->isInvalidDecl())
10897 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010898 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010899 }
Sean Hunt82713172011-05-25 23:16:36 +000010900
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010901 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010902 if (!MD->isInvalidDecl())
10903 DefineImplicitMoveAssignment(DefaultLoc, MD);
10904 break;
10905 }
10906
10907 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010908 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010909 }
10910 } else {
10911 Diag(DefaultLoc, diag::err_default_special_members);
10912 }
10913}
10914
Sebastian Redl13e88542009-04-27 21:33:24 +000010915static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010916 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010917 Stmt *SubStmt = *CI;
10918 if (!SubStmt)
10919 continue;
10920 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010921 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010922 diag::err_return_in_constructor_handler);
10923 if (!isa<Expr>(SubStmt))
10924 SearchForReturnInStmt(Self, SubStmt);
10925 }
10926}
10927
10928void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10929 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10930 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10931 SearchForReturnInStmt(*this, Handler);
10932 }
10933}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010934
Aaron Ballmanfff32482012-12-09 17:45:41 +000010935bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
10936 const CXXMethodDecl *Old) {
10937 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
10938 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
10939
10940 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
10941
10942 // If the calling conventions match, everything is fine
10943 if (NewCC == OldCC)
10944 return false;
10945
10946 // If either of the calling conventions are set to "default", we need to pick
10947 // something more sensible based on the target. This supports code where the
10948 // one method explicitly sets thiscall, and another has no explicit calling
10949 // convention.
10950 CallingConv Default =
10951 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
10952 if (NewCC == CC_Default)
10953 NewCC = Default;
10954 if (OldCC == CC_Default)
10955 OldCC = Default;
10956
10957 // If the calling conventions still don't match, then report the error
10958 if (NewCC != OldCC) {
10959 Diag(New->getLocation(),
10960 diag::err_conflicting_overriding_cc_attributes)
10961 << New->getDeclName() << New->getType() << Old->getType();
10962 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10963 return true;
10964 }
10965
10966 return false;
10967}
10968
Mike Stump1eb44332009-09-09 15:08:12 +000010969bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010970 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010971 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10972 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010973
Chandler Carruth73857792010-02-15 11:53:20 +000010974 if (Context.hasSameType(NewTy, OldTy) ||
10975 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010976 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010977
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010978 // Check if the return types are covariant
10979 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010980
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010981 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010982 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10983 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010984 NewClassTy = NewPT->getPointeeType();
10985 OldClassTy = OldPT->getPointeeType();
10986 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010987 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10988 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10989 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10990 NewClassTy = NewRT->getPointeeType();
10991 OldClassTy = OldRT->getPointeeType();
10992 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010993 }
10994 }
Mike Stump1eb44332009-09-09 15:08:12 +000010995
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010996 // The return types aren't either both pointers or references to a class type.
10997 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010998 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010999 diag::err_different_return_type_for_overriding_virtual_function)
11000 << New->getDeclName() << NewTy << OldTy;
11001 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011002
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011003 return true;
11004 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011005
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011006 // C++ [class.virtual]p6:
11007 // If the return type of D::f differs from the return type of B::f, the
11008 // class type in the return type of D::f shall be complete at the point of
11009 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011010 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11011 if (!RT->isBeingDefined() &&
11012 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011013 diag::err_covariant_return_incomplete,
11014 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011015 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011016 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011017
Douglas Gregora4923eb2009-11-16 21:35:15 +000011018 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011019 // Check if the new class derives from the old class.
11020 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11021 Diag(New->getLocation(),
11022 diag::err_covariant_return_not_derived)
11023 << New->getDeclName() << NewTy << OldTy;
11024 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11025 return true;
11026 }
Mike Stump1eb44332009-09-09 15:08:12 +000011027
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011028 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011029 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011030 diag::err_covariant_return_inaccessible_base,
11031 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11032 // FIXME: Should this point to the return type?
11033 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011034 // FIXME: this note won't trigger for delayed access control
11035 // diagnostics, and it's impossible to get an undelayed error
11036 // here from access control during the original parse because
11037 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011038 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11039 return true;
11040 }
11041 }
Mike Stump1eb44332009-09-09 15:08:12 +000011042
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011043 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011044 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011045 Diag(New->getLocation(),
11046 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011047 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011048 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11049 return true;
11050 };
Mike Stump1eb44332009-09-09 15:08:12 +000011051
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011052
11053 // The new class type must have the same or less qualifiers as the old type.
11054 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11055 Diag(New->getLocation(),
11056 diag::err_covariant_return_type_class_type_more_qualified)
11057 << New->getDeclName() << NewTy << OldTy;
11058 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11059 return true;
11060 };
Mike Stump1eb44332009-09-09 15:08:12 +000011061
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011062 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011063}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011064
Douglas Gregor4ba31362009-12-01 17:24:26 +000011065/// \brief Mark the given method pure.
11066///
11067/// \param Method the method to be marked pure.
11068///
11069/// \param InitRange the source range that covers the "0" initializer.
11070bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011071 SourceLocation EndLoc = InitRange.getEnd();
11072 if (EndLoc.isValid())
11073 Method->setRangeEnd(EndLoc);
11074
Douglas Gregor4ba31362009-12-01 17:24:26 +000011075 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11076 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011077 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011078 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011079
11080 if (!Method->isInvalidDecl())
11081 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11082 << Method->getDeclName() << InitRange;
11083 return true;
11084}
11085
Douglas Gregor552e2992012-02-21 02:22:07 +000011086/// \brief Determine whether the given declaration is a static data member.
11087static bool isStaticDataMember(Decl *D) {
11088 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11089 if (!Var)
11090 return false;
11091
11092 return Var->isStaticDataMember();
11093}
John McCall731ad842009-12-19 09:28:58 +000011094/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11095/// an initializer for the out-of-line declaration 'Dcl'. The scope
11096/// is a fresh scope pushed for just this purpose.
11097///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011098/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11099/// static data member of class X, names should be looked up in the scope of
11100/// class X.
John McCalld226f652010-08-21 09:40:31 +000011101void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011102 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011103 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011104
John McCall731ad842009-12-19 09:28:58 +000011105 // We should only get called for declarations with scope specifiers, like:
11106 // int foo::bar;
11107 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011108 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011109
11110 // If we are parsing the initializer for a static data member, push a
11111 // new expression evaluation context that is associated with this static
11112 // data member.
11113 if (isStaticDataMember(D))
11114 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011115}
11116
11117/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011118/// initializer for the out-of-line declaration 'D'.
11119void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011120 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011121 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011122
Douglas Gregor552e2992012-02-21 02:22:07 +000011123 if (isStaticDataMember(D))
11124 PopExpressionEvaluationContext();
11125
John McCall731ad842009-12-19 09:28:58 +000011126 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011127 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011128}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011129
11130/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11131/// C++ if/switch/while/for statement.
11132/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011133DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011134 // C++ 6.4p2:
11135 // The declarator shall not specify a function or an array.
11136 // The type-specifier-seq shall not contain typedef and shall not declare a
11137 // new class or enumeration.
11138 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11139 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011140
11141 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011142 if (!Dcl)
11143 return true;
11144
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011145 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11146 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011147 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011148 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011149 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011150
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011151 return Dcl;
11152}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011153
Douglas Gregordfe65432011-07-28 19:11:31 +000011154void Sema::LoadExternalVTableUses() {
11155 if (!ExternalSource)
11156 return;
11157
11158 SmallVector<ExternalVTableUse, 4> VTables;
11159 ExternalSource->ReadUsedVTables(VTables);
11160 SmallVector<VTableUse, 4> NewUses;
11161 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11162 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11163 = VTablesUsed.find(VTables[I].Record);
11164 // Even if a definition wasn't required before, it may be required now.
11165 if (Pos != VTablesUsed.end()) {
11166 if (!Pos->second && VTables[I].DefinitionRequired)
11167 Pos->second = true;
11168 continue;
11169 }
11170
11171 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11172 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11173 }
11174
11175 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11176}
11177
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011178void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11179 bool DefinitionRequired) {
11180 // Ignore any vtable uses in unevaluated operands or for classes that do
11181 // not have a vtable.
11182 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11183 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011184 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011185 return;
11186
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011187 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011188 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011189 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11190 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11191 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11192 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011193 // If we already had an entry, check to see if we are promoting this vtable
11194 // to required a definition. If so, we need to reappend to the VTableUses
11195 // list, since we may have already processed the first entry.
11196 if (DefinitionRequired && !Pos.first->second) {
11197 Pos.first->second = true;
11198 } else {
11199 // Otherwise, we can early exit.
11200 return;
11201 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011202 }
11203
11204 // Local classes need to have their virtual members marked
11205 // immediately. For all other classes, we mark their virtual members
11206 // at the end of the translation unit.
11207 if (Class->isLocalClass())
11208 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011209 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011210 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011211}
11212
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011213bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011214 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011215 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011216 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011217
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011218 // Note: The VTableUses vector could grow as a result of marking
11219 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011220 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011221 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011222 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011223 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011224 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011225 if (!Class)
11226 continue;
11227
11228 SourceLocation Loc = VTableUses[I].second;
11229
Richard Smithb9d0b762012-07-27 04:22:15 +000011230 bool DefineVTable = true;
11231
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011232 // If this class has a key function, but that key function is
11233 // defined in another translation unit, we don't need to emit the
11234 // vtable even though we're using it.
11235 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011236 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011237 switch (KeyFunction->getTemplateSpecializationKind()) {
11238 case TSK_Undeclared:
11239 case TSK_ExplicitSpecialization:
11240 case TSK_ExplicitInstantiationDeclaration:
11241 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011242 DefineVTable = false;
11243 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011244
11245 case TSK_ExplicitInstantiationDefinition:
11246 case TSK_ImplicitInstantiation:
11247 // We will be instantiating the key function.
11248 break;
11249 }
11250 } else if (!KeyFunction) {
11251 // If we have a class with no key function that is the subject
11252 // of an explicit instantiation declaration, suppress the
11253 // vtable; it will live with the explicit instantiation
11254 // definition.
11255 bool IsExplicitInstantiationDeclaration
11256 = Class->getTemplateSpecializationKind()
11257 == TSK_ExplicitInstantiationDeclaration;
11258 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11259 REnd = Class->redecls_end();
11260 R != REnd; ++R) {
11261 TemplateSpecializationKind TSK
11262 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11263 if (TSK == TSK_ExplicitInstantiationDeclaration)
11264 IsExplicitInstantiationDeclaration = true;
11265 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11266 IsExplicitInstantiationDeclaration = false;
11267 break;
11268 }
11269 }
11270
11271 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011272 DefineVTable = false;
11273 }
11274
11275 // The exception specifications for all virtual members may be needed even
11276 // if we are not providing an authoritative form of the vtable in this TU.
11277 // We may choose to emit it available_externally anyway.
11278 if (!DefineVTable) {
11279 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11280 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011281 }
11282
11283 // Mark all of the virtual members of this class as referenced, so
11284 // that we can build a vtable. Then, tell the AST consumer that a
11285 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011286 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011287 MarkVirtualMembersReferenced(Loc, Class);
11288 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11289 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11290
11291 // Optionally warn if we're emitting a weak vtable.
11292 if (Class->getLinkage() == ExternalLinkage &&
11293 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011294 const FunctionDecl *KeyFunctionDef = 0;
11295 if (!KeyFunction ||
11296 (KeyFunction->hasBody(KeyFunctionDef) &&
11297 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011298 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11299 TSK_ExplicitInstantiationDefinition
11300 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11301 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011302 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011303 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011304 VTableUses.clear();
11305
Douglas Gregor78844032011-04-22 22:25:37 +000011306 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011307}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011308
Richard Smithb9d0b762012-07-27 04:22:15 +000011309void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11310 const CXXRecordDecl *RD) {
11311 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11312 E = RD->method_end(); I != E; ++I)
11313 if ((*I)->isVirtual() && !(*I)->isPure())
11314 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11315}
11316
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011317void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11318 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011319 // Mark all functions which will appear in RD's vtable as used.
11320 CXXFinalOverriderMap FinalOverriders;
11321 RD->getFinalOverriders(FinalOverriders);
11322 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11323 E = FinalOverriders.end();
11324 I != E; ++I) {
11325 for (OverridingMethods::const_iterator OI = I->second.begin(),
11326 OE = I->second.end();
11327 OI != OE; ++OI) {
11328 assert(OI->second.size() > 0 && "no final overrider");
11329 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011330
Richard Smithff817f72012-07-07 06:59:51 +000011331 // C++ [basic.def.odr]p2:
11332 // [...] A virtual member function is used if it is not pure. [...]
11333 if (!Overrider->isPure())
11334 MarkFunctionReferenced(Loc, Overrider);
11335 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011336 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011337
11338 // Only classes that have virtual bases need a VTT.
11339 if (RD->getNumVBases() == 0)
11340 return;
11341
11342 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11343 e = RD->bases_end(); i != e; ++i) {
11344 const CXXRecordDecl *Base =
11345 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011346 if (Base->getNumVBases() == 0)
11347 continue;
11348 MarkVirtualMembersReferenced(Loc, Base);
11349 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011350}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011351
11352/// SetIvarInitializers - This routine builds initialization ASTs for the
11353/// Objective-C implementation whose ivars need be initialized.
11354void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011355 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011356 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011357 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011358 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011359 CollectIvarsToConstructOrDestruct(OID, ivars);
11360 if (ivars.empty())
11361 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011362 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011363 for (unsigned i = 0; i < ivars.size(); i++) {
11364 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011365 if (Field->isInvalidDecl())
11366 continue;
11367
Sean Huntcbb67482011-01-08 20:30:50 +000011368 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011369 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11370 InitializationKind InitKind =
11371 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11372
11373 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011374 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011375 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011376 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011377 // Note, MemberInit could actually come back empty if no initialization
11378 // is required (e.g., because it would call a trivial default constructor)
11379 if (!MemberInit.get() || MemberInit.isInvalid())
11380 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011381
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011382 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011383 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11384 SourceLocation(),
11385 MemberInit.takeAs<Expr>(),
11386 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011387 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011388
11389 // Be sure that the destructor is accessible and is marked as referenced.
11390 if (const RecordType *RecordTy
11391 = Context.getBaseElementType(Field->getType())
11392 ->getAs<RecordType>()) {
11393 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011394 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011395 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011396 CheckDestructorAccess(Field->getLocation(), Destructor,
11397 PDiag(diag::err_access_dtor_ivar)
11398 << Context.getBaseElementType(Field->getType()));
11399 }
11400 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011401 }
11402 ObjCImplementation->setIvarInitializers(Context,
11403 AllToInit.data(), AllToInit.size());
11404 }
11405}
Sean Huntfe57eef2011-05-04 05:57:24 +000011406
Sean Huntebcbe1d2011-05-04 23:29:54 +000011407static
11408void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11409 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11410 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11411 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11412 Sema &S) {
11413 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11414 CE = Current.end();
11415 if (Ctor->isInvalidDecl())
11416 return;
11417
Richard Smitha8eaf002012-08-23 06:16:52 +000011418 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11419
11420 // Target may not be determinable yet, for instance if this is a dependent
11421 // call in an uninstantiated template.
11422 if (Target) {
11423 const FunctionDecl *FNTarget = 0;
11424 (void)Target->hasBody(FNTarget);
11425 Target = const_cast<CXXConstructorDecl*>(
11426 cast_or_null<CXXConstructorDecl>(FNTarget));
11427 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011428
11429 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11430 // Avoid dereferencing a null pointer here.
11431 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11432
11433 if (!Current.insert(Canonical))
11434 return;
11435
11436 // We know that beyond here, we aren't chaining into a cycle.
11437 if (!Target || !Target->isDelegatingConstructor() ||
11438 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11439 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11440 Valid.insert(*CI);
11441 Current.clear();
11442 // We've hit a cycle.
11443 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11444 Current.count(TCanonical)) {
11445 // If we haven't diagnosed this cycle yet, do so now.
11446 if (!Invalid.count(TCanonical)) {
11447 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011448 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011449 << Ctor;
11450
Richard Smitha8eaf002012-08-23 06:16:52 +000011451 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011452 if (TCanonical != Canonical)
11453 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11454
11455 CXXConstructorDecl *C = Target;
11456 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011457 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011458 (void)C->getTargetConstructor()->hasBody(FNTarget);
11459 assert(FNTarget && "Ctor cycle through bodiless function");
11460
Richard Smitha8eaf002012-08-23 06:16:52 +000011461 C = const_cast<CXXConstructorDecl*>(
11462 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011463 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11464 }
11465 }
11466
11467 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11468 Invalid.insert(*CI);
11469 Current.clear();
11470 } else {
11471 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11472 }
11473}
11474
11475
Sean Huntfe57eef2011-05-04 05:57:24 +000011476void Sema::CheckDelegatingCtorCycles() {
11477 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11478
Sean Huntebcbe1d2011-05-04 23:29:54 +000011479 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11480 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011481
Douglas Gregor0129b562011-07-27 21:57:17 +000011482 for (DelegatingCtorDeclsType::iterator
11483 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011484 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011485 I != E; ++I)
11486 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011487
11488 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11489 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011490}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011491
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011492namespace {
11493 /// \brief AST visitor that finds references to the 'this' expression.
11494 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11495 Sema &S;
11496
11497 public:
11498 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11499
11500 bool VisitCXXThisExpr(CXXThisExpr *E) {
11501 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11502 << E->isImplicit();
11503 return false;
11504 }
11505 };
11506}
11507
11508bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11509 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11510 if (!TSInfo)
11511 return false;
11512
11513 TypeLoc TL = TSInfo->getTypeLoc();
11514 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11515 if (!ProtoTL)
11516 return false;
11517
11518 // C++11 [expr.prim.general]p3:
11519 // [The expression this] shall not appear before the optional
11520 // cv-qualifier-seq and it shall not appear within the declaration of a
11521 // static member function (although its type and value category are defined
11522 // within a static member function as they are within a non-static member
11523 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011524 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011525 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11526 FindCXXThisExpr Finder(*this);
11527
11528 // If the return type came after the cv-qualifier-seq, check it now.
11529 if (Proto->hasTrailingReturn() &&
11530 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11531 return true;
11532
11533 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011534 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11535 return true;
11536
11537 return checkThisInStaticMemberFunctionAttributes(Method);
11538}
11539
11540bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11541 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11542 if (!TSInfo)
11543 return false;
11544
11545 TypeLoc TL = TSInfo->getTypeLoc();
11546 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11547 if (!ProtoTL)
11548 return false;
11549
11550 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11551 FindCXXThisExpr Finder(*this);
11552
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011553 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011554 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011555 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011556 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011557 case EST_DynamicNone:
11558 case EST_MSAny:
11559 case EST_None:
11560 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011561
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011562 case EST_ComputedNoexcept:
11563 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11564 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011565
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011566 case EST_Dynamic:
11567 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011568 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011569 E != EEnd; ++E) {
11570 if (!Finder.TraverseType(*E))
11571 return true;
11572 }
11573 break;
11574 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011575
11576 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011577}
11578
11579bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11580 FindCXXThisExpr Finder(*this);
11581
11582 // Check attributes.
11583 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11584 A != AEnd; ++A) {
11585 // FIXME: This should be emitted by tblgen.
11586 Expr *Arg = 0;
11587 ArrayRef<Expr *> Args;
11588 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11589 Arg = G->getArg();
11590 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11591 Arg = G->getArg();
11592 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11593 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11594 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11595 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11596 else if (ExclusiveLockFunctionAttr *ELF
11597 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11598 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11599 else if (SharedLockFunctionAttr *SLF
11600 = dyn_cast<SharedLockFunctionAttr>(*A))
11601 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11602 else if (ExclusiveTrylockFunctionAttr *ETLF
11603 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11604 Arg = ETLF->getSuccessValue();
11605 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11606 } else if (SharedTrylockFunctionAttr *STLF
11607 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11608 Arg = STLF->getSuccessValue();
11609 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11610 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11611 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11612 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11613 Arg = LR->getArg();
11614 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11615 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11616 else if (ExclusiveLocksRequiredAttr *ELR
11617 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11618 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11619 else if (SharedLocksRequiredAttr *SLR
11620 = dyn_cast<SharedLocksRequiredAttr>(*A))
11621 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11622
11623 if (Arg && !Finder.TraverseStmt(Arg))
11624 return true;
11625
11626 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11627 if (!Finder.TraverseStmt(Args[I]))
11628 return true;
11629 }
11630 }
11631
11632 return false;
11633}
11634
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011635void
11636Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11637 ArrayRef<ParsedType> DynamicExceptions,
11638 ArrayRef<SourceRange> DynamicExceptionRanges,
11639 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011640 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011641 FunctionProtoType::ExtProtoInfo &EPI) {
11642 Exceptions.clear();
11643 EPI.ExceptionSpecType = EST;
11644 if (EST == EST_Dynamic) {
11645 Exceptions.reserve(DynamicExceptions.size());
11646 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11647 // FIXME: Preserve type source info.
11648 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11649
11650 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11651 collectUnexpandedParameterPacks(ET, Unexpanded);
11652 if (!Unexpanded.empty()) {
11653 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11654 UPPC_ExceptionType,
11655 Unexpanded);
11656 continue;
11657 }
11658
11659 // Check that the type is valid for an exception spec, and
11660 // drop it if not.
11661 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11662 Exceptions.push_back(ET);
11663 }
11664 EPI.NumExceptions = Exceptions.size();
11665 EPI.Exceptions = Exceptions.data();
11666 return;
11667 }
11668
11669 if (EST == EST_ComputedNoexcept) {
11670 // If an error occurred, there's no expression here.
11671 if (NoexceptExpr) {
11672 assert((NoexceptExpr->isTypeDependent() ||
11673 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11674 Context.BoolTy) &&
11675 "Parser should have made sure that the expression is boolean");
11676 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11677 EPI.ExceptionSpecType = EST_BasicNoexcept;
11678 return;
11679 }
11680
11681 if (!NoexceptExpr->isValueDependent())
11682 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011683 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011684 /*AllowFold*/ false).take();
11685 EPI.NoexceptExpr = NoexceptExpr;
11686 }
11687 return;
11688 }
11689}
11690
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011691/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11692Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11693 // Implicitly declared functions (e.g. copy constructors) are
11694 // __host__ __device__
11695 if (D->isImplicit())
11696 return CFT_HostDevice;
11697
11698 if (D->hasAttr<CUDAGlobalAttr>())
11699 return CFT_Global;
11700
11701 if (D->hasAttr<CUDADeviceAttr>()) {
11702 if (D->hasAttr<CUDAHostAttr>())
11703 return CFT_HostDevice;
11704 else
11705 return CFT_Device;
11706 }
11707
11708 return CFT_Host;
11709}
11710
11711bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11712 CUDAFunctionTarget CalleeTarget) {
11713 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11714 // Callable from the device only."
11715 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11716 return true;
11717
11718 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11719 // Callable from the host only."
11720 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11721 // Callable from the host only."
11722 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11723 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11724 return true;
11725
11726 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11727 return true;
11728
11729 return false;
11730}