blob: 99366b6a6bc2b9383ad0346d9c759f173376d8f7 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000040#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000041#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner8123a952008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattner9e979552008-04-12 23:52:44 +000049namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 public:
Mike Stump1eb44332009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000068 };
Chris Lattner8123a952008-04-10 02:22:51 +000069
Chris Lattner9e979552008-04-12 23:52:44 +000070 /// VisitExpr - Visit all of the children of this expression.
71 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
72 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000073 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000074 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000075 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000076 }
77
Chris Lattner9e979552008-04-12 23:52:44 +000078 /// VisitDeclRefExpr - Visit a reference to a declaration, to
79 /// determine whether this declaration can be used in the default
80 /// argument expression.
81 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000082 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000083 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
84 // C++ [dcl.fct.default]p9
85 // Default arguments are evaluated each time the function is
86 // called. The order of evaluation of function arguments is
87 // unspecified. Consequently, parameters of a function shall not
88 // be used in default argument expressions, even if they are not
89 // evaluated. Parameters of a function declared before a default
90 // argument expression are in scope and can hide namespace and
91 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000092 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000093 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000094 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000095 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000096 // C++ [dcl.fct.default]p7
97 // Local variables shall not be used in default argument
98 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000099 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000100 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000101 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000102 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000103 }
Chris Lattner8123a952008-04-10 02:22:51 +0000104
Douglas Gregor3996f232008-11-04 13:41:56 +0000105 return false;
106 }
Chris Lattner9e979552008-04-12 23:52:44 +0000107
Douglas Gregor796da182008-11-04 14:32:21 +0000108 /// VisitCXXThisExpr - Visit a C++ "this" expression.
109 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
110 // C++ [dcl.fct.default]p8:
111 // The keyword this shall not be used in a default argument of a
112 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000113 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000114 diag::err_param_default_argument_references_this)
115 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000116 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000117
118 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
119 // C++11 [expr.lambda.prim]p13:
120 // A lambda-expression appearing in a default argument shall not
121 // implicitly or explicitly capture any entity.
122 if (Lambda->capture_begin() == Lambda->capture_end())
123 return false;
124
125 return S->Diag(Lambda->getLocStart(),
126 diag::err_lambda_capture_default_arg);
127 }
Chris Lattner8123a952008-04-10 02:22:51 +0000128}
129
Richard Smithe6975e92012-04-17 00:58:00 +0000130void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
131 CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000132 // If we have an MSAny spec already, don't bother.
133 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000134 return;
135
136 const FunctionProtoType *Proto
137 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000138 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
139 if (!Proto)
140 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000141
142 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
143
144 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000145 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000146 ClearExceptions();
147 ComputedEST = EST;
148 return;
149 }
150
Richard Smith7a614d82011-06-11 17:19:42 +0000151 // FIXME: If the call to this decl is using any of its default arguments, we
152 // need to search them for potentially-throwing calls.
153
Sean Hunt001cad92011-05-10 00:49:42 +0000154 // If this function has a basic noexcept, it doesn't affect the outcome.
155 if (EST == EST_BasicNoexcept)
156 return;
157
158 // If we have a throw-all spec at this point, ignore the function.
159 if (ComputedEST == EST_None)
160 return;
161
162 // If we're still at noexcept(true) and there's a nothrow() callee,
163 // change to that specification.
164 if (EST == EST_DynamicNone) {
165 if (ComputedEST == EST_BasicNoexcept)
166 ComputedEST = EST_DynamicNone;
167 return;
168 }
169
170 // Check out noexcept specs.
171 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000172 FunctionProtoType::NoexceptResult NR =
173 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000174 assert(NR != FunctionProtoType::NR_NoNoexcept &&
175 "Must have noexcept result for EST_ComputedNoexcept.");
176 assert(NR != FunctionProtoType::NR_Dependent &&
177 "Should not generate implicit declarations for dependent cases, "
178 "and don't know how to handle them anyway.");
179
180 // noexcept(false) -> no spec on the new function
181 if (NR == FunctionProtoType::NR_Throw) {
182 ClearExceptions();
183 ComputedEST = EST_None;
184 }
185 // noexcept(true) won't change anything either.
186 return;
187 }
188
189 assert(EST == EST_Dynamic && "EST case not considered earlier.");
190 assert(ComputedEST != EST_None &&
191 "Shouldn't collect exceptions when throw-all is guaranteed.");
192 ComputedEST = EST_Dynamic;
193 // Record the exceptions in this function's exception specification.
194 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
195 EEnd = Proto->exception_end();
196 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000197 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000198 Exceptions.push_back(*E);
199}
200
Richard Smith7a614d82011-06-11 17:19:42 +0000201void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000202 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000203 return;
204
205 // FIXME:
206 //
207 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000208 // [An] implicit exception-specification specifies the type-id T if and
209 // only if T is allowed by the exception-specification of a function directly
210 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000211 // function it directly invokes allows all exceptions, and f shall allow no
212 // exceptions if every function it directly invokes allows no exceptions.
213 //
214 // Note in particular that if an implicit exception-specification is generated
215 // for a function containing a throw-expression, that specification can still
216 // be noexcept(true).
217 //
218 // Note also that 'directly invoked' is not defined in the standard, and there
219 // is no indication that we should only consider potentially-evaluated calls.
220 //
221 // Ultimately we should implement the intent of the standard: the exception
222 // specification should be the set of exceptions which can be thrown by the
223 // implicit definition. For now, we assume that any non-nothrow expression can
224 // throw any exception.
225
Richard Smithe6975e92012-04-17 00:58:00 +0000226 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000227 ComputedEST = EST_None;
228}
229
Anders Carlssoned961f92009-08-25 02:29:20 +0000230bool
John McCall9ae2f072010-08-23 23:25:46 +0000231Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000232 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000233 if (RequireCompleteType(Param->getLocation(), Param->getType(),
234 diag::err_typecheck_decl_incomplete_type)) {
235 Param->setInvalidDecl();
236 return true;
237 }
238
Anders Carlssoned961f92009-08-25 02:29:20 +0000239 // C++ [dcl.fct.default]p5
240 // A default argument expression is implicitly converted (clause
241 // 4) to the parameter type. The default argument expression has
242 // the same semantic constraints as the initializer expression in
243 // a declaration of a variable of the parameter type, using the
244 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000245 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
246 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000247 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
248 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000249 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000250 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000251 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000252 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000253 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000254
John McCallb4eb64d2010-10-08 02:01:28 +0000255 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000256 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // Okay: add the default argument to the parameter
259 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000261 // We have already instantiated this parameter; provide each of the
262 // instantiations with the uninstantiated default argument.
263 UnparsedDefaultArgInstantiationsMap::iterator InstPos
264 = UnparsedDefaultArgInstantiations.find(Param);
265 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
266 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
267 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
268
269 // We're done tracking this parameter's instantiations.
270 UnparsedDefaultArgInstantiations.erase(InstPos);
271 }
272
Anders Carlsson9351c172009-08-25 03:18:48 +0000273 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000274}
275
Chris Lattner8123a952008-04-10 02:22:51 +0000276/// ActOnParamDefaultArgument - Check whether the default argument
277/// provided for a function parameter is well-formed. If so, attach it
278/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000279void
John McCalld226f652010-08-21 09:40:31 +0000280Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000281 Expr *DefaultArg) {
282 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000283 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
John McCalld226f652010-08-21 09:40:31 +0000285 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000286 UnparsedDefaultArgLocs.erase(Param);
287
Chris Lattner3d1cee32008-04-08 05:04:30 +0000288 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000289 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000290 Diag(EqualLoc, diag::err_param_default_argument)
291 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000292 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000293 return;
294 }
295
Douglas Gregor6f526752010-12-16 08:48:57 +0000296 // Check for unexpanded parameter packs.
297 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
298 Param->setInvalidDecl();
299 return;
300 }
301
Anders Carlsson66e30672009-08-25 01:02:06 +0000302 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000303 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
304 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000305 Param->setInvalidDecl();
306 return;
307 }
Mike Stump1eb44332009-09-09 15:08:12 +0000308
John McCall9ae2f072010-08-23 23:25:46 +0000309 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000310}
311
Douglas Gregor61366e92008-12-24 00:01:03 +0000312/// ActOnParamUnparsedDefaultArgument - We've seen a default
313/// argument for a function parameter, but we can't parse it yet
314/// because we're inside a class definition. Note that this default
315/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000316void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000317 SourceLocation EqualLoc,
318 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000319 if (!param)
320 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000321
John McCalld226f652010-08-21 09:40:31 +0000322 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000323 if (Param)
324 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Anders Carlsson5e300d12009-06-12 16:51:40 +0000326 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000327}
328
Douglas Gregor72b505b2008-12-16 21:30:33 +0000329/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
330/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000331void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000332 if (!param)
333 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000334
John McCalld226f652010-08-21 09:40:31 +0000335 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Anders Carlsson5e300d12009-06-12 16:51:40 +0000337 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Anders Carlsson5e300d12009-06-12 16:51:40 +0000339 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000340}
341
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000342/// CheckExtraCXXDefaultArguments - Check for any extra default
343/// arguments in the declarator, which is not a function declaration
344/// or definition and therefore is not permitted to have default
345/// arguments. This routine should be invoked for every declarator
346/// that is not a function declaration or definition.
347void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
348 // C++ [dcl.fct.default]p3
349 // A default argument expression shall be specified only in the
350 // parameter-declaration-clause of a function declaration or in a
351 // template-parameter (14.1). It shall not be specified for a
352 // parameter pack. If it is specified in a
353 // parameter-declaration-clause, it shall not occur within a
354 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000355 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000356 DeclaratorChunk &chunk = D.getTypeObject(i);
357 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000358 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
359 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000360 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000361 if (Param->hasUnparsedDefaultArg()) {
362 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
365 delete Toks;
366 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000367 } else if (Param->getDefaultArg()) {
368 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
369 << Param->getDefaultArg()->getSourceRange();
370 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000371 }
372 }
373 }
374 }
375}
376
Craig Topper1a6eac82012-09-21 04:33:26 +0000377/// MergeCXXFunctionDecl - Merge two declarations of the same C++
378/// function, once we already know that they have the same
379/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
380/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000381bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
382 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000383 bool Invalid = false;
384
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000386 // For non-template functions, default arguments can be added in
387 // later declarations of a function in the same
388 // scope. Declarations in different scopes have completely
389 // distinct sets of default arguments. That is, declarations in
390 // inner scopes do not acquire default arguments from
391 // declarations in outer scopes, and vice versa. In a given
392 // function declaration, all parameters subsequent to a
393 // parameter with a default argument shall have default
394 // arguments supplied in this or previous declarations. A
395 // default argument shall not be redefined by a later
396 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000397 //
398 // C++ [dcl.fct.default]p6:
399 // Except for member functions of class templates, the default arguments
400 // in a member function definition that appears outside of the class
401 // definition are added to the set of default arguments provided by the
402 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000403 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
404 ParmVarDecl *OldParam = Old->getParamDecl(p);
405 ParmVarDecl *NewParam = New->getParamDecl(p);
406
James Molloy9cda03f2012-03-13 08:55:35 +0000407 bool OldParamHasDfl = OldParam->hasDefaultArg();
408 bool NewParamHasDfl = NewParam->hasDefaultArg();
409
410 NamedDecl *ND = Old;
411 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
412 // Ignore default parameters of old decl if they are not in
413 // the same scope.
414 OldParamHasDfl = false;
415
416 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000417
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 unsigned DiagDefaultParamID =
419 diag::err_param_default_argument_redefinition;
420
421 // MSVC accepts that default parameters be redefined for member functions
422 // of template class. The new default parameter's value is ignored.
423 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000424 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000425 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
426 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000427 // Merge the old default argument into the new parameter.
428 NewParam->setHasInheritedDefaultArg();
429 if (OldParam->hasUninstantiatedDefaultArg())
430 NewParam->setUninstantiatedDefaultArg(
431 OldParam->getUninstantiatedDefaultArg());
432 else
433 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000434 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000435 Invalid = false;
436 }
437 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000438
Francois Pichet8cf90492011-04-10 04:58:30 +0000439 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
440 // hint here. Alternatively, we could walk the type-source information
441 // for NewParam to find the last source location in the type... but it
442 // isn't worth the effort right now. This is the kind of test case that
443 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000444 // int f(int);
445 // void g(int (*fp)(int) = f);
446 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000447 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000448 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000449
450 // Look for the function declaration where the default argument was
451 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000452 for (FunctionDecl *Older = Old->getPreviousDecl();
453 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000454 if (!Older->getParamDecl(p)->hasDefaultArg())
455 break;
456
457 OldParam = Older->getParamDecl(p);
458 }
459
460 Diag(OldParam->getLocation(), diag::note_previous_definition)
461 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000462 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000463 // Merge the old default argument into the new parameter.
464 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000465 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000466 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000467 if (OldParam->hasUninstantiatedDefaultArg())
468 NewParam->setUninstantiatedDefaultArg(
469 OldParam->getUninstantiatedDefaultArg());
470 else
John McCall3d6c1782010-05-04 01:53:42 +0000471 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000472 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000473 if (New->getDescribedFunctionTemplate()) {
474 // Paragraph 4, quoted above, only applies to non-template functions.
475 Diag(NewParam->getLocation(),
476 diag::err_param_default_argument_template_redecl)
477 << NewParam->getDefaultArgRange();
478 Diag(Old->getLocation(), diag::note_template_prev_declaration)
479 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000480 } else if (New->getTemplateSpecializationKind()
481 != TSK_ImplicitInstantiation &&
482 New->getTemplateSpecializationKind() != TSK_Undeclared) {
483 // C++ [temp.expr.spec]p21:
484 // Default function arguments shall not be specified in a declaration
485 // or a definition for one of the following explicit specializations:
486 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000487 // - the explicit specialization of a member function template;
488 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000489 // template where the class template specialization to which the
490 // member function specialization belongs is implicitly
491 // instantiated.
492 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
493 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
494 << New->getDeclName()
495 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000496 } else if (New->getDeclContext()->isDependentContext()) {
497 // C++ [dcl.fct.default]p6 (DR217):
498 // Default arguments for a member function of a class template shall
499 // be specified on the initial declaration of the member function
500 // within the class template.
501 //
502 // Reading the tea leaves a bit in DR217 and its reference to DR205
503 // leads me to the conclusion that one cannot add default function
504 // arguments for an out-of-line definition of a member function of a
505 // dependent type.
506 int WhichKind = 2;
507 if (CXXRecordDecl *Record
508 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
509 if (Record->getDescribedClassTemplate())
510 WhichKind = 0;
511 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
512 WhichKind = 1;
513 else
514 WhichKind = 2;
515 }
516
517 Diag(NewParam->getLocation(),
518 diag::err_param_default_argument_member_template_redecl)
519 << WhichKind
520 << NewParam->getDefaultArgRange();
521 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000522 }
523 }
524
Richard Smithb8abff62012-11-28 03:45:24 +0000525 // DR1344: If a default argument is added outside a class definition and that
526 // default argument makes the function a special member function, the program
527 // is ill-formed. This can only happen for constructors.
528 if (isa<CXXConstructorDecl>(New) &&
529 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
530 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
531 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
532 if (NewSM != OldSM) {
533 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
534 assert(NewParam->hasDefaultArg());
535 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
536 << NewParam->getDefaultArgRange() << NewSM;
537 Diag(Old->getLocation(), diag::note_previous_declaration);
538 }
539 }
540
Richard Smithff234882012-02-20 23:28:05 +0000541 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000542 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000543 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000544 if (New->isConstexpr() != Old->isConstexpr()) {
545 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
546 << New << New->isConstexpr();
547 Diag(Old->getLocation(), diag::note_previous_declaration);
548 Invalid = true;
549 }
550
Douglas Gregore13ad832010-02-12 07:32:17 +0000551 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000552 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000553
Douglas Gregorcda9c672009-02-16 17:45:42 +0000554 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000555}
556
Sebastian Redl60618fa2011-03-12 11:50:43 +0000557/// \brief Merge the exception specifications of two variable declarations.
558///
559/// This is called when there's a redeclaration of a VarDecl. The function
560/// checks if the redeclaration might have an exception specification and
561/// validates compatibility and merges the specs if necessary.
562void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
563 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000564 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000565 return;
566
567 assert(Context.hasSameType(New->getType(), Old->getType()) &&
568 "Should only be called if types are otherwise the same.");
569
570 QualType NewType = New->getType();
571 QualType OldType = Old->getType();
572
573 // We're only interested in pointers and references to functions, as well
574 // as pointers to member functions.
575 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
576 NewType = R->getPointeeType();
577 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
578 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
579 NewType = P->getPointeeType();
580 OldType = OldType->getAs<PointerType>()->getPointeeType();
581 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
582 NewType = M->getPointeeType();
583 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
584 }
585
586 if (!NewType->isFunctionProtoType())
587 return;
588
589 // There's lots of special cases for functions. For function pointers, system
590 // libraries are hopefully not as broken so that we don't need these
591 // workarounds.
592 if (CheckEquivalentExceptionSpec(
593 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
594 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
595 New->setInvalidDecl();
596 }
597}
598
Chris Lattner3d1cee32008-04-08 05:04:30 +0000599/// CheckCXXDefaultArguments - Verify that the default arguments for a
600/// function declaration are well-formed according to C++
601/// [dcl.fct.default].
602void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
603 unsigned NumParams = FD->getNumParams();
604 unsigned p;
605
Douglas Gregorc6889e72012-02-14 22:28:59 +0000606 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
607 isa<CXXMethodDecl>(FD) &&
608 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
609
Chris Lattner3d1cee32008-04-08 05:04:30 +0000610 // Find first parameter with a default argument
611 for (p = 0; p < NumParams; ++p) {
612 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000613 if (Param->hasDefaultArg()) {
614 // C++11 [expr.prim.lambda]p5:
615 // [...] Default arguments (8.3.6) shall not be specified in the
616 // parameter-declaration-clause of a lambda-declarator.
617 //
618 // FIXME: Core issue 974 strikes this sentence, we only provide an
619 // extension warning.
620 if (IsLambda)
621 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
622 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000623 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000624 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000625 }
626
627 // C++ [dcl.fct.default]p4:
628 // In a given function declaration, all parameters
629 // subsequent to a parameter with a default argument shall
630 // have default arguments supplied in this or previous
631 // declarations. A default argument shall not be redefined
632 // by a later declaration (not even to the same value).
633 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000634 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000635 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000636 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000637 if (Param->isInvalidDecl())
638 /* We already complained about this parameter. */;
639 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000640 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000641 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000642 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000643 else
Mike Stump1eb44332009-09-09 15:08:12 +0000644 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000645 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattner3d1cee32008-04-08 05:04:30 +0000647 LastMissingDefaultArg = p;
648 }
649 }
650
651 if (LastMissingDefaultArg > 0) {
652 // Some default arguments were missing. Clear out all of the
653 // default arguments up to (and including) the last missing
654 // default argument, so that we leave the function parameters
655 // in a semantically valid state.
656 for (p = 0; p <= LastMissingDefaultArg; ++p) {
657 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000658 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000659 Param->setDefaultArg(0);
660 }
661 }
662 }
663}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000664
Richard Smith9f569cc2011-10-01 02:31:28 +0000665// CheckConstexprParameterTypes - Check whether a function's parameter types
666// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000667// diagnostic and return false.
668static bool CheckConstexprParameterTypes(Sema &SemaRef,
669 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000670 unsigned ArgIndex = 0;
671 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
672 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
673 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
674 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
675 SourceLocation ParamLoc = PD->getLocation();
676 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000677 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000678 diag::err_constexpr_non_literal_param,
679 ArgIndex+1, PD->getSourceRange(),
680 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000681 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000682 }
Joao Matos17d35c32012-08-31 22:18:20 +0000683 return true;
684}
685
686/// \brief Get diagnostic %select index for tag kind for
687/// record diagnostic message.
688/// WARNING: Indexes apply to particular diagnostics only!
689///
690/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000691static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000692 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000693 case TTK_Struct: return 0;
694 case TTK_Interface: return 1;
695 case TTK_Class: return 2;
696 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000697 }
Joao Matos17d35c32012-08-31 22:18:20 +0000698}
699
700// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
701// the requirements of a constexpr function definition or a constexpr
702// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000703// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000704//
Richard Smith86c3ae42012-02-13 03:54:03 +0000705// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
706bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000707 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
708 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000709 // C++11 [dcl.constexpr]p4:
710 // The definition of a constexpr constructor shall satisfy the following
711 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000712 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000713 const CXXRecordDecl *RD = MD->getParent();
714 if (RD->getNumVBases()) {
715 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
716 << isa<CXXConstructorDecl>(NewFD)
717 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
718 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
719 E = RD->vbases_end(); I != E; ++I)
720 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000721 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000722 return false;
723 }
Richard Smith35340502012-01-13 04:54:00 +0000724 }
725
726 if (!isa<CXXConstructorDecl>(NewFD)) {
727 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 // The definition of a constexpr function shall satisfy the following
729 // constraints:
730 // - it shall not be virtual;
731 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
732 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000733 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000734
Richard Smith86c3ae42012-02-13 03:54:03 +0000735 // If it's not obvious why this function is virtual, find an overridden
736 // function which uses the 'virtual' keyword.
737 const CXXMethodDecl *WrittenVirtual = Method;
738 while (!WrittenVirtual->isVirtualAsWritten())
739 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
740 if (WrittenVirtual != Method)
741 Diag(WrittenVirtual->getLocation(),
742 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000743 return false;
744 }
745
746 // - its return type shall be a literal type;
747 QualType RT = NewFD->getResultType();
748 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000750 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000751 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000752 }
753
Richard Smith35340502012-01-13 04:54:00 +0000754 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000755 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000756 return false;
757
Richard Smith9f569cc2011-10-01 02:31:28 +0000758 return true;
759}
760
761/// Check the given declaration statement is legal within a constexpr function
762/// body. C++0x [dcl.constexpr]p3,p4.
763///
764/// \return true if the body is OK, false if we have diagnosed a problem.
765static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
766 DeclStmt *DS) {
767 // C++0x [dcl.constexpr]p3 and p4:
768 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
769 // contain only
770 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
771 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
772 switch ((*DclIt)->getKind()) {
773 case Decl::StaticAssert:
774 case Decl::Using:
775 case Decl::UsingShadow:
776 case Decl::UsingDirective:
777 case Decl::UnresolvedUsingTypename:
778 // - static_assert-declarations
779 // - using-declarations,
780 // - using-directives,
781 continue;
782
783 case Decl::Typedef:
784 case Decl::TypeAlias: {
785 // - typedef declarations and alias-declarations that do not define
786 // classes or enumerations,
787 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
788 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
789 // Don't allow variably-modified types in constexpr functions.
790 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
791 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
792 << TL.getSourceRange() << TL.getType()
793 << isa<CXXConstructorDecl>(Dcl);
794 return false;
795 }
796 continue;
797 }
798
799 case Decl::Enum:
800 case Decl::CXXRecord:
801 // As an extension, we allow the declaration (but not the definition) of
802 // classes and enumerations in all declarations, not just in typedef and
803 // alias declarations.
804 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
805 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
806 << isa<CXXConstructorDecl>(Dcl);
807 return false;
808 }
809 continue;
810
811 case Decl::Var:
812 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
813 << isa<CXXConstructorDecl>(Dcl);
814 return false;
815
816 default:
817 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
818 << isa<CXXConstructorDecl>(Dcl);
819 return false;
820 }
821 }
822
823 return true;
824}
825
826/// Check that the given field is initialized within a constexpr constructor.
827///
828/// \param Dcl The constexpr constructor being checked.
829/// \param Field The field being checked. This may be a member of an anonymous
830/// struct or union nested within the class being checked.
831/// \param Inits All declarations, including anonymous struct/union members and
832/// indirect members, for which any initialization was provided.
833/// \param Diagnosed Set to true if an error is produced.
834static void CheckConstexprCtorInitializer(Sema &SemaRef,
835 const FunctionDecl *Dcl,
836 FieldDecl *Field,
837 llvm::SmallSet<Decl*, 16> &Inits,
838 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000839 if (Field->isUnnamedBitfield())
840 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000841
842 if (Field->isAnonymousStructOrUnion() &&
843 Field->getType()->getAsCXXRecordDecl()->isEmpty())
844 return;
845
Richard Smith9f569cc2011-10-01 02:31:28 +0000846 if (!Inits.count(Field)) {
847 if (!Diagnosed) {
848 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
849 Diagnosed = true;
850 }
851 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
852 } else if (Field->isAnonymousStructOrUnion()) {
853 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
854 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
855 I != E; ++I)
856 // If an anonymous union contains an anonymous struct of which any member
857 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000858 if (!RD->isUnion() || Inits.count(*I))
859 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000860 }
861}
862
863/// Check the body for the given constexpr function declaration only contains
864/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
865///
866/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000867bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000868 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000869 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000870 // The definition of a constexpr function shall satisfy the following
871 // constraints: [...]
872 // - its function-body shall be = delete, = default, or a
873 // compound-statement
874 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000875 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000876 // In the definition of a constexpr constructor, [...]
877 // - its function-body shall not be a function-try-block;
878 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882
883 // - its function-body shall be [...] a compound-statement that contains only
884 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
885
886 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
887 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.
Richard Smith745f5142012-01-27 01:14:48 +0000996 llvm::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).
John McCalld226f652010-08-21 09:40:31 +00001568Decl *
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
1669 Decl *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;
Douglas Gregordd084272012-09-14 04:20:37 +00001935 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent() &&
1936 !FD->getDeclContext()->isDependentContext()) {
1937 // Note: We don't type-check when we're in a dependent context, because
1938 // the initialization-substitution code does not properly handle direct
1939 // list initialization. We have the same hackaround for ctor-initializers.
Sebastian Redl772291a2012-02-19 16:31:05 +00001940 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001941 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001942 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1943 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001944 Expr **Inits = &InitExpr;
1945 unsigned NumInits = 1;
1946 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001947 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001948 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001949 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001950 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1951 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001952 if (Init.isInvalid()) {
1953 FD->setInvalidDecl();
1954 return;
1955 }
1956
Richard Smithca523302012-06-10 03:12:00 +00001957 CheckImplicitConversions(Init.get(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001958 }
1959
1960 // C++0x [class.base.init]p7:
1961 // The initialization of each base and member constitutes a
1962 // full-expression.
1963 Init = MaybeCreateExprWithCleanups(Init);
1964 if (Init.isInvalid()) {
1965 FD->setInvalidDecl();
1966 return;
1967 }
1968
1969 InitExpr = Init.release();
1970
1971 FD->setInClassInitializer(InitExpr);
1972}
1973
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001974/// \brief Find the direct and/or virtual base specifiers that
1975/// correspond to the given base type, for use in base initialization
1976/// within a constructor.
1977static bool FindBaseInitializer(Sema &SemaRef,
1978 CXXRecordDecl *ClassDecl,
1979 QualType BaseType,
1980 const CXXBaseSpecifier *&DirectBaseSpec,
1981 const CXXBaseSpecifier *&VirtualBaseSpec) {
1982 // First, check for a direct base class.
1983 DirectBaseSpec = 0;
1984 for (CXXRecordDecl::base_class_const_iterator Base
1985 = ClassDecl->bases_begin();
1986 Base != ClassDecl->bases_end(); ++Base) {
1987 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1988 // We found a direct base of this type. That's what we're
1989 // initializing.
1990 DirectBaseSpec = &*Base;
1991 break;
1992 }
1993 }
1994
1995 // Check for a virtual base class.
1996 // FIXME: We might be able to short-circuit this if we know in advance that
1997 // there are no virtual bases.
1998 VirtualBaseSpec = 0;
1999 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2000 // We haven't found a base yet; search the class hierarchy for a
2001 // virtual base class.
2002 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2003 /*DetectVirtual=*/false);
2004 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2005 BaseType, Paths)) {
2006 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2007 Path != Paths.end(); ++Path) {
2008 if (Path->back().Base->isVirtual()) {
2009 VirtualBaseSpec = Path->back().Base;
2010 break;
2011 }
2012 }
2013 }
2014 }
2015
2016 return DirectBaseSpec || VirtualBaseSpec;
2017}
2018
Sebastian Redl6df65482011-09-24 17:48:25 +00002019/// \brief Handle a C++ member initializer using braced-init-list syntax.
2020MemInitResult
2021Sema::ActOnMemInitializer(Decl *ConstructorD,
2022 Scope *S,
2023 CXXScopeSpec &SS,
2024 IdentifierInfo *MemberOrBase,
2025 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002026 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002027 SourceLocation IdLoc,
2028 Expr *InitList,
2029 SourceLocation EllipsisLoc) {
2030 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002031 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002032 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002033}
2034
2035/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002036MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002037Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002038 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002039 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002040 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002041 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002042 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002043 SourceLocation IdLoc,
2044 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002045 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002046 SourceLocation RParenLoc,
2047 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002048 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2049 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002050 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002051 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002052 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002053}
2054
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002055namespace {
2056
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002057// Callback to only accept typo corrections that can be a valid C++ member
2058// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002059class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2060 public:
2061 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2062 : ClassDecl(ClassDecl) {}
2063
2064 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2065 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2066 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2067 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2068 else
2069 return isa<TypeDecl>(ND);
2070 }
2071 return false;
2072 }
2073
2074 private:
2075 CXXRecordDecl *ClassDecl;
2076};
2077
2078}
2079
Sebastian Redl6df65482011-09-24 17:48:25 +00002080/// \brief Handle a C++ member initializer.
2081MemInitResult
2082Sema::BuildMemInitializer(Decl *ConstructorD,
2083 Scope *S,
2084 CXXScopeSpec &SS,
2085 IdentifierInfo *MemberOrBase,
2086 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002087 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002088 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002089 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002090 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002091 if (!ConstructorD)
2092 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002094 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002095
2096 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002097 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002098 if (!Constructor) {
2099 // The user wrote a constructor initializer on a function that is
2100 // not a C++ constructor. Ignore the error for now, because we may
2101 // have more member initializers coming; we'll diagnose it just
2102 // once in ActOnMemInitializers.
2103 return true;
2104 }
2105
2106 CXXRecordDecl *ClassDecl = Constructor->getParent();
2107
2108 // C++ [class.base.init]p2:
2109 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002110 // constructor's class and, if not found in that scope, are looked
2111 // up in the scope containing the constructor's definition.
2112 // [Note: if the constructor's class contains a member with the
2113 // same name as a direct or virtual base class of the class, a
2114 // mem-initializer-id naming the member or base class and composed
2115 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002116 // mem-initializer-id for the hidden base class may be specified
2117 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002118 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002119 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002120 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002121 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002122 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002123 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002124 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2125 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002126 if (EllipsisLoc.isValid())
2127 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002128 << MemberOrBase
2129 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002130
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002131 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002132 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002133 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002134 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002135 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002136 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002137 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002138
2139 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002140 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002141 } else if (DS.getTypeSpecType() == TST_decltype) {
2142 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002143 } else {
2144 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2145 LookupParsedName(R, S, &SS);
2146
2147 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2148 if (!TyD) {
2149 if (R.isAmbiguous()) return true;
2150
John McCallfd225442010-04-09 19:01:14 +00002151 // We don't want access-control diagnostics here.
2152 R.suppressDiagnostics();
2153
Douglas Gregor7a886e12010-01-19 06:46:48 +00002154 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2155 bool NotUnknownSpecialization = false;
2156 DeclContext *DC = computeDeclContext(SS, false);
2157 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2158 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2159
2160 if (!NotUnknownSpecialization) {
2161 // When the scope specifier can refer to a member of an unknown
2162 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002163 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2164 SS.getWithLocInContext(Context),
2165 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002166 if (BaseType.isNull())
2167 return true;
2168
Douglas Gregor7a886e12010-01-19 06:46:48 +00002169 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002170 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002171 }
2172 }
2173
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002174 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002175 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002176 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002177 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002178 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002179 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002180 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2181 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002182 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002183 // We have found a non-static data member with a similar
2184 // name to what was typed; complain and initialize that
2185 // member.
2186 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2187 << MemberOrBase << true << CorrectedQuotedStr
2188 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2189 Diag(Member->getLocation(), diag::note_previous_decl)
2190 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002191
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002192 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002193 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002194 const CXXBaseSpecifier *DirectBaseSpec;
2195 const CXXBaseSpecifier *VirtualBaseSpec;
2196 if (FindBaseInitializer(*this, ClassDecl,
2197 Context.getTypeDeclType(Type),
2198 DirectBaseSpec, VirtualBaseSpec)) {
2199 // We have found a direct or virtual base class with a
2200 // similar name to what was typed; complain and initialize
2201 // that base class.
2202 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002203 << MemberOrBase << false << CorrectedQuotedStr
2204 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002205
2206 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2207 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002208 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002209 diag::note_base_class_specified_here)
2210 << BaseSpec->getType()
2211 << BaseSpec->getSourceRange();
2212
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002213 TyD = Type;
2214 }
2215 }
2216 }
2217
Douglas Gregor7a886e12010-01-19 06:46:48 +00002218 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002219 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002220 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002221 return true;
2222 }
John McCall2b194412009-12-21 10:41:20 +00002223 }
2224
Douglas Gregor7a886e12010-01-19 06:46:48 +00002225 if (BaseType.isNull()) {
2226 BaseType = Context.getTypeDeclType(TyD);
2227 if (SS.isSet()) {
2228 NestedNameSpecifier *Qualifier =
2229 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002230
Douglas Gregor7a886e12010-01-19 06:46:48 +00002231 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002232 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002233 }
John McCall2b194412009-12-21 10:41:20 +00002234 }
2235 }
Mike Stump1eb44332009-09-09 15:08:12 +00002236
John McCalla93c9342009-12-07 02:54:59 +00002237 if (!TInfo)
2238 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002239
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002240 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002241}
2242
Chandler Carruth81c64772011-09-03 01:14:15 +00002243/// Checks a member initializer expression for cases where reference (or
2244/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002245static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2246 Expr *Init,
2247 SourceLocation IdLoc) {
2248 QualType MemberTy = Member->getType();
2249
2250 // We only handle pointers and references currently.
2251 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2252 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2253 return;
2254
2255 const bool IsPointer = MemberTy->isPointerType();
2256 if (IsPointer) {
2257 if (const UnaryOperator *Op
2258 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2259 // The only case we're worried about with pointers requires taking the
2260 // address.
2261 if (Op->getOpcode() != UO_AddrOf)
2262 return;
2263
2264 Init = Op->getSubExpr();
2265 } else {
2266 // We only handle address-of expression initializers for pointers.
2267 return;
2268 }
2269 }
2270
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002271 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2272 // Taking the address of a temporary will be diagnosed as a hard error.
2273 if (IsPointer)
2274 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002275
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002276 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2277 << Member << Init->getSourceRange();
2278 } else if (const DeclRefExpr *DRE
2279 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2280 // We only warn when referring to a non-reference parameter declaration.
2281 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2282 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002283 return;
2284
2285 S.Diag(Init->getExprLoc(),
2286 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2287 : diag::warn_bind_ref_member_to_parameter)
2288 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002289 } else {
2290 // Other initializers are fine.
2291 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002292 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002293
2294 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2295 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002296}
2297
John McCallf312b1e2010-08-26 23:41:50 +00002298MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002299Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002300 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002301 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2302 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2303 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002304 "Member must be a FieldDecl or IndirectFieldDecl");
2305
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002306 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002307 return true;
2308
Douglas Gregor464b2f02010-11-05 22:21:31 +00002309 if (Member->isInvalidDecl())
2310 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002311
John McCallb4190042009-11-04 23:02:40 +00002312 // Diagnose value-uses of fields to initialize themselves, e.g.
2313 // foo(foo)
2314 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002315 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002316 Expr **Args;
2317 unsigned NumArgs;
2318 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2319 Args = ParenList->getExprs();
2320 NumArgs = ParenList->getNumExprs();
2321 } else {
2322 InitListExpr *InitList = cast<InitListExpr>(Init);
2323 Args = InitList->getInits();
2324 NumArgs = InitList->getNumInits();
2325 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002326
Richard Trieude5e75c2012-06-14 23:11:34 +00002327 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2328 != DiagnosticsEngine::Ignored)
2329 for (unsigned i = 0; i < NumArgs; ++i)
2330 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002331 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002332 // initializing the i'th field, throw a warning if any of the >= i'th
2333 // fields are used, as they are not yet initialized.
2334 // Right now we are only handling the case where the i'th field uses
2335 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002336 // Also need to take into account that some fields may be initialized by
2337 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002338 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002339
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002340 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002341
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002342 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002343 // Can't check initialization for a member of dependent type or when
2344 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002345 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002346 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002347 bool InitList = false;
2348 if (isa<InitListExpr>(Init)) {
2349 InitList = true;
2350 Args = &Init;
2351 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002352
2353 if (isStdInitializerList(Member->getType(), 0)) {
2354 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2355 << /*at end of ctor*/1 << InitRange;
2356 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002357 }
2358
Chandler Carruth894aed92010-12-06 09:23:57 +00002359 // Initialize the member.
2360 InitializedEntity MemberEntity =
2361 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2362 : InitializedEntity::InitializeMember(IndirectMember, 0);
2363 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002364 InitList ? InitializationKind::CreateDirectList(IdLoc)
2365 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2366 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002367
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002368 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2369 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002370 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002371 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002372 if (MemberInit.isInvalid())
2373 return true;
2374
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002375 CheckImplicitConversions(MemberInit.get(),
2376 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002377
2378 // C++0x [class.base.init]p7:
2379 // The initialization of each base and member constitutes a
2380 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002381 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002382 if (MemberInit.isInvalid())
2383 return true;
2384
2385 // If we are in a dependent context, template instantiation will
2386 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002387 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002388 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2389 // of the information that we have about the member
2390 // initializer. However, deconstructing the ASTs is a dicey process,
2391 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002392 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002393 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002394 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002395 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002396 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2397 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002398 }
2399
Chandler Carruth894aed92010-12-06 09:23:57 +00002400 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002401 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2402 InitRange.getBegin(), Init,
2403 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002404 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002405 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2406 InitRange.getBegin(), Init,
2407 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002408 }
Eli Friedman59c04372009-07-29 19:44:27 +00002409}
2410
John McCallf312b1e2010-08-26 23:41:50 +00002411MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002412Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002413 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002414 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002415 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002416 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002417 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002418 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002419
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002420 bool InitList = true;
2421 Expr **Args = &Init;
2422 unsigned NumArgs = 1;
2423 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2424 InitList = false;
2425 Args = ParenList->getExprs();
2426 NumArgs = ParenList->getNumExprs();
2427 }
2428
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002429 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002430 // Initialize the object.
2431 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2432 QualType(ClassDecl->getTypeForDecl(), 0));
2433 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002434 InitList ? InitializationKind::CreateDirectList(NameLoc)
2435 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2436 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002437 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2438 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002439 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002440 0);
Sean Hunt41717662011-02-26 19:13:13 +00002441 if (DelegationInit.isInvalid())
2442 return true;
2443
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002444 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2445 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002446
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002447 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002448
2449 // C++0x [class.base.init]p7:
2450 // The initialization of each base and member constitutes a
2451 // full-expression.
2452 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2453 if (DelegationInit.isInvalid())
2454 return true;
2455
Eli Friedmand21016f2012-05-19 23:35:23 +00002456 // If we are in a dependent context, template instantiation will
2457 // perform this type-checking again. Just save the arguments that we
2458 // received in a ParenListExpr.
2459 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2460 // of the information that we have about the base
2461 // initializer. However, deconstructing the ASTs is a dicey process,
2462 // and this approach is far more likely to get the corner cases right.
2463 if (CurContext->isDependentContext())
2464 DelegationInit = Owned(Init);
2465
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002466 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002467 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002468 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002469}
2470
2471MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002472Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002473 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002474 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002475 SourceLocation BaseLoc
2476 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002477
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002478 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2479 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2480 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2481
2482 // C++ [class.base.init]p2:
2483 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002484 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002485 // of that class, the mem-initializer is ill-formed. A
2486 // mem-initializer-list can initialize a base class using any
2487 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002488 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002489
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002490 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002491 if (EllipsisLoc.isValid()) {
2492 // This is a pack expansion.
2493 if (!BaseType->containsUnexpandedParameterPack()) {
2494 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002495 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002496
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002497 EllipsisLoc = SourceLocation();
2498 }
2499 } else {
2500 // Check for any unexpanded parameter packs.
2501 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2502 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002503
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002504 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002505 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002506 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002507
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002508 // Check for direct and virtual base classes.
2509 const CXXBaseSpecifier *DirectBaseSpec = 0;
2510 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2511 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002512 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2513 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002514 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002515
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002516 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2517 VirtualBaseSpec);
2518
2519 // C++ [base.class.init]p2:
2520 // Unless the mem-initializer-id names a nonstatic data member of the
2521 // constructor's class or a direct or virtual base of that class, the
2522 // mem-initializer is ill-formed.
2523 if (!DirectBaseSpec && !VirtualBaseSpec) {
2524 // If the class has any dependent bases, then it's possible that
2525 // one of those types will resolve to the same type as
2526 // BaseType. Therefore, just treat this as a dependent base
2527 // class initialization. FIXME: Should we try to check the
2528 // initialization anyway? It seems odd.
2529 if (ClassDecl->hasAnyDependentBases())
2530 Dependent = true;
2531 else
2532 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2533 << BaseType << Context.getTypeDeclType(ClassDecl)
2534 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2535 }
2536 }
2537
2538 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002539 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002540
Sebastian Redl6df65482011-09-24 17:48:25 +00002541 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2542 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002543 InitRange.getBegin(), Init,
2544 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002545 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002546
2547 // C++ [base.class.init]p2:
2548 // If a mem-initializer-id is ambiguous because it designates both
2549 // a direct non-virtual base class and an inherited virtual base
2550 // class, the mem-initializer is ill-formed.
2551 if (DirectBaseSpec && VirtualBaseSpec)
2552 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002553 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002554
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002555 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002556 if (!BaseSpec)
2557 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2558
2559 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002560 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002561 Expr **Args = &Init;
2562 unsigned NumArgs = 1;
2563 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002564 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002565 Args = ParenList->getExprs();
2566 NumArgs = ParenList->getNumExprs();
2567 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002568
2569 InitializedEntity BaseEntity =
2570 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2571 InitializationKind Kind =
2572 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2573 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2574 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002575 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2576 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002577 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002578 if (BaseInit.isInvalid())
2579 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002580
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002581 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002582
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002583 // C++0x [class.base.init]p7:
2584 // The initialization of each base and member constitutes a
2585 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002586 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002587 if (BaseInit.isInvalid())
2588 return true;
2589
2590 // If we are in a dependent context, template instantiation will
2591 // perform this type-checking again. Just save the arguments that we
2592 // received in a ParenListExpr.
2593 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2594 // of the information that we have about the base
2595 // initializer. However, deconstructing the ASTs is a dicey process,
2596 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002597 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002598 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002599
Sean Huntcbb67482011-01-08 20:30:50 +00002600 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002601 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002602 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002603 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002604 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002605}
2606
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002607// Create a static_cast\<T&&>(expr).
2608static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2609 QualType ExprType = E->getType();
2610 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2611 SourceLocation ExprLoc = E->getLocStart();
2612 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2613 TargetType, ExprLoc);
2614
2615 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2616 SourceRange(ExprLoc, ExprLoc),
2617 E->getSourceRange()).take();
2618}
2619
Anders Carlssone5ef7402010-04-23 03:10:23 +00002620/// ImplicitInitializerKind - How an implicit base or member initializer should
2621/// initialize its base or member.
2622enum ImplicitInitializerKind {
2623 IIK_Default,
2624 IIK_Copy,
2625 IIK_Move
2626};
2627
Anders Carlssondefefd22010-04-23 02:00:02 +00002628static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002629BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002630 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002631 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002632 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002633 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002634 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002635 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2636 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002637
John McCall60d7b3a2010-08-24 06:29:42 +00002638 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002639
2640 switch (ImplicitInitKind) {
2641 case IIK_Default: {
2642 InitializationKind InitKind
2643 = InitializationKind::CreateDefault(Constructor->getLocation());
2644 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002645 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002646 break;
2647 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002648
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002649 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002650 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002651 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002652 ParmVarDecl *Param = Constructor->getParamDecl(0);
2653 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002654
Anders Carlssone5ef7402010-04-23 03:10:23 +00002655 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002656 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002657 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002658 Constructor->getLocation(), ParamType,
2659 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002660
Eli Friedman5f2987c2012-02-02 03:46:19 +00002661 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2662
Anders Carlssonc7957502010-04-24 22:02:54 +00002663 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002664 QualType ArgTy =
2665 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2666 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002667
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002668 if (Moving) {
2669 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2670 }
2671
John McCallf871d0c2010-08-07 06:22:56 +00002672 CXXCastPath BasePath;
2673 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002674 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2675 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002676 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002677 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002678
Anders Carlssone5ef7402010-04-23 03:10:23 +00002679 InitializationKind InitKind
2680 = InitializationKind::CreateDirect(Constructor->getLocation(),
2681 SourceLocation(), SourceLocation());
2682 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2683 &CopyCtorArg, 1);
2684 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002685 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002686 break;
2687 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002688 }
John McCall9ae2f072010-08-23 23:25:46 +00002689
Douglas Gregor53c374f2010-12-07 00:41:46 +00002690 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002691 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002692 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002693
Anders Carlssondefefd22010-04-23 02:00:02 +00002694 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002695 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002696 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2697 SourceLocation()),
2698 BaseSpec->isVirtual(),
2699 SourceLocation(),
2700 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002701 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002702 SourceLocation());
2703
Anders Carlssondefefd22010-04-23 02:00:02 +00002704 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002705}
2706
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002707static bool RefersToRValueRef(Expr *MemRef) {
2708 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2709 return Referenced->getType()->isRValueReferenceType();
2710}
2711
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002712static bool
2713BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002714 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002715 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002716 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002717 if (Field->isInvalidDecl())
2718 return true;
2719
Chandler Carruthf186b542010-06-29 23:50:44 +00002720 SourceLocation Loc = Constructor->getLocation();
2721
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002722 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2723 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002724 ParmVarDecl *Param = Constructor->getParamDecl(0);
2725 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002726
2727 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002728 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2729 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002730
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002731 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002732 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002733 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002734 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002735
Eli Friedman5f2987c2012-02-02 03:46:19 +00002736 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2737
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002738 if (Moving) {
2739 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2740 }
2741
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002742 // Build a reference to this field within the parameter.
2743 CXXScopeSpec SS;
2744 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2745 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002746 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2747 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002748 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002749 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002750 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002751 ParamType, Loc,
2752 /*IsArrow=*/false,
2753 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002754 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002755 /*FirstQualifierInScope=*/0,
2756 MemberLookup,
2757 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002758 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002759 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002760
2761 // C++11 [class.copy]p15:
2762 // - if a member m has rvalue reference type T&&, it is direct-initialized
2763 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002764 if (RefersToRValueRef(CtorArg.get())) {
2765 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002766 }
2767
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002768 // When the field we are copying is an array, create index variables for
2769 // each dimension of the array. We use these index variables to subscript
2770 // the source array, and other clients (e.g., CodeGen) will perform the
2771 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002772 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002773 QualType BaseType = Field->getType();
2774 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002775 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002776 while (const ConstantArrayType *Array
2777 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002778 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002779 // Create the iteration variable for this array index.
2780 IdentifierInfo *IterationVarName = 0;
2781 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002782 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002783 llvm::raw_svector_ostream OS(Str);
2784 OS << "__i" << IndexVariables.size();
2785 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2786 }
2787 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002788 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002789 IterationVarName, SizeType,
2790 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002791 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002792 IndexVariables.push_back(IterationVar);
2793
2794 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002795 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002796 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002797 assert(!IterationVarRef.isInvalid() &&
2798 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002799 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2800 assert(!IterationVarRef.isInvalid() &&
2801 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002802
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002803 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002804 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002805 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002806 Loc);
2807 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002808 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002809
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002810 BaseType = Array->getElementType();
2811 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002812
2813 // The array subscript expression is an lvalue, which is wrong for moving.
2814 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002815 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002816
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002817 // Construct the entity that we will be initializing. For an array, this
2818 // will be first element in the array, which may require several levels
2819 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002820 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002821 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002822 if (Indirect)
2823 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2824 else
2825 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002826 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2827 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2828 0,
2829 Entities.back()));
2830
2831 // Direct-initialize to use the copy constructor.
2832 InitializationKind InitKind =
2833 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2834
Sebastian Redl74e611a2011-09-04 18:14:28 +00002835 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002836 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002837 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002838
John McCall60d7b3a2010-08-24 06:29:42 +00002839 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002840 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002841 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002842 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002843 if (MemberInit.isInvalid())
2844 return true;
2845
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002846 if (Indirect) {
2847 assert(IndexVariables.size() == 0 &&
2848 "Indirect field improperly initialized");
2849 CXXMemberInit
2850 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2851 Loc, Loc,
2852 MemberInit.takeAs<Expr>(),
2853 Loc);
2854 } else
2855 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2856 Loc, MemberInit.takeAs<Expr>(),
2857 Loc,
2858 IndexVariables.data(),
2859 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002860 return false;
2861 }
2862
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002863 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2864
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002865 QualType FieldBaseElementType =
2866 SemaRef.Context.getBaseElementType(Field->getType());
2867
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002868 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002869 InitializedEntity InitEntity
2870 = Indirect? InitializedEntity::InitializeMember(Indirect)
2871 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002872 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002873 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002874
2875 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002876 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002877 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002878
Douglas Gregor53c374f2010-12-07 00:41:46 +00002879 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002880 if (MemberInit.isInvalid())
2881 return true;
2882
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002883 if (Indirect)
2884 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2885 Indirect, Loc,
2886 Loc,
2887 MemberInit.get(),
2888 Loc);
2889 else
2890 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2891 Field, Loc, Loc,
2892 MemberInit.get(),
2893 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002894 return false;
2895 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002896
Sean Hunt1f2f3842011-05-17 00:19:05 +00002897 if (!Field->getParent()->isUnion()) {
2898 if (FieldBaseElementType->isReferenceType()) {
2899 SemaRef.Diag(Constructor->getLocation(),
2900 diag::err_uninitialized_member_in_ctor)
2901 << (int)Constructor->isImplicit()
2902 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2903 << 0 << Field->getDeclName();
2904 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2905 return true;
2906 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002907
Sean Hunt1f2f3842011-05-17 00:19:05 +00002908 if (FieldBaseElementType.isConstQualified()) {
2909 SemaRef.Diag(Constructor->getLocation(),
2910 diag::err_uninitialized_member_in_ctor)
2911 << (int)Constructor->isImplicit()
2912 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2913 << 1 << Field->getDeclName();
2914 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2915 return true;
2916 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002917 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002918
David Blaikie4e4d0842012-03-11 07:00:24 +00002919 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002920 FieldBaseElementType->isObjCRetainableType() &&
2921 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2922 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002923 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002924 // Default-initialize Objective-C pointers to NULL.
2925 CXXMemberInit
2926 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2927 Loc, Loc,
2928 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2929 Loc);
2930 return false;
2931 }
2932
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002933 // Nothing to initialize.
2934 CXXMemberInit = 0;
2935 return false;
2936}
John McCallf1860e52010-05-20 23:23:51 +00002937
2938namespace {
2939struct BaseAndFieldInfo {
2940 Sema &S;
2941 CXXConstructorDecl *Ctor;
2942 bool AnyErrorsInInits;
2943 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002944 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002945 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002946
2947 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2948 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002949 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2950 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002951 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002952 else if (Generated && Ctor->isMoveConstructor())
2953 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002954 else
2955 IIK = IIK_Default;
2956 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002957
2958 bool isImplicitCopyOrMove() const {
2959 switch (IIK) {
2960 case IIK_Copy:
2961 case IIK_Move:
2962 return true;
2963
2964 case IIK_Default:
2965 return false;
2966 }
David Blaikie30263482012-01-20 21:50:17 +00002967
2968 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002969 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002970
2971 bool addFieldInitializer(CXXCtorInitializer *Init) {
2972 AllToInit.push_back(Init);
2973
2974 // Check whether this initializer makes the field "used".
2975 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2976 S.UnusedPrivateFields.remove(Init->getAnyMember());
2977
2978 return false;
2979 }
John McCallf1860e52010-05-20 23:23:51 +00002980};
2981}
2982
Richard Smitha4950662011-09-19 13:34:43 +00002983/// \brief Determine whether the given indirect field declaration is somewhere
2984/// within an anonymous union.
2985static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2986 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2987 CEnd = F->chain_end();
2988 C != CEnd; ++C)
2989 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2990 if (Record->isUnion())
2991 return true;
2992
2993 return false;
2994}
2995
Douglas Gregorddb21472011-11-02 23:04:16 +00002996/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2997/// array type.
2998static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2999 if (T->isIncompleteArrayType())
3000 return true;
3001
3002 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3003 if (!ArrayT->getSize())
3004 return true;
3005
3006 T = ArrayT->getElementType();
3007 }
3008
3009 return false;
3010}
3011
Richard Smith7a614d82011-06-11 17:19:42 +00003012static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003013 FieldDecl *Field,
3014 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003015
Chandler Carruthe861c602010-06-30 02:59:29 +00003016 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003017 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3018 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003019
Richard Smith0b8220a2012-08-07 21:30:42 +00003020 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003021 // has a brace-or-equal-initializer, the entity is initialized as specified
3022 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003023 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003024 CXXCtorInitializer *Init;
3025 if (Indirect)
3026 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3027 SourceLocation(),
3028 SourceLocation(), 0,
3029 SourceLocation());
3030 else
3031 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3032 SourceLocation(),
3033 SourceLocation(), 0,
3034 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003035 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003036 }
3037
Richard Smithc115f632011-09-18 11:14:50 +00003038 // Don't build an implicit initializer for union members if none was
3039 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003040 if (Field->getParent()->isUnion() ||
3041 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003042 return false;
3043
Douglas Gregorddb21472011-11-02 23:04:16 +00003044 // Don't initialize incomplete or zero-length arrays.
3045 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3046 return false;
3047
John McCallf1860e52010-05-20 23:23:51 +00003048 // Don't try to build an implicit initializer if there were semantic
3049 // errors in any of the initializers (and therefore we might be
3050 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003051 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003052 return false;
3053
Sean Huntcbb67482011-01-08 20:30:50 +00003054 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003055 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3056 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003057 return true;
John McCallf1860e52010-05-20 23:23:51 +00003058
Richard Smith0b8220a2012-08-07 21:30:42 +00003059 if (!Init)
3060 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003061
Richard Smith0b8220a2012-08-07 21:30:42 +00003062 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003063}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003064
3065bool
3066Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3067 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003068 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003069 Constructor->setNumCtorInitializers(1);
3070 CXXCtorInitializer **initializer =
3071 new (Context) CXXCtorInitializer*[1];
3072 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3073 Constructor->setCtorInitializers(initializer);
3074
Sean Huntb76af9c2011-05-03 23:05:34 +00003075 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003076 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003077 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3078 }
3079
Sean Huntc1598702011-05-05 00:05:47 +00003080 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003081
Sean Hunt059ce0d2011-05-01 07:04:31 +00003082 return false;
3083}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003084
John McCallb77115d2011-06-17 00:18:42 +00003085bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
3086 CXXCtorInitializer **Initializers,
3087 unsigned NumInitializers,
3088 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003089 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003090 // Just store the initializers as written, they will be checked during
3091 // instantiation.
3092 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003093 Constructor->setNumCtorInitializers(NumInitializers);
3094 CXXCtorInitializer **baseOrMemberInitializers =
3095 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003096 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00003097 NumInitializers * sizeof(CXXCtorInitializer*));
3098 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003099 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003100
3101 // Let template instantiation know whether we had errors.
3102 if (AnyErrors)
3103 Constructor->setInvalidDecl();
3104
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003105 return false;
3106 }
3107
John McCallf1860e52010-05-20 23:23:51 +00003108 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003109
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003110 // We need to build the initializer AST according to order of construction
3111 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003112 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003113 if (!ClassDecl)
3114 return true;
3115
Eli Friedman80c30da2009-11-09 19:20:36 +00003116 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003117
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003118 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003119 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003120
3121 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003122 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003123 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003124 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003125 }
3126
Anders Carlsson711f34a2010-04-21 19:52:01 +00003127 // Keep track of the direct virtual bases.
3128 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3129 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3130 E = ClassDecl->bases_end(); I != E; ++I) {
3131 if (I->isVirtual())
3132 DirectVBases.insert(I);
3133 }
3134
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003135 // Push virtual bases before others.
3136 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3137 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3138
Sean Huntcbb67482011-01-08 20:30:50 +00003139 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003140 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3141 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003142 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003143 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003144 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003145 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003146 VBase, IsInheritedVirtualBase,
3147 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003148 HadError = true;
3149 continue;
3150 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003151
John McCallf1860e52010-05-20 23:23:51 +00003152 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003153 }
3154 }
Mike Stump1eb44332009-09-09 15:08:12 +00003155
John McCallf1860e52010-05-20 23:23:51 +00003156 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003157 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3158 E = ClassDecl->bases_end(); Base != E; ++Base) {
3159 // Virtuals are in the virtual base list and already constructed.
3160 if (Base->isVirtual())
3161 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003162
Sean Huntcbb67482011-01-08 20:30:50 +00003163 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003164 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3165 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003166 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003167 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003168 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003169 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003170 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003171 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003172 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003173 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003174
John McCallf1860e52010-05-20 23:23:51 +00003175 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003176 }
3177 }
Mike Stump1eb44332009-09-09 15:08:12 +00003178
John McCallf1860e52010-05-20 23:23:51 +00003179 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003180 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3181 MemEnd = ClassDecl->decls_end();
3182 Mem != MemEnd; ++Mem) {
3183 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003184 // C++ [class.bit]p2:
3185 // A declaration for a bit-field that omits the identifier declares an
3186 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3187 // initialized.
3188 if (F->isUnnamedBitfield())
3189 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003190
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003191 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003192 // handle anonymous struct/union fields based on their individual
3193 // indirect fields.
3194 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3195 continue;
3196
3197 if (CollectFieldInitializer(*this, Info, F))
3198 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003199 continue;
3200 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003201
3202 // Beyond this point, we only consider default initialization.
3203 if (Info.IIK != IIK_Default)
3204 continue;
3205
3206 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3207 if (F->getType()->isIncompleteArrayType()) {
3208 assert(ClassDecl->hasFlexibleArrayMember() &&
3209 "Incomplete array type is not valid");
3210 continue;
3211 }
3212
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003213 // Initialize each field of an anonymous struct individually.
3214 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3215 HadError = true;
3216
3217 continue;
3218 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003219 }
Mike Stump1eb44332009-09-09 15:08:12 +00003220
John McCallf1860e52010-05-20 23:23:51 +00003221 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003222 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003223 Constructor->setNumCtorInitializers(NumInitializers);
3224 CXXCtorInitializer **baseOrMemberInitializers =
3225 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003226 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003227 NumInitializers * sizeof(CXXCtorInitializer*));
3228 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003229
John McCallef027fe2010-03-16 21:39:52 +00003230 // Constructors implicitly reference the base and member
3231 // destructors.
3232 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3233 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003234 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003235
3236 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003237}
3238
Eli Friedman6347f422009-07-21 19:28:10 +00003239static void *GetKeyForTopLevelField(FieldDecl *Field) {
3240 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003241 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003242 if (RT->getDecl()->isAnonymousStructOrUnion())
3243 return static_cast<void *>(RT->getDecl());
3244 }
3245 return static_cast<void *>(Field);
3246}
3247
Anders Carlssonea356fb2010-04-02 05:42:15 +00003248static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003249 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003250}
3251
Anders Carlssonea356fb2010-04-02 05:42:15 +00003252static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003253 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003254 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003255 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003256
Eli Friedman6347f422009-07-21 19:28:10 +00003257 // For fields injected into the class via declaration of an anonymous union,
3258 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003259 FieldDecl *Field = Member->getAnyMember();
3260
John McCall3c3ccdb2010-04-10 09:28:51 +00003261 // If the field is a member of an anonymous struct or union, our key
3262 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003263 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003264 if (RD->isAnonymousStructOrUnion()) {
3265 while (true) {
3266 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3267 if (Parent->isAnonymousStructOrUnion())
3268 RD = Parent;
3269 else
3270 break;
3271 }
3272
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003273 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003274 }
Mike Stump1eb44332009-09-09 15:08:12 +00003275
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003276 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003277}
3278
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003279static void
3280DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003281 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003282 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003283 unsigned NumInits) {
3284 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003285 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003286
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003287 // Don't check initializers order unless the warning is enabled at the
3288 // location of at least one initializer.
3289 bool ShouldCheckOrder = false;
3290 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003291 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003292 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3293 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003294 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003295 ShouldCheckOrder = true;
3296 break;
3297 }
3298 }
3299 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003300 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003301
John McCalld6ca8da2010-04-10 07:37:23 +00003302 // Build the list of bases and members in the order that they'll
3303 // actually be initialized. The explicit initializers should be in
3304 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003305 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003306
Anders Carlsson071d6102010-04-02 03:38:04 +00003307 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3308
John McCalld6ca8da2010-04-10 07:37:23 +00003309 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003310 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003311 ClassDecl->vbases_begin(),
3312 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003313 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003314
John McCalld6ca8da2010-04-10 07:37:23 +00003315 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003316 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003317 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003318 if (Base->isVirtual())
3319 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003320 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003321 }
Mike Stump1eb44332009-09-09 15:08:12 +00003322
John McCalld6ca8da2010-04-10 07:37:23 +00003323 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003324 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003325 E = ClassDecl->field_end(); Field != E; ++Field) {
3326 if (Field->isUnnamedBitfield())
3327 continue;
3328
David Blaikie581deb32012-06-06 20:45:41 +00003329 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003330 }
3331
John McCalld6ca8da2010-04-10 07:37:23 +00003332 unsigned NumIdealInits = IdealInitKeys.size();
3333 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003334
Sean Huntcbb67482011-01-08 20:30:50 +00003335 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003336 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003337 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003338 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003339
3340 // Scan forward to try to find this initializer in the idealized
3341 // initializers list.
3342 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3343 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003344 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003345
3346 // If we didn't find this initializer, it must be because we
3347 // scanned past it on a previous iteration. That can only
3348 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003349 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003350 Sema::SemaDiagnosticBuilder D =
3351 SemaRef.Diag(PrevInit->getSourceLocation(),
3352 diag::warn_initializer_out_of_order);
3353
Francois Pichet00eb3f92010-12-04 09:14:42 +00003354 if (PrevInit->isAnyMemberInitializer())
3355 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003356 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003357 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003358
Francois Pichet00eb3f92010-12-04 09:14:42 +00003359 if (Init->isAnyMemberInitializer())
3360 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003361 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003362 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003363
3364 // Move back to the initializer's location in the ideal list.
3365 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3366 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003367 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003368
3369 assert(IdealIndex != NumIdealInits &&
3370 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003371 }
John McCalld6ca8da2010-04-10 07:37:23 +00003372
3373 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003374 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003375}
3376
John McCall3c3ccdb2010-04-10 09:28:51 +00003377namespace {
3378bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003379 CXXCtorInitializer *Init,
3380 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003381 if (!PrevInit) {
3382 PrevInit = Init;
3383 return false;
3384 }
3385
3386 if (FieldDecl *Field = Init->getMember())
3387 S.Diag(Init->getSourceLocation(),
3388 diag::err_multiple_mem_initialization)
3389 << Field->getDeclName()
3390 << Init->getSourceRange();
3391 else {
John McCallf4c73712011-01-19 06:33:43 +00003392 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003393 assert(BaseClass && "neither field nor base");
3394 S.Diag(Init->getSourceLocation(),
3395 diag::err_multiple_base_initialization)
3396 << QualType(BaseClass, 0)
3397 << Init->getSourceRange();
3398 }
3399 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3400 << 0 << PrevInit->getSourceRange();
3401
3402 return true;
3403}
3404
Sean Huntcbb67482011-01-08 20:30:50 +00003405typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003406typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3407
3408bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003409 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003410 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003411 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003412 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003413 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003414
3415 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003416 if (Parent->isUnion()) {
3417 UnionEntry &En = Unions[Parent];
3418 if (En.first && En.first != Child) {
3419 S.Diag(Init->getSourceLocation(),
3420 diag::err_multiple_mem_union_initialization)
3421 << Field->getDeclName()
3422 << Init->getSourceRange();
3423 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3424 << 0 << En.second->getSourceRange();
3425 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003426 }
3427 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003428 En.first = Child;
3429 En.second = Init;
3430 }
David Blaikie6fe29652011-11-17 06:01:57 +00003431 if (!Parent->isAnonymousStructOrUnion())
3432 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003433 }
3434
3435 Child = Parent;
3436 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003437 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003438
3439 return false;
3440}
3441}
3442
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003443/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003444void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003445 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003446 CXXCtorInitializer **meminits,
3447 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003448 bool AnyErrors) {
3449 if (!ConstructorDecl)
3450 return;
3451
3452 AdjustDeclIfTemplate(ConstructorDecl);
3453
3454 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003455 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003456
3457 if (!Constructor) {
3458 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3459 return;
3460 }
3461
Sean Huntcbb67482011-01-08 20:30:50 +00003462 CXXCtorInitializer **MemInits =
3463 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003464
3465 // Mapping for the duplicate initializers check.
3466 // For member initializers, this is keyed with a FieldDecl*.
3467 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003468 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003469
3470 // Mapping for the inconsistent anonymous-union initializers check.
3471 RedundantUnionMap MemberUnions;
3472
Anders Carlssonea356fb2010-04-02 05:42:15 +00003473 bool HadError = false;
3474 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003475 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003476
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003477 // Set the source order index.
3478 Init->setSourceOrder(i);
3479
Francois Pichet00eb3f92010-12-04 09:14:42 +00003480 if (Init->isAnyMemberInitializer()) {
3481 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003482 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3483 CheckRedundantUnionInit(*this, Init, MemberUnions))
3484 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003485 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003486 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3487 if (CheckRedundantInit(*this, Init, Members[Key]))
3488 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003489 } else {
3490 assert(Init->isDelegatingInitializer());
3491 // This must be the only initializer
Richard Smitha6ddea62012-09-14 18:21:10 +00003492 if (NumMemInits != 1) {
3493 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003494 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003495 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003496 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003497 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003498 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003499 // Return immediately as the initializer is set.
3500 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003501 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003502 }
3503
Anders Carlssonea356fb2010-04-02 05:42:15 +00003504 if (HadError)
3505 return;
3506
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003507 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003508
Sean Huntcbb67482011-01-08 20:30:50 +00003509 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003510}
3511
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003512void
John McCallef027fe2010-03-16 21:39:52 +00003513Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3514 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003515 // Ignore dependent contexts. Also ignore unions, since their members never
3516 // have destructors implicitly called.
3517 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003518 return;
John McCall58e6f342010-03-16 05:22:47 +00003519
3520 // FIXME: all the access-control diagnostics are positioned on the
3521 // field/base declaration. That's probably good; that said, the
3522 // user might reasonably want to know why the destructor is being
3523 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003524
Anders Carlsson9f853df2009-11-17 04:44:12 +00003525 // Non-static data members.
3526 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3527 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003528 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003529 if (Field->isInvalidDecl())
3530 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003531
3532 // Don't destroy incomplete or zero-length arrays.
3533 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3534 continue;
3535
Anders Carlsson9f853df2009-11-17 04:44:12 +00003536 QualType FieldType = Context.getBaseElementType(Field->getType());
3537
3538 const RecordType* RT = FieldType->getAs<RecordType>();
3539 if (!RT)
3540 continue;
3541
3542 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003543 if (FieldClassDecl->isInvalidDecl())
3544 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003545 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003546 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003547 // The destructor for an implicit anonymous union member is never invoked.
3548 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3549 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003550
Douglas Gregordb89f282010-07-01 22:47:18 +00003551 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003552 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003553 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003554 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003555 << Field->getDeclName()
3556 << FieldType);
3557
Eli Friedman5f2987c2012-02-02 03:46:19 +00003558 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003559 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003560 }
3561
John McCall58e6f342010-03-16 05:22:47 +00003562 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3563
Anders Carlsson9f853df2009-11-17 04:44:12 +00003564 // Bases.
3565 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3566 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003567 // Bases are always records in a well-formed non-dependent class.
3568 const RecordType *RT = Base->getType()->getAs<RecordType>();
3569
3570 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003571 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003572 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003573
John McCall58e6f342010-03-16 05:22:47 +00003574 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003575 // If our base class is invalid, we probably can't get its dtor anyway.
3576 if (BaseClassDecl->isInvalidDecl())
3577 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003578 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003579 continue;
John McCall58e6f342010-03-16 05:22:47 +00003580
Douglas Gregordb89f282010-07-01 22:47:18 +00003581 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003582 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003583
3584 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003585 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003586 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003587 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003588 << Base->getSourceRange(),
3589 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003590
Eli Friedman5f2987c2012-02-02 03:46:19 +00003591 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003592 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003593 }
3594
3595 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003596 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3597 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003598
3599 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003600 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003601
3602 // Ignore direct virtual bases.
3603 if (DirectVirtualBases.count(RT))
3604 continue;
3605
John McCall58e6f342010-03-16 05:22:47 +00003606 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003607 // If our base class is invalid, we probably can't get its dtor anyway.
3608 if (BaseClassDecl->isInvalidDecl())
3609 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003610 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003611 continue;
John McCall58e6f342010-03-16 05:22:47 +00003612
Douglas Gregordb89f282010-07-01 22:47:18 +00003613 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003614 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003615 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003616 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003617 << VBase->getType(),
3618 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003619
Eli Friedman5f2987c2012-02-02 03:46:19 +00003620 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003621 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003622 }
3623}
3624
John McCalld226f652010-08-21 09:40:31 +00003625void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003626 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003627 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003628
Mike Stump1eb44332009-09-09 15:08:12 +00003629 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003630 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003631 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003632}
3633
Mike Stump1eb44332009-09-09 15:08:12 +00003634bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003635 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003636 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3637 unsigned DiagID;
3638 AbstractDiagSelID SelID;
3639
3640 public:
3641 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3642 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3643
3644 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003645 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003646 if (SelID == -1)
3647 S.Diag(Loc, DiagID) << T;
3648 else
3649 S.Diag(Loc, DiagID) << SelID << T;
3650 }
3651 } Diagnoser(DiagID, SelID);
3652
3653 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003654}
3655
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003656bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003657 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003658 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003659 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003660
Anders Carlsson11f21a02009-03-23 19:10:31 +00003661 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003662 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003663
Ted Kremenek6217b802009-07-29 21:53:49 +00003664 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003665 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003666 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003667 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003669 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003670 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003671 }
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Ted Kremenek6217b802009-07-29 21:53:49 +00003673 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003674 if (!RT)
3675 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003676
John McCall86ff3082010-02-04 22:26:26 +00003677 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003678
John McCall94c3b562010-08-18 09:41:07 +00003679 // We can't answer whether something is abstract until it has a
3680 // definition. If it's currently being defined, we'll walk back
3681 // over all the declarations when we have a full definition.
3682 const CXXRecordDecl *Def = RD->getDefinition();
3683 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003684 return false;
3685
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003686 if (!RD->isAbstract())
3687 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003689 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003690 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003691
John McCall94c3b562010-08-18 09:41:07 +00003692 return true;
3693}
3694
3695void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3696 // Check if we've already emitted the list of pure virtual functions
3697 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003698 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003699 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003700
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003701 CXXFinalOverriderMap FinalOverriders;
3702 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003703
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003704 // Keep a set of seen pure methods so we won't diagnose the same method
3705 // more than once.
3706 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3707
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003708 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3709 MEnd = FinalOverriders.end();
3710 M != MEnd;
3711 ++M) {
3712 for (OverridingMethods::iterator SO = M->second.begin(),
3713 SOEnd = M->second.end();
3714 SO != SOEnd; ++SO) {
3715 // C++ [class.abstract]p4:
3716 // A class is abstract if it contains or inherits at least one
3717 // pure virtual function for which the final overrider is pure
3718 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003719
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003720 //
3721 if (SO->second.size() != 1)
3722 continue;
3723
3724 if (!SO->second.front().Method->isPure())
3725 continue;
3726
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003727 if (!SeenPureMethods.insert(SO->second.front().Method))
3728 continue;
3729
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003730 Diag(SO->second.front().Method->getLocation(),
3731 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003732 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003733 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003734 }
3735
3736 if (!PureVirtualClassDiagSet)
3737 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3738 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003739}
3740
Anders Carlsson8211eff2009-03-24 01:19:16 +00003741namespace {
John McCall94c3b562010-08-18 09:41:07 +00003742struct AbstractUsageInfo {
3743 Sema &S;
3744 CXXRecordDecl *Record;
3745 CanQualType AbstractType;
3746 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003747
John McCall94c3b562010-08-18 09:41:07 +00003748 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3749 : S(S), Record(Record),
3750 AbstractType(S.Context.getCanonicalType(
3751 S.Context.getTypeDeclType(Record))),
3752 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003753
John McCall94c3b562010-08-18 09:41:07 +00003754 void DiagnoseAbstractType() {
3755 if (Invalid) return;
3756 S.DiagnoseAbstractType(Record);
3757 Invalid = true;
3758 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003759
John McCall94c3b562010-08-18 09:41:07 +00003760 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3761};
3762
3763struct CheckAbstractUsage {
3764 AbstractUsageInfo &Info;
3765 const NamedDecl *Ctx;
3766
3767 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3768 : Info(Info), Ctx(Ctx) {}
3769
3770 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3771 switch (TL.getTypeLocClass()) {
3772#define ABSTRACT_TYPELOC(CLASS, PARENT)
3773#define TYPELOC(CLASS, PARENT) \
3774 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3775#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003776 }
John McCall94c3b562010-08-18 09:41:07 +00003777 }
Mike Stump1eb44332009-09-09 15:08:12 +00003778
John McCall94c3b562010-08-18 09:41:07 +00003779 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3780 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3781 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003782 if (!TL.getArg(I))
3783 continue;
3784
John McCall94c3b562010-08-18 09:41:07 +00003785 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3786 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003787 }
John McCall94c3b562010-08-18 09:41:07 +00003788 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003789
John McCall94c3b562010-08-18 09:41:07 +00003790 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3791 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3792 }
Mike Stump1eb44332009-09-09 15:08:12 +00003793
John McCall94c3b562010-08-18 09:41:07 +00003794 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3795 // Visit the type parameters from a permissive context.
3796 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3797 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3798 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3799 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3800 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3801 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003802 }
John McCall94c3b562010-08-18 09:41:07 +00003803 }
Mike Stump1eb44332009-09-09 15:08:12 +00003804
John McCall94c3b562010-08-18 09:41:07 +00003805 // Visit pointee types from a permissive context.
3806#define CheckPolymorphic(Type) \
3807 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3808 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3809 }
3810 CheckPolymorphic(PointerTypeLoc)
3811 CheckPolymorphic(ReferenceTypeLoc)
3812 CheckPolymorphic(MemberPointerTypeLoc)
3813 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003814 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003815
John McCall94c3b562010-08-18 09:41:07 +00003816 /// Handle all the types we haven't given a more specific
3817 /// implementation for above.
3818 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3819 // Every other kind of type that we haven't called out already
3820 // that has an inner type is either (1) sugar or (2) contains that
3821 // inner type in some way as a subobject.
3822 if (TypeLoc Next = TL.getNextTypeLoc())
3823 return Visit(Next, Sel);
3824
3825 // If there's no inner type and we're in a permissive context,
3826 // don't diagnose.
3827 if (Sel == Sema::AbstractNone) return;
3828
3829 // Check whether the type matches the abstract type.
3830 QualType T = TL.getType();
3831 if (T->isArrayType()) {
3832 Sel = Sema::AbstractArrayType;
3833 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003834 }
John McCall94c3b562010-08-18 09:41:07 +00003835 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3836 if (CT != Info.AbstractType) return;
3837
3838 // It matched; do some magic.
3839 if (Sel == Sema::AbstractArrayType) {
3840 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3841 << T << TL.getSourceRange();
3842 } else {
3843 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3844 << Sel << T << TL.getSourceRange();
3845 }
3846 Info.DiagnoseAbstractType();
3847 }
3848};
3849
3850void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3851 Sema::AbstractDiagSelID Sel) {
3852 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3853}
3854
3855}
3856
3857/// Check for invalid uses of an abstract type in a method declaration.
3858static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3859 CXXMethodDecl *MD) {
3860 // No need to do the check on definitions, which require that
3861 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003862 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003863 return;
3864
3865 // For safety's sake, just ignore it if we don't have type source
3866 // information. This should never happen for non-implicit methods,
3867 // but...
3868 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3869 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3870}
3871
3872/// Check for invalid uses of an abstract type within a class definition.
3873static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3874 CXXRecordDecl *RD) {
3875 for (CXXRecordDecl::decl_iterator
3876 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3877 Decl *D = *I;
3878 if (D->isImplicit()) continue;
3879
3880 // Methods and method templates.
3881 if (isa<CXXMethodDecl>(D)) {
3882 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3883 } else if (isa<FunctionTemplateDecl>(D)) {
3884 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3885 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3886
3887 // Fields and static variables.
3888 } else if (isa<FieldDecl>(D)) {
3889 FieldDecl *FD = cast<FieldDecl>(D);
3890 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3891 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3892 } else if (isa<VarDecl>(D)) {
3893 VarDecl *VD = cast<VarDecl>(D);
3894 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3895 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3896
3897 // Nested classes and class templates.
3898 } else if (isa<CXXRecordDecl>(D)) {
3899 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3900 } else if (isa<ClassTemplateDecl>(D)) {
3901 CheckAbstractClassUsage(Info,
3902 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3903 }
3904 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003905}
3906
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003907/// \brief Perform semantic checks on a class definition that has been
3908/// completing, introducing implicitly-declared members, checking for
3909/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003910void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003911 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003912 return;
3913
John McCall94c3b562010-08-18 09:41:07 +00003914 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3915 AbstractUsageInfo Info(*this, Record);
3916 CheckAbstractClassUsage(Info, Record);
3917 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003918
3919 // If this is not an aggregate type and has no user-declared constructor,
3920 // complain about any non-static data members of reference or const scalar
3921 // type, since they will never get initializers.
3922 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003923 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3924 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003925 bool Complained = false;
3926 for (RecordDecl::field_iterator F = Record->field_begin(),
3927 FEnd = Record->field_end();
3928 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003929 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003930 continue;
3931
Douglas Gregor325e5932010-04-15 00:00:53 +00003932 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003933 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003934 if (!Complained) {
3935 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3936 << Record->getTagKind() << Record;
3937 Complained = true;
3938 }
3939
3940 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3941 << F->getType()->isReferenceType()
3942 << F->getDeclName();
3943 }
3944 }
3945 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003946
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003947 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003948 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003949
3950 if (Record->getIdentifier()) {
3951 // C++ [class.mem]p13:
3952 // If T is the name of a class, then each of the following shall have a
3953 // name different from T:
3954 // - every member of every anonymous union that is a member of class T.
3955 //
3956 // C++ [class.mem]p14:
3957 // In addition, if class T has a user-declared constructor (12.1), every
3958 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00003959 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3960 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3961 ++I) {
3962 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00003963 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3964 isa<IndirectFieldDecl>(D)) {
3965 Diag(D->getLocation(), diag::err_member_name_of_class)
3966 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003967 break;
3968 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003969 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003970 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003971
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003972 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003973 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003974 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003975 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003976 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3977 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3978 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003979
David Blaikieb6b5b972012-09-21 03:21:07 +00003980 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3981 Diag(Record->getLocation(), diag::warn_abstract_final_class);
3982 DiagnoseAbstractType(Record);
3983 }
3984
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003985 if (!Record->isDependentType()) {
3986 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3987 MEnd = Record->method_end();
3988 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00003989 // See if a method overloads virtual methods in a base
3990 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00003991 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003992 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00003993
3994 // Check whether the explicitly-defaulted special members are valid.
3995 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
3996 CheckExplicitlyDefaultedSpecialMember(*M);
3997
3998 // For an explicitly defaulted or deleted special member, we defer
3999 // determining triviality until the class is complete. That time is now!
4000 if (!M->isImplicit() && !M->isUserProvided()) {
4001 CXXSpecialMember CSM = getSpecialMember(*M);
4002 if (CSM != CXXInvalid) {
4003 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4004
4005 // Inform the class that we've finished declaring this member.
4006 Record->finishedDefaultedOrDeletedMember(*M);
4007 }
4008 }
4009 }
4010 }
4011
4012 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4013 // function that is not a constructor declares that member function to be
4014 // const. [...] The class of which that function is a member shall be
4015 // a literal type.
4016 //
4017 // If the class has virtual bases, any constexpr members will already have
4018 // been diagnosed by the checks performed on the member declaration, so
4019 // suppress this (less useful) diagnostic.
4020 //
4021 // We delay this until we know whether an explicitly-defaulted (or deleted)
4022 // destructor for the class is trivial.
4023 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
4024 !Record->isLiteral() && !Record->getNumVBases()) {
4025 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4026 MEnd = Record->method_end();
4027 M != MEnd; ++M) {
4028 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4029 switch (Record->getTemplateSpecializationKind()) {
4030 case TSK_ImplicitInstantiation:
4031 case TSK_ExplicitInstantiationDeclaration:
4032 case TSK_ExplicitInstantiationDefinition:
4033 // If a template instantiates to a non-literal type, but its members
4034 // instantiate to constexpr functions, the template is technically
4035 // ill-formed, but we allow it for sanity.
4036 continue;
4037
4038 case TSK_Undeclared:
4039 case TSK_ExplicitSpecialization:
4040 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4041 diag::err_constexpr_method_non_literal);
4042 break;
4043 }
4044
4045 // Only produce one error per class.
4046 break;
4047 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004048 }
4049 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004050
4051 // Declare inherited constructors. We do this eagerly here because:
4052 // - The standard requires an eager diagnostic for conflicting inherited
4053 // constructors from different classes.
4054 // - The lazy declaration of the other implicit constructors is so as to not
4055 // waste space and performance on classes that are not meant to be
4056 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4057 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004058 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004059}
4060
Richard Smith7756afa2012-06-10 05:43:50 +00004061/// Is the special member function which would be selected to perform the
4062/// specified operation on the specified class type a constexpr constructor?
4063static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4064 Sema::CXXSpecialMember CSM,
4065 bool ConstArg) {
4066 Sema::SpecialMemberOverloadResult *SMOR =
4067 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4068 false, false, false, false);
4069 if (!SMOR || !SMOR->getMethod())
4070 // A constructor we wouldn't select can't be "involved in initializing"
4071 // anything.
4072 return true;
4073 return SMOR->getMethod()->isConstexpr();
4074}
4075
4076/// Determine whether the specified special member function would be constexpr
4077/// if it were implicitly defined.
4078static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4079 Sema::CXXSpecialMember CSM,
4080 bool ConstArg) {
4081 if (!S.getLangOpts().CPlusPlus0x)
4082 return false;
4083
4084 // C++11 [dcl.constexpr]p4:
4085 // In the definition of a constexpr constructor [...]
4086 switch (CSM) {
4087 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004088 // Since default constructor lookup is essentially trivial (and cannot
4089 // involve, for instance, template instantiation), we compute whether a
4090 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4091 //
4092 // This is important for performance; we need to know whether the default
4093 // constructor is constexpr to determine whether the type is a literal type.
4094 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4095
Richard Smith7756afa2012-06-10 05:43:50 +00004096 case Sema::CXXCopyConstructor:
4097 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004098 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004099 break;
4100
4101 case Sema::CXXCopyAssignment:
4102 case Sema::CXXMoveAssignment:
4103 case Sema::CXXDestructor:
4104 case Sema::CXXInvalid:
4105 return false;
4106 }
4107
4108 // -- if the class is a non-empty union, or for each non-empty anonymous
4109 // union member of a non-union class, exactly one non-static data member
4110 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004111 //
4112 // If we squint, this is guaranteed, since exactly one non-static data member
4113 // will be initialized (if the constructor isn't deleted), we just don't know
4114 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004115 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004116 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004117
4118 // -- the class shall not have any virtual base classes;
4119 if (ClassDecl->getNumVBases())
4120 return false;
4121
4122 // -- every constructor involved in initializing [...] base class
4123 // sub-objects shall be a constexpr constructor;
4124 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4125 BEnd = ClassDecl->bases_end();
4126 B != BEnd; ++B) {
4127 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4128 if (!BaseType) continue;
4129
4130 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4131 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4132 return false;
4133 }
4134
4135 // -- every constructor involved in initializing non-static data members
4136 // [...] shall be a constexpr constructor;
4137 // -- every non-static data member and base class sub-object shall be
4138 // initialized
4139 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4140 FEnd = ClassDecl->field_end();
4141 F != FEnd; ++F) {
4142 if (F->isInvalidDecl())
4143 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004144 if (const RecordType *RecordTy =
4145 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004146 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4147 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4148 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004149 }
4150 }
4151
4152 // All OK, it's constexpr!
4153 return true;
4154}
4155
Richard Smithb9d0b762012-07-27 04:22:15 +00004156static Sema::ImplicitExceptionSpecification
4157computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4158 switch (S.getSpecialMember(MD)) {
4159 case Sema::CXXDefaultConstructor:
4160 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4161 case Sema::CXXCopyConstructor:
4162 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4163 case Sema::CXXCopyAssignment:
4164 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4165 case Sema::CXXMoveConstructor:
4166 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4167 case Sema::CXXMoveAssignment:
4168 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4169 case Sema::CXXDestructor:
4170 return S.ComputeDefaultedDtorExceptionSpec(MD);
4171 case Sema::CXXInvalid:
4172 break;
4173 }
4174 llvm_unreachable("only special members have implicit exception specs");
4175}
4176
Richard Smithdd25e802012-07-30 23:48:14 +00004177static void
4178updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4179 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4180 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4181 ExceptSpec.getEPI(EPI);
4182 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4183 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4184 FPT->getNumArgs(), EPI));
4185 FD->setType(QualType(NewFPT, 0));
4186}
4187
Richard Smithb9d0b762012-07-27 04:22:15 +00004188void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4189 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4190 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4191 return;
4192
Richard Smithdd25e802012-07-30 23:48:14 +00004193 // Evaluate the exception specification.
4194 ImplicitExceptionSpecification ExceptSpec =
4195 computeImplicitExceptionSpec(*this, Loc, MD);
4196
4197 // Update the type of the special member to use it.
4198 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4199
4200 // A user-provided destructor can be defined outside the class. When that
4201 // happens, be sure to update the exception specification on both
4202 // declarations.
4203 const FunctionProtoType *CanonicalFPT =
4204 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4205 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4206 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4207 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004208}
4209
Richard Smith3003e1d2012-05-15 04:39:51 +00004210void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4211 CXXRecordDecl *RD = MD->getParent();
4212 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004213
Richard Smith3003e1d2012-05-15 04:39:51 +00004214 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4215 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004216
4217 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004218 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004219 bool First = MD == MD->getCanonicalDecl();
4220
4221 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004222
4223 // C++11 [dcl.fct.def.default]p1:
4224 // A function that is explicitly defaulted shall
4225 // -- be a special member function (checked elsewhere),
4226 // -- have the same type (except for ref-qualifiers, and except that a
4227 // copy operation can take a non-const reference) as an implicit
4228 // declaration, and
4229 // -- not have default arguments.
4230 unsigned ExpectedParams = 1;
4231 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4232 ExpectedParams = 0;
4233 if (MD->getNumParams() != ExpectedParams) {
4234 // This also checks for default arguments: a copy or move constructor with a
4235 // default argument is classified as a default constructor, and assignment
4236 // operations and destructors can't have default arguments.
4237 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4238 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004239 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004240 } else if (MD->isVariadic()) {
4241 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4242 << CSM << MD->getSourceRange();
4243 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004244 }
4245
Richard Smith3003e1d2012-05-15 04:39:51 +00004246 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004247
Richard Smith7756afa2012-06-10 05:43:50 +00004248 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004249 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004250 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004251 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004252 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004253
Richard Smith3003e1d2012-05-15 04:39:51 +00004254 QualType ReturnType = Context.VoidTy;
4255 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4256 // Check for return type matching.
4257 ReturnType = Type->getResultType();
4258 QualType ExpectedReturnType =
4259 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4260 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4261 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4262 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4263 HadError = true;
4264 }
4265
4266 // A defaulted special member cannot have cv-qualifiers.
4267 if (Type->getTypeQuals()) {
4268 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4269 << (CSM == CXXMoveAssignment);
4270 HadError = true;
4271 }
4272 }
4273
4274 // Check for parameter type matching.
4275 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004276 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004277 if (ExpectedParams && ArgType->isReferenceType()) {
4278 // Argument must be reference to possibly-const T.
4279 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004280 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004281
4282 if (ReferentType.isVolatileQualified()) {
4283 Diag(MD->getLocation(),
4284 diag::err_defaulted_special_member_volatile_param) << CSM;
4285 HadError = true;
4286 }
4287
Richard Smith7756afa2012-06-10 05:43:50 +00004288 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004289 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4290 Diag(MD->getLocation(),
4291 diag::err_defaulted_special_member_copy_const_param)
4292 << (CSM == CXXCopyAssignment);
4293 // FIXME: Explain why this special member can't be const.
4294 } else {
4295 Diag(MD->getLocation(),
4296 diag::err_defaulted_special_member_move_const_param)
4297 << (CSM == CXXMoveAssignment);
4298 }
4299 HadError = true;
4300 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004301 } else if (ExpectedParams) {
4302 // A copy assignment operator can take its argument by value, but a
4303 // defaulted one cannot.
4304 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004305 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004306 HadError = true;
4307 }
Sean Huntbe631222011-05-17 20:44:43 +00004308
Richard Smith61802452011-12-22 02:22:31 +00004309 // C++11 [dcl.fct.def.default]p2:
4310 // An explicitly-defaulted function may be declared constexpr only if it
4311 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004312 // Do not apply this rule to members of class templates, since core issue 1358
4313 // makes such functions always instantiate to constexpr functions. For
4314 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004315 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4316 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004317 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4318 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4319 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004320 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004321 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004322 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004323
Richard Smith61802452011-12-22 02:22:31 +00004324 // and may have an explicit exception-specification only if it is compatible
4325 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004326 if (Type->hasExceptionSpec()) {
4327 // Delay the check if this is the first declaration of the special member,
4328 // since we may not have parsed some necessary in-class initializers yet.
4329 if (First)
4330 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4331 else
4332 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4333 }
Richard Smith61802452011-12-22 02:22:31 +00004334
4335 // If a function is explicitly defaulted on its first declaration,
4336 if (First) {
4337 // -- it is implicitly considered to be constexpr if the implicit
4338 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004339 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004340
Richard Smith3003e1d2012-05-15 04:39:51 +00004341 // -- it is implicitly considered to have the same exception-specification
4342 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004343 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4344 EPI.ExceptionSpecType = EST_Unevaluated;
4345 EPI.ExceptionSpecDecl = MD;
4346 MD->setType(Context.getFunctionType(ReturnType, &ArgType,
4347 ExpectedParams, EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004348 }
4349
Richard Smith3003e1d2012-05-15 04:39:51 +00004350 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004351 if (First) {
4352 MD->setDeletedAsWritten();
4353 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004354 // C++11 [dcl.fct.def.default]p4:
4355 // [For a] user-provided explicitly-defaulted function [...] if such a
4356 // function is implicitly defined as deleted, the program is ill-formed.
4357 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4358 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004359 }
4360 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004361
Richard Smith3003e1d2012-05-15 04:39:51 +00004362 if (HadError)
4363 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004364}
4365
Richard Smith1d28caf2012-12-11 01:14:52 +00004366/// Check whether the exception specification provided for an
4367/// explicitly-defaulted special member matches the exception specification
4368/// that would have been generated for an implicit special member, per
4369/// C++11 [dcl.fct.def.default]p2.
4370void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4371 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4372 // Compute the implicit exception specification.
4373 FunctionProtoType::ExtProtoInfo EPI;
4374 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4375 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4376 Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4377
4378 // Ensure that it matches.
4379 CheckEquivalentExceptionSpec(
4380 PDiag(diag::err_incorrect_defaulted_exception_spec)
4381 << getSpecialMember(MD), PDiag(),
4382 ImplicitType, SourceLocation(),
4383 SpecifiedType, MD->getLocation());
4384}
4385
4386void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4387 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4388 I != N; ++I)
4389 CheckExplicitlyDefaultedMemberExceptionSpec(
4390 DelayedDefaultedMemberExceptionSpecs[I].first,
4391 DelayedDefaultedMemberExceptionSpecs[I].second);
4392
4393 DelayedDefaultedMemberExceptionSpecs.clear();
4394}
4395
Richard Smith7d5088a2012-02-18 02:02:13 +00004396namespace {
4397struct SpecialMemberDeletionInfo {
4398 Sema &S;
4399 CXXMethodDecl *MD;
4400 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004401 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004402
4403 // Properties of the special member, computed for convenience.
4404 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4405 SourceLocation Loc;
4406
4407 bool AllFieldsAreConst;
4408
4409 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004410 Sema::CXXSpecialMember CSM, bool Diagnose)
4411 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004412 IsConstructor(false), IsAssignment(false), IsMove(false),
4413 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4414 AllFieldsAreConst(true) {
4415 switch (CSM) {
4416 case Sema::CXXDefaultConstructor:
4417 case Sema::CXXCopyConstructor:
4418 IsConstructor = true;
4419 break;
4420 case Sema::CXXMoveConstructor:
4421 IsConstructor = true;
4422 IsMove = true;
4423 break;
4424 case Sema::CXXCopyAssignment:
4425 IsAssignment = true;
4426 break;
4427 case Sema::CXXMoveAssignment:
4428 IsAssignment = true;
4429 IsMove = true;
4430 break;
4431 case Sema::CXXDestructor:
4432 break;
4433 case Sema::CXXInvalid:
4434 llvm_unreachable("invalid special member kind");
4435 }
4436
4437 if (MD->getNumParams()) {
4438 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4439 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4440 }
4441 }
4442
4443 bool inUnion() const { return MD->getParent()->isUnion(); }
4444
4445 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004446 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4447 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004448 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004449 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4450 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4451 Quals = 0;
4452 return S.LookupSpecialMember(Class, CSM,
4453 ConstArg || (Quals & Qualifiers::Const),
4454 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004455 MD->getRefQualifier() == RQ_RValue,
4456 TQ & Qualifiers::Const,
4457 TQ & Qualifiers::Volatile);
4458 }
4459
Richard Smith6c4c36c2012-03-30 20:53:28 +00004460 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004461
Richard Smith6c4c36c2012-03-30 20:53:28 +00004462 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004463 bool shouldDeleteForField(FieldDecl *FD);
4464 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004465
Richard Smith517bb842012-07-18 03:51:16 +00004466 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4467 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004468 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4469 Sema::SpecialMemberOverloadResult *SMOR,
4470 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004471
4472 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004473};
4474}
4475
John McCall12d8d802012-04-09 20:53:23 +00004476/// Is the given special member inaccessible when used on the given
4477/// sub-object.
4478bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4479 CXXMethodDecl *target) {
4480 /// If we're operating on a base class, the object type is the
4481 /// type of this special member.
4482 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004483 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004484 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4485 objectTy = S.Context.getTypeDeclType(MD->getParent());
4486 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4487
4488 // If we're operating on a field, the object type is the type of the field.
4489 } else {
4490 objectTy = S.Context.getTypeDeclType(target->getParent());
4491 }
4492
4493 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4494}
4495
Richard Smith6c4c36c2012-03-30 20:53:28 +00004496/// Check whether we should delete a special member due to the implicit
4497/// definition containing a call to a special member of a subobject.
4498bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4499 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4500 bool IsDtorCallInCtor) {
4501 CXXMethodDecl *Decl = SMOR->getMethod();
4502 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4503
4504 int DiagKind = -1;
4505
4506 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4507 DiagKind = !Decl ? 0 : 1;
4508 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4509 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004510 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004511 DiagKind = 3;
4512 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4513 !Decl->isTrivial()) {
4514 // A member of a union must have a trivial corresponding special member.
4515 // As a weird special case, a destructor call from a union's constructor
4516 // must be accessible and non-deleted, but need not be trivial. Such a
4517 // destructor is never actually called, but is semantically checked as
4518 // if it were.
4519 DiagKind = 4;
4520 }
4521
4522 if (DiagKind == -1)
4523 return false;
4524
4525 if (Diagnose) {
4526 if (Field) {
4527 S.Diag(Field->getLocation(),
4528 diag::note_deleted_special_member_class_subobject)
4529 << CSM << MD->getParent() << /*IsField*/true
4530 << Field << DiagKind << IsDtorCallInCtor;
4531 } else {
4532 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4533 S.Diag(Base->getLocStart(),
4534 diag::note_deleted_special_member_class_subobject)
4535 << CSM << MD->getParent() << /*IsField*/false
4536 << Base->getType() << DiagKind << IsDtorCallInCtor;
4537 }
4538
4539 if (DiagKind == 1)
4540 S.NoteDeletedFunction(Decl);
4541 // FIXME: Explain inaccessibility if DiagKind == 3.
4542 }
4543
4544 return true;
4545}
4546
Richard Smith9a561d52012-02-26 09:11:52 +00004547/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004548/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004549bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004550 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004551 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004552
4553 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004554 // -- any direct or virtual base class, or non-static data member with no
4555 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004556 // either M has no default constructor or overload resolution as applied
4557 // to M's default constructor results in an ambiguity or in a function
4558 // that is deleted or inaccessible
4559 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4560 // -- a direct or virtual base class B that cannot be copied/moved because
4561 // overload resolution, as applied to B's corresponding special member,
4562 // results in an ambiguity or a function that is deleted or inaccessible
4563 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004564 // C++11 [class.dtor]p5:
4565 // -- any direct or virtual base class [...] has a type with a destructor
4566 // that is deleted or inaccessible
4567 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004568 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004569 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004570 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004571
Richard Smith6c4c36c2012-03-30 20:53:28 +00004572 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4573 // -- any direct or virtual base class or non-static data member has a
4574 // type with a destructor that is deleted or inaccessible
4575 if (IsConstructor) {
4576 Sema::SpecialMemberOverloadResult *SMOR =
4577 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4578 false, false, false, false, false);
4579 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4580 return true;
4581 }
4582
Richard Smith9a561d52012-02-26 09:11:52 +00004583 return false;
4584}
4585
4586/// Check whether we should delete a special member function due to the class
4587/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004588bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004589 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004590 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004591}
4592
4593/// Check whether we should delete a special member function due to the class
4594/// having a particular non-static data member.
4595bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4596 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4597 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4598
4599 if (CSM == Sema::CXXDefaultConstructor) {
4600 // For a default constructor, all references must be initialized in-class
4601 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004602 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4603 if (Diagnose)
4604 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4605 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004606 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004607 }
Richard Smith79363f52012-02-27 06:07:25 +00004608 // C++11 [class.ctor]p5: any non-variant non-static data member of
4609 // const-qualified type (or array thereof) with no
4610 // brace-or-equal-initializer does not have a user-provided default
4611 // constructor.
4612 if (!inUnion() && FieldType.isConstQualified() &&
4613 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004614 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4615 if (Diagnose)
4616 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004617 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004618 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004619 }
4620
4621 if (inUnion() && !FieldType.isConstQualified())
4622 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004623 } else if (CSM == Sema::CXXCopyConstructor) {
4624 // For a copy constructor, data members must not be of rvalue reference
4625 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004626 if (FieldType->isRValueReferenceType()) {
4627 if (Diagnose)
4628 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4629 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004630 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004631 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004632 } else if (IsAssignment) {
4633 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004634 if (FieldType->isReferenceType()) {
4635 if (Diagnose)
4636 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4637 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004638 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004639 }
4640 if (!FieldRecord && FieldType.isConstQualified()) {
4641 // C++11 [class.copy]p23:
4642 // -- a non-static data member of const non-class type (or array thereof)
4643 if (Diagnose)
4644 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004645 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004646 return true;
4647 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004648 }
4649
4650 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004651 // Some additional restrictions exist on the variant members.
4652 if (!inUnion() && FieldRecord->isUnion() &&
4653 FieldRecord->isAnonymousStructOrUnion()) {
4654 bool AllVariantFieldsAreConst = true;
4655
Richard Smithdf8dc862012-03-29 19:00:10 +00004656 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004657 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4658 UE = FieldRecord->field_end();
4659 UI != UE; ++UI) {
4660 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004661
4662 if (!UnionFieldType.isConstQualified())
4663 AllVariantFieldsAreConst = false;
4664
Richard Smith9a561d52012-02-26 09:11:52 +00004665 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4666 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004667 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4668 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004669 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004670 }
4671
4672 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004673 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004674 FieldRecord->field_begin() != FieldRecord->field_end()) {
4675 if (Diagnose)
4676 S.Diag(FieldRecord->getLocation(),
4677 diag::note_deleted_default_ctor_all_const)
4678 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004679 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004680 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004681
Richard Smithdf8dc862012-03-29 19:00:10 +00004682 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004683 // This is technically non-conformant, but sanity demands it.
4684 return false;
4685 }
4686
Richard Smith517bb842012-07-18 03:51:16 +00004687 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4688 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004689 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004690 }
4691
4692 return false;
4693}
4694
4695/// C++11 [class.ctor] p5:
4696/// A defaulted default constructor for a class X is defined as deleted if
4697/// X is a union and all of its variant members are of const-qualified type.
4698bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004699 // This is a silly definition, because it gives an empty union a deleted
4700 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004701 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4702 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4703 if (Diagnose)
4704 S.Diag(MD->getParent()->getLocation(),
4705 diag::note_deleted_default_ctor_all_const)
4706 << MD->getParent() << /*not anonymous union*/0;
4707 return true;
4708 }
4709 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004710}
4711
4712/// Determine whether a defaulted special member function should be defined as
4713/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4714/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004715bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4716 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004717 if (MD->isInvalidDecl())
4718 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004719 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004720 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004721 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004722 return false;
4723
Richard Smith7d5088a2012-02-18 02:02:13 +00004724 // C++11 [expr.lambda.prim]p19:
4725 // The closure type associated with a lambda-expression has a
4726 // deleted (8.4.3) default constructor and a deleted copy
4727 // assignment operator.
4728 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004729 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4730 if (Diagnose)
4731 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004732 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004733 }
4734
Richard Smith5bdaac52012-04-02 20:59:25 +00004735 // For an anonymous struct or union, the copy and assignment special members
4736 // will never be used, so skip the check. For an anonymous union declared at
4737 // namespace scope, the constructor and destructor are used.
4738 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4739 RD->isAnonymousStructOrUnion())
4740 return false;
4741
Richard Smith6c4c36c2012-03-30 20:53:28 +00004742 // C++11 [class.copy]p7, p18:
4743 // If the class definition declares a move constructor or move assignment
4744 // operator, an implicitly declared copy constructor or copy assignment
4745 // operator is defined as deleted.
4746 if (MD->isImplicit() &&
4747 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4748 CXXMethodDecl *UserDeclaredMove = 0;
4749
4750 // In Microsoft mode, a user-declared move only causes the deletion of the
4751 // corresponding copy operation, not both copy operations.
4752 if (RD->hasUserDeclaredMoveConstructor() &&
4753 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4754 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004755
4756 // Find any user-declared move constructor.
4757 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4758 E = RD->ctor_end(); I != E; ++I) {
4759 if (I->isMoveConstructor()) {
4760 UserDeclaredMove = *I;
4761 break;
4762 }
4763 }
Richard Smith1c931be2012-04-02 18:40:40 +00004764 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004765 } else if (RD->hasUserDeclaredMoveAssignment() &&
4766 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4767 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004768
4769 // Find any user-declared move assignment operator.
4770 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4771 E = RD->method_end(); I != E; ++I) {
4772 if (I->isMoveAssignmentOperator()) {
4773 UserDeclaredMove = *I;
4774 break;
4775 }
4776 }
Richard Smith1c931be2012-04-02 18:40:40 +00004777 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004778 }
4779
4780 if (UserDeclaredMove) {
4781 Diag(UserDeclaredMove->getLocation(),
4782 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004783 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004784 << UserDeclaredMove->isMoveAssignmentOperator();
4785 return true;
4786 }
4787 }
Sean Hunte16da072011-10-10 06:18:57 +00004788
Richard Smith5bdaac52012-04-02 20:59:25 +00004789 // Do access control from the special member function
4790 ContextRAII MethodContext(*this, MD);
4791
Richard Smith9a561d52012-02-26 09:11:52 +00004792 // C++11 [class.dtor]p5:
4793 // -- for a virtual destructor, lookup of the non-array deallocation function
4794 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004795 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004796 FunctionDecl *OperatorDelete = 0;
4797 DeclarationName Name =
4798 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4799 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004800 OperatorDelete, false)) {
4801 if (Diagnose)
4802 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004803 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004804 }
Richard Smith9a561d52012-02-26 09:11:52 +00004805 }
4806
Richard Smith6c4c36c2012-03-30 20:53:28 +00004807 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004808
Sean Huntcdee3fe2011-05-11 22:34:38 +00004809 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004810 BE = RD->bases_end(); BI != BE; ++BI)
4811 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004812 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004813 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004814
4815 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004816 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004817 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004818 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004819
4820 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004821 FE = RD->field_end(); FI != FE; ++FI)
4822 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004823 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004824 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004825
Richard Smith7d5088a2012-02-18 02:02:13 +00004826 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004827 return true;
4828
4829 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004830}
4831
Richard Smithac713512012-12-08 02:53:02 +00004832/// Perform lookup for a special member of the specified kind, and determine
4833/// whether it is trivial. If the triviality can be determined without the
4834/// lookup, skip it. This is intended for use when determining whether a
4835/// special member of a containing object is trivial, and thus does not ever
4836/// perform overload resolution for default constructors.
4837///
4838/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4839/// member that was most likely to be intended to be trivial, if any.
4840static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4841 Sema::CXXSpecialMember CSM, unsigned Quals,
4842 CXXMethodDecl **Selected) {
4843 if (Selected)
4844 *Selected = 0;
4845
4846 switch (CSM) {
4847 case Sema::CXXInvalid:
4848 llvm_unreachable("not a special member");
4849
4850 case Sema::CXXDefaultConstructor:
4851 // C++11 [class.ctor]p5:
4852 // A default constructor is trivial if:
4853 // - all the [direct subobjects] have trivial default constructors
4854 //
4855 // Note, no overload resolution is performed in this case.
4856 if (RD->hasTrivialDefaultConstructor())
4857 return true;
4858
4859 if (Selected) {
4860 // If there's a default constructor which could have been trivial, dig it
4861 // out. Otherwise, if there's any user-provided default constructor, point
4862 // to that as an example of why there's not a trivial one.
4863 CXXConstructorDecl *DefCtor = 0;
4864 if (RD->needsImplicitDefaultConstructor())
4865 S.DeclareImplicitDefaultConstructor(RD);
4866 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4867 CE = RD->ctor_end(); CI != CE; ++CI) {
4868 if (!CI->isDefaultConstructor())
4869 continue;
4870 DefCtor = *CI;
4871 if (!DefCtor->isUserProvided())
4872 break;
4873 }
4874
4875 *Selected = DefCtor;
4876 }
4877
4878 return false;
4879
4880 case Sema::CXXDestructor:
4881 // C++11 [class.dtor]p5:
4882 // A destructor is trivial if:
4883 // - all the direct [subobjects] have trivial destructors
4884 if (RD->hasTrivialDestructor())
4885 return true;
4886
4887 if (Selected) {
4888 if (RD->needsImplicitDestructor())
4889 S.DeclareImplicitDestructor(RD);
4890 *Selected = RD->getDestructor();
4891 }
4892
4893 return false;
4894
4895 case Sema::CXXCopyConstructor:
4896 // C++11 [class.copy]p12:
4897 // A copy constructor is trivial if:
4898 // - the constructor selected to copy each direct [subobject] is trivial
4899 if (RD->hasTrivialCopyConstructor()) {
4900 if (Quals == Qualifiers::Const)
4901 // We must either select the trivial copy constructor or reach an
4902 // ambiguity; no need to actually perform overload resolution.
4903 return true;
4904 } else if (!Selected) {
4905 return false;
4906 }
4907 // In C++98, we are not supposed to perform overload resolution here, but we
4908 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4909 // cases like B as having a non-trivial copy constructor:
4910 // struct A { template<typename T> A(T&); };
4911 // struct B { mutable A a; };
4912 goto NeedOverloadResolution;
4913
4914 case Sema::CXXCopyAssignment:
4915 // C++11 [class.copy]p25:
4916 // A copy assignment operator is trivial if:
4917 // - the assignment operator selected to copy each direct [subobject] is
4918 // trivial
4919 if (RD->hasTrivialCopyAssignment()) {
4920 if (Quals == Qualifiers::Const)
4921 return true;
4922 } else if (!Selected) {
4923 return false;
4924 }
4925 // In C++98, we are not supposed to perform overload resolution here, but we
4926 // treat that as a language defect.
4927 goto NeedOverloadResolution;
4928
4929 case Sema::CXXMoveConstructor:
4930 case Sema::CXXMoveAssignment:
4931 NeedOverloadResolution:
4932 Sema::SpecialMemberOverloadResult *SMOR =
4933 S.LookupSpecialMember(RD, CSM,
4934 Quals & Qualifiers::Const,
4935 Quals & Qualifiers::Volatile,
4936 /*RValueThis*/false, /*ConstThis*/false,
4937 /*VolatileThis*/false);
4938
4939 // The standard doesn't describe how to behave if the lookup is ambiguous.
4940 // We treat it as not making the member non-trivial, just like the standard
4941 // mandates for the default constructor. This should rarely matter, because
4942 // the member will also be deleted.
4943 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4944 return true;
4945
4946 if (!SMOR->getMethod()) {
4947 assert(SMOR->getKind() ==
4948 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4949 return false;
4950 }
4951
4952 // We deliberately don't check if we found a deleted special member. We're
4953 // not supposed to!
4954 if (Selected)
4955 *Selected = SMOR->getMethod();
4956 return SMOR->getMethod()->isTrivial();
4957 }
4958
4959 llvm_unreachable("unknown special method kind");
4960}
4961
4962CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
4963 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
4964 CI != CE; ++CI)
4965 if (!CI->isImplicit())
4966 return *CI;
4967
4968 // Look for constructor templates.
4969 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
4970 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
4971 if (CXXConstructorDecl *CD =
4972 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
4973 return CD;
4974 }
4975
4976 return 0;
4977}
4978
4979/// The kind of subobject we are checking for triviality. The values of this
4980/// enumeration are used in diagnostics.
4981enum TrivialSubobjectKind {
4982 /// The subobject is a base class.
4983 TSK_BaseClass,
4984 /// The subobject is a non-static data member.
4985 TSK_Field,
4986 /// The object is actually the complete object.
4987 TSK_CompleteObject
4988};
4989
4990/// Check whether the special member selected for a given type would be trivial.
4991static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
4992 QualType SubType,
4993 Sema::CXXSpecialMember CSM,
4994 TrivialSubobjectKind Kind,
4995 bool Diagnose) {
4996 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
4997 if (!SubRD)
4998 return true;
4999
5000 CXXMethodDecl *Selected;
5001 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5002 Diagnose ? &Selected : 0))
5003 return true;
5004
5005 if (Diagnose) {
5006 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5007 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5008 << Kind << SubType.getUnqualifiedType();
5009 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5010 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5011 } else if (!Selected)
5012 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5013 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5014 else if (Selected->isUserProvided()) {
5015 if (Kind == TSK_CompleteObject)
5016 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5017 << Kind << SubType.getUnqualifiedType() << CSM;
5018 else {
5019 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5020 << Kind << SubType.getUnqualifiedType() << CSM;
5021 S.Diag(Selected->getLocation(), diag::note_declared_at);
5022 }
5023 } else {
5024 if (Kind != TSK_CompleteObject)
5025 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5026 << Kind << SubType.getUnqualifiedType() << CSM;
5027
5028 // Explain why the defaulted or deleted special member isn't trivial.
5029 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5030 }
5031 }
5032
5033 return false;
5034}
5035
5036/// Check whether the members of a class type allow a special member to be
5037/// trivial.
5038static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5039 Sema::CXXSpecialMember CSM,
5040 bool ConstArg, bool Diagnose) {
5041 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5042 FE = RD->field_end(); FI != FE; ++FI) {
5043 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5044 continue;
5045
5046 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5047
5048 // Pretend anonymous struct or union members are members of this class.
5049 if (FI->isAnonymousStructOrUnion()) {
5050 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5051 CSM, ConstArg, Diagnose))
5052 return false;
5053 continue;
5054 }
5055
5056 // C++11 [class.ctor]p5:
5057 // A default constructor is trivial if [...]
5058 // -- no non-static data member of its class has a
5059 // brace-or-equal-initializer
5060 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5061 if (Diagnose)
5062 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5063 return false;
5064 }
5065
5066 // Objective C ARC 4.3.5:
5067 // [...] nontrivally ownership-qualified types are [...] not trivially
5068 // default constructible, copy constructible, move constructible, copy
5069 // assignable, move assignable, or destructible [...]
5070 if (S.getLangOpts().ObjCAutoRefCount &&
5071 FieldType.hasNonTrivialObjCLifetime()) {
5072 if (Diagnose)
5073 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5074 << RD << FieldType.getObjCLifetime();
5075 return false;
5076 }
5077
5078 if (ConstArg && !FI->isMutable())
5079 FieldType.addConst();
5080 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5081 TSK_Field, Diagnose))
5082 return false;
5083 }
5084
5085 return true;
5086}
5087
5088/// Diagnose why the specified class does not have a trivial special member of
5089/// the given kind.
5090void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5091 QualType Ty = Context.getRecordType(RD);
5092 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5093 Ty.addConst();
5094
5095 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5096 TSK_CompleteObject, /*Diagnose*/true);
5097}
5098
5099/// Determine whether a defaulted or deleted special member function is trivial,
5100/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5101/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5102bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5103 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005104 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5105
5106 CXXRecordDecl *RD = MD->getParent();
5107
5108 bool ConstArg = false;
5109 ParmVarDecl *Param0 = MD->getNumParams() ? MD->getParamDecl(0) : 0;
5110
5111 // C++11 [class.copy]p12, p25:
5112 // A [special member] is trivial if its declared parameter type is the same
5113 // as if it had been implicitly declared [...]
5114 switch (CSM) {
5115 case CXXDefaultConstructor:
5116 case CXXDestructor:
5117 // Trivial default constructors and destructors cannot have parameters.
5118 break;
5119
5120 case CXXCopyConstructor:
5121 case CXXCopyAssignment: {
5122 // Trivial copy operations always have const, non-volatile parameter types.
5123 ConstArg = true;
5124 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5125 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5126 if (Diagnose)
5127 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5128 << Param0->getSourceRange() << Param0->getType()
5129 << Context.getLValueReferenceType(
5130 Context.getRecordType(RD).withConst());
5131 return false;
5132 }
5133 break;
5134 }
5135
5136 case CXXMoveConstructor:
5137 case CXXMoveAssignment: {
5138 // Trivial move operations always have non-cv-qualified parameters.
5139 const RValueReferenceType *RT =
5140 Param0->getType()->getAs<RValueReferenceType>();
5141 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5142 if (Diagnose)
5143 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5144 << Param0->getSourceRange() << Param0->getType()
5145 << Context.getRValueReferenceType(Context.getRecordType(RD));
5146 return false;
5147 }
5148 break;
5149 }
5150
5151 case CXXInvalid:
5152 llvm_unreachable("not a special member");
5153 }
5154
5155 // FIXME: We require that the parameter-declaration-clause is equivalent to
5156 // that of an implicit declaration, not just that the declared parameter type
5157 // matches, in order to prevent absuridities like a function simultaneously
5158 // being a trivial copy constructor and a non-trivial default constructor.
5159 // This issue has not yet been assigned a core issue number.
5160 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5161 if (Diagnose)
5162 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5163 diag::note_nontrivial_default_arg)
5164 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5165 return false;
5166 }
5167 if (MD->isVariadic()) {
5168 if (Diagnose)
5169 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5170 return false;
5171 }
5172
5173 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5174 // A copy/move [constructor or assignment operator] is trivial if
5175 // -- the [member] selected to copy/move each direct base class subobject
5176 // is trivial
5177 //
5178 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5179 // A [default constructor or destructor] is trivial if
5180 // -- all the direct base classes have trivial [default constructors or
5181 // destructors]
5182 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5183 BE = RD->bases_end(); BI != BE; ++BI)
5184 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5185 ConstArg ? BI->getType().withConst()
5186 : BI->getType(),
5187 CSM, TSK_BaseClass, Diagnose))
5188 return false;
5189
5190 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5191 // A copy/move [constructor or assignment operator] for a class X is
5192 // trivial if
5193 // -- for each non-static data member of X that is of class type (or array
5194 // thereof), the constructor selected to copy/move that member is
5195 // trivial
5196 //
5197 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5198 // A [default constructor or destructor] is trivial if
5199 // -- for all of the non-static data members of its class that are of class
5200 // type (or array thereof), each such class has a trivial [default
5201 // constructor or destructor]
5202 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5203 return false;
5204
5205 // C++11 [class.dtor]p5:
5206 // A destructor is trivial if [...]
5207 // -- the destructor is not virtual
5208 if (CSM == CXXDestructor && MD->isVirtual()) {
5209 if (Diagnose)
5210 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5211 return false;
5212 }
5213
5214 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5215 // A [special member] for class X is trivial if [...]
5216 // -- class X has no virtual functions and no virtual base classes
5217 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5218 if (!Diagnose)
5219 return false;
5220
5221 if (RD->getNumVBases()) {
5222 // Check for virtual bases. We already know that the corresponding
5223 // member in all bases is trivial, so vbases must all be direct.
5224 CXXBaseSpecifier &BS = *RD->vbases_begin();
5225 assert(BS.isVirtual());
5226 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5227 return false;
5228 }
5229
5230 // Must have a virtual method.
5231 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5232 ME = RD->method_end(); MI != ME; ++MI) {
5233 if (MI->isVirtual()) {
5234 SourceLocation MLoc = MI->getLocStart();
5235 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5236 return false;
5237 }
5238 }
5239
5240 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5241 }
5242
5243 // Looks like it's trivial!
5244 return true;
5245}
5246
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005247/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005248namespace {
5249 struct FindHiddenVirtualMethodData {
5250 Sema *S;
5251 CXXMethodDecl *Method;
5252 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005253 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005254 };
5255}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005256
David Blaikie5f750682012-10-19 00:53:08 +00005257/// \brief Check whether any most overriden method from MD in Methods
5258static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5259 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5260 if (MD->size_overridden_methods() == 0)
5261 return Methods.count(MD->getCanonicalDecl());
5262 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5263 E = MD->end_overridden_methods();
5264 I != E; ++I)
5265 if (CheckMostOverridenMethods(*I, Methods))
5266 return true;
5267 return false;
5268}
5269
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005270/// \brief Member lookup function that determines whether a given C++
5271/// method overloads virtual methods in a base class without overriding any,
5272/// to be used with CXXRecordDecl::lookupInBases().
5273static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5274 CXXBasePath &Path,
5275 void *UserData) {
5276 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5277
5278 FindHiddenVirtualMethodData &Data
5279 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5280
5281 DeclarationName Name = Data.Method->getDeclName();
5282 assert(Name.getNameKind() == DeclarationName::Identifier);
5283
5284 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005285 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005286 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005287 !Path.Decls.empty();
5288 Path.Decls = Path.Decls.slice(1)) {
5289 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005290 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005291 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005292 foundSameNameMethod = true;
5293 // Interested only in hidden virtual methods.
5294 if (!MD->isVirtual())
5295 continue;
5296 // If the method we are checking overrides a method from its base
5297 // don't warn about the other overloaded methods.
5298 if (!Data.S->IsOverload(Data.Method, MD, false))
5299 return true;
5300 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005301 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005302 overloadedMethods.push_back(MD);
5303 }
5304 }
5305
5306 if (foundSameNameMethod)
5307 Data.OverloadedMethods.append(overloadedMethods.begin(),
5308 overloadedMethods.end());
5309 return foundSameNameMethod;
5310}
5311
David Blaikie5f750682012-10-19 00:53:08 +00005312/// \brief Add the most overriden methods from MD to Methods
5313static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5314 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5315 if (MD->size_overridden_methods() == 0)
5316 Methods.insert(MD->getCanonicalDecl());
5317 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5318 E = MD->end_overridden_methods();
5319 I != E; ++I)
5320 AddMostOverridenMethods(*I, Methods);
5321}
5322
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005323/// \brief See if a method overloads virtual methods in a base class without
5324/// overriding any.
5325void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5326 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005327 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005328 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005329 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005330 return;
5331
5332 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5333 /*bool RecordPaths=*/false,
5334 /*bool DetectVirtual=*/false);
5335 FindHiddenVirtualMethodData Data;
5336 Data.Method = MD;
5337 Data.S = this;
5338
5339 // Keep the base methods that were overriden or introduced in the subclass
5340 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005341 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5342 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5343 NamedDecl *ND = *I;
5344 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005345 ND = shad->getTargetDecl();
5346 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5347 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005348 }
5349
5350 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5351 !Data.OverloadedMethods.empty()) {
5352 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5353 << MD << (Data.OverloadedMethods.size() > 1);
5354
5355 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5356 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5357 Diag(overloadedMD->getLocation(),
5358 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5359 }
5360 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005361}
5362
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005363void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005364 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005365 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005366 SourceLocation RBrac,
5367 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005368 if (!TagDecl)
5369 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005370
Douglas Gregor42af25f2009-05-11 19:58:34 +00005371 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005372
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005373 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5374 if (l->getKind() != AttributeList::AT_Visibility)
5375 continue;
5376 l->setInvalid();
5377 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5378 l->getName();
5379 }
5380
David Blaikie77b6de02011-09-22 02:58:26 +00005381 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005382 // strict aliasing violation!
5383 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005384 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005385
Douglas Gregor23c94db2010-07-02 17:43:08 +00005386 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005387 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005388}
5389
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005390/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5391/// special functions, such as the default constructor, copy
5392/// constructor, or destructor, to the given C++ class (C++
5393/// [special]p1). This routine can only be executed just before the
5394/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005395void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005396 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005397 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005398
Richard Smithbc2a35d2012-12-08 08:32:28 +00005399 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005400 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005401
Richard Smithbc2a35d2012-12-08 08:32:28 +00005402 // If the properties or semantics of the copy constructor couldn't be
5403 // determined while the class was being declared, force a declaration
5404 // of it now.
5405 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5406 DeclareImplicitCopyConstructor(ClassDecl);
5407 }
5408
5409 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005410 ++ASTContext::NumImplicitMoveConstructors;
5411
Richard Smithbc2a35d2012-12-08 08:32:28 +00005412 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5413 DeclareImplicitMoveConstructor(ClassDecl);
5414 }
5415
Douglas Gregora376d102010-07-02 21:50:04 +00005416 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5417 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005418
5419 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005420 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005421 // it shows up in the right place in the vtable and that we diagnose
5422 // problems with the implicit exception specification.
5423 if (ClassDecl->isDynamicClass() ||
5424 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005425 DeclareImplicitCopyAssignment(ClassDecl);
5426 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005427
Richard Smith1c931be2012-04-02 18:40:40 +00005428 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005429 ++ASTContext::NumImplicitMoveAssignmentOperators;
5430
5431 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005432 if (ClassDecl->isDynamicClass() ||
5433 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005434 DeclareImplicitMoveAssignment(ClassDecl);
5435 }
5436
Douglas Gregor4923aa22010-07-02 20:37:36 +00005437 if (!ClassDecl->hasUserDeclaredDestructor()) {
5438 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005439
5440 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005441 // have to declare the destructor immediately. This ensures that, e.g., it
5442 // shows up in the right place in the vtable and that we diagnose problems
5443 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005444 if (ClassDecl->isDynamicClass() ||
5445 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005446 DeclareImplicitDestructor(ClassDecl);
5447 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005448}
5449
Francois Pichet8387e2a2011-04-22 22:18:13 +00005450void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5451 if (!D)
5452 return;
5453
5454 int NumParamList = D->getNumTemplateParameterLists();
5455 for (int i = 0; i < NumParamList; i++) {
5456 TemplateParameterList* Params = D->getTemplateParameterList(i);
5457 for (TemplateParameterList::iterator Param = Params->begin(),
5458 ParamEnd = Params->end();
5459 Param != ParamEnd; ++Param) {
5460 NamedDecl *Named = cast<NamedDecl>(*Param);
5461 if (Named->getDeclName()) {
5462 S->AddDecl(Named);
5463 IdResolver.AddDecl(Named);
5464 }
5465 }
5466 }
5467}
5468
John McCalld226f652010-08-21 09:40:31 +00005469void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005470 if (!D)
5471 return;
5472
5473 TemplateParameterList *Params = 0;
5474 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5475 Params = Template->getTemplateParameters();
5476 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5477 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5478 Params = PartialSpec->getTemplateParameters();
5479 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005480 return;
5481
Douglas Gregor6569d682009-05-27 23:11:45 +00005482 for (TemplateParameterList::iterator Param = Params->begin(),
5483 ParamEnd = Params->end();
5484 Param != ParamEnd; ++Param) {
5485 NamedDecl *Named = cast<NamedDecl>(*Param);
5486 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005487 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005488 IdResolver.AddDecl(Named);
5489 }
5490 }
5491}
5492
John McCalld226f652010-08-21 09:40:31 +00005493void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005494 if (!RecordD) return;
5495 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005496 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005497 PushDeclContext(S, Record);
5498}
5499
John McCalld226f652010-08-21 09:40:31 +00005500void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005501 if (!RecordD) return;
5502 PopDeclContext();
5503}
5504
Douglas Gregor72b505b2008-12-16 21:30:33 +00005505/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5506/// parsing a top-level (non-nested) C++ class, and we are now
5507/// parsing those parts of the given Method declaration that could
5508/// not be parsed earlier (C++ [class.mem]p2), such as default
5509/// arguments. This action should enter the scope of the given
5510/// Method declaration as if we had just parsed the qualified method
5511/// name. However, it should not bring the parameters into scope;
5512/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005513void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005514}
5515
5516/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5517/// C++ method declaration. We're (re-)introducing the given
5518/// function parameter into scope for use in parsing later parts of
5519/// the method declaration. For example, we could see an
5520/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005521void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005522 if (!ParamD)
5523 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005524
John McCalld226f652010-08-21 09:40:31 +00005525 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005526
5527 // If this parameter has an unparsed default argument, clear it out
5528 // to make way for the parsed default argument.
5529 if (Param->hasUnparsedDefaultArg())
5530 Param->setDefaultArg(0);
5531
John McCalld226f652010-08-21 09:40:31 +00005532 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005533 if (Param->getDeclName())
5534 IdResolver.AddDecl(Param);
5535}
5536
5537/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5538/// processing the delayed method declaration for Method. The method
5539/// declaration is now considered finished. There may be a separate
5540/// ActOnStartOfFunctionDef action later (not necessarily
5541/// immediately!) for this method, if it was also defined inside the
5542/// class body.
John McCalld226f652010-08-21 09:40:31 +00005543void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005544 if (!MethodD)
5545 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005546
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005547 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005548
John McCalld226f652010-08-21 09:40:31 +00005549 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005550
5551 // Now that we have our default arguments, check the constructor
5552 // again. It could produce additional diagnostics or affect whether
5553 // the class has implicitly-declared destructors, among other
5554 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005555 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5556 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005557
5558 // Check the default arguments, which we may have added.
5559 if (!Method->isInvalidDecl())
5560 CheckCXXDefaultArguments(Method);
5561}
5562
Douglas Gregor42a552f2008-11-05 20:51:48 +00005563/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005564/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005565/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005566/// emit diagnostics and set the invalid bit to true. In any case, the type
5567/// will be updated to reflect a well-formed type for the constructor and
5568/// returned.
5569QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005570 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005571 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005572
5573 // C++ [class.ctor]p3:
5574 // A constructor shall not be virtual (10.3) or static (9.4). A
5575 // constructor can be invoked for a const, volatile or const
5576 // volatile object. A constructor shall not be declared const,
5577 // volatile, or const volatile (9.3.2).
5578 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005579 if (!D.isInvalidType())
5580 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5581 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5582 << SourceRange(D.getIdentifierLoc());
5583 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005584 }
John McCalld931b082010-08-26 03:08:43 +00005585 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005586 if (!D.isInvalidType())
5587 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5588 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5589 << SourceRange(D.getIdentifierLoc());
5590 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005591 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005592 }
Mike Stump1eb44332009-09-09 15:08:12 +00005593
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005594 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005595 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005596 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005597 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5598 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005599 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005600 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5601 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005602 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005603 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5604 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005605 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005606 }
Mike Stump1eb44332009-09-09 15:08:12 +00005607
Douglas Gregorc938c162011-01-26 05:01:58 +00005608 // C++0x [class.ctor]p4:
5609 // A constructor shall not be declared with a ref-qualifier.
5610 if (FTI.hasRefQualifier()) {
5611 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5612 << FTI.RefQualifierIsLValueRef
5613 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5614 D.setInvalidType();
5615 }
5616
Douglas Gregor42a552f2008-11-05 20:51:48 +00005617 // Rebuild the function type "R" without any type qualifiers (in
5618 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005619 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005620 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005621 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5622 return R;
5623
5624 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5625 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005626 EPI.RefQualifier = RQ_None;
5627
Chris Lattner65401802009-04-25 08:28:21 +00005628 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005629 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005630}
5631
Douglas Gregor72b505b2008-12-16 21:30:33 +00005632/// CheckConstructor - Checks a fully-formed constructor for
5633/// well-formedness, issuing any diagnostics required. Returns true if
5634/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005635void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005636 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005637 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5638 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005639 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005640
5641 // C++ [class.copy]p3:
5642 // A declaration of a constructor for a class X is ill-formed if
5643 // its first parameter is of type (optionally cv-qualified) X and
5644 // either there are no other parameters or else all other
5645 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005646 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005647 ((Constructor->getNumParams() == 1) ||
5648 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005649 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5650 Constructor->getTemplateSpecializationKind()
5651 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005652 QualType ParamType = Constructor->getParamDecl(0)->getType();
5653 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5654 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005655 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005656 const char *ConstRef
5657 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5658 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005659 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005660 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005661
5662 // FIXME: Rather that making the constructor invalid, we should endeavor
5663 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005664 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005665 }
5666 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005667}
5668
John McCall15442822010-08-04 01:04:25 +00005669/// CheckDestructor - Checks a fully-formed destructor definition for
5670/// well-formedness, issuing any diagnostics required. Returns true
5671/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005672bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005673 CXXRecordDecl *RD = Destructor->getParent();
5674
5675 if (Destructor->isVirtual()) {
5676 SourceLocation Loc;
5677
5678 if (!Destructor->isImplicit())
5679 Loc = Destructor->getLocation();
5680 else
5681 Loc = RD->getLocation();
5682
5683 // If we have a virtual destructor, look up the deallocation function
5684 FunctionDecl *OperatorDelete = 0;
5685 DeclarationName Name =
5686 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005687 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005688 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005689
Eli Friedman5f2987c2012-02-02 03:46:19 +00005690 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005691
5692 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005693 }
Anders Carlsson37909802009-11-30 21:24:50 +00005694
5695 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005696}
5697
Mike Stump1eb44332009-09-09 15:08:12 +00005698static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005699FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5700 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5701 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005702 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005703}
5704
Douglas Gregor42a552f2008-11-05 20:51:48 +00005705/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5706/// the well-formednes of the destructor declarator @p D with type @p
5707/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005708/// emit diagnostics and set the declarator to invalid. Even if this happens,
5709/// will be updated to reflect a well-formed type for the destructor and
5710/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005711QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005712 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005713 // C++ [class.dtor]p1:
5714 // [...] A typedef-name that names a class is a class-name
5715 // (7.1.3); however, a typedef-name that names a class shall not
5716 // be used as the identifier in the declarator for a destructor
5717 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005718 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005719 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005720 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005721 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005722 else if (const TemplateSpecializationType *TST =
5723 DeclaratorType->getAs<TemplateSpecializationType>())
5724 if (TST->isTypeAlias())
5725 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5726 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005727
5728 // C++ [class.dtor]p2:
5729 // A destructor is used to destroy objects of its class type. A
5730 // destructor takes no parameters, and no return type can be
5731 // specified for it (not even void). The address of a destructor
5732 // shall not be taken. A destructor shall not be static. A
5733 // destructor can be invoked for a const, volatile or const
5734 // volatile object. A destructor shall not be declared const,
5735 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005736 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005737 if (!D.isInvalidType())
5738 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5739 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005740 << SourceRange(D.getIdentifierLoc())
5741 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5742
John McCalld931b082010-08-26 03:08:43 +00005743 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005744 }
Chris Lattner65401802009-04-25 08:28:21 +00005745 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005746 // Destructors don't have return types, but the parser will
5747 // happily parse something like:
5748 //
5749 // class X {
5750 // float ~X();
5751 // };
5752 //
5753 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005754 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5755 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5756 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005757 }
Mike Stump1eb44332009-09-09 15:08:12 +00005758
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005759 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005760 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005761 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005762 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5763 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005764 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005765 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5766 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005767 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005768 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5769 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005770 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005771 }
5772
Douglas Gregorc938c162011-01-26 05:01:58 +00005773 // C++0x [class.dtor]p2:
5774 // A destructor shall not be declared with a ref-qualifier.
5775 if (FTI.hasRefQualifier()) {
5776 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5777 << FTI.RefQualifierIsLValueRef
5778 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5779 D.setInvalidType();
5780 }
5781
Douglas Gregor42a552f2008-11-05 20:51:48 +00005782 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005783 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005784 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5785
5786 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005787 FTI.freeArgs();
5788 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005789 }
5790
Mike Stump1eb44332009-09-09 15:08:12 +00005791 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005792 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005793 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005794 D.setInvalidType();
5795 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005796
5797 // Rebuild the function type "R" without any type qualifiers or
5798 // parameters (in case any of the errors above fired) and with
5799 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005800 // types.
John McCalle23cf432010-12-14 08:05:40 +00005801 if (!D.isInvalidType())
5802 return R;
5803
Douglas Gregord92ec472010-07-01 05:10:53 +00005804 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005805 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5806 EPI.Variadic = false;
5807 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005808 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005809 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005810}
5811
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005812/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5813/// well-formednes of the conversion function declarator @p D with
5814/// type @p R. If there are any errors in the declarator, this routine
5815/// will emit diagnostics and return true. Otherwise, it will return
5816/// false. Either way, the type @p R will be updated to reflect a
5817/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005818void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005819 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005820 // C++ [class.conv.fct]p1:
5821 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005822 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005823 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005824 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005825 if (!D.isInvalidType())
5826 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5827 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5828 << SourceRange(D.getIdentifierLoc());
5829 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005830 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005831 }
John McCalla3f81372010-04-13 00:04:31 +00005832
5833 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5834
Chris Lattner6e475012009-04-25 08:35:12 +00005835 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005836 // Conversion functions don't have return types, but the parser will
5837 // happily parse something like:
5838 //
5839 // class X {
5840 // float operator bool();
5841 // };
5842 //
5843 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005844 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5845 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5846 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005847 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005848 }
5849
John McCalla3f81372010-04-13 00:04:31 +00005850 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5851
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005852 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005853 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005854 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5855
5856 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005857 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005858 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005859 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005860 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005861 D.setInvalidType();
5862 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005863
John McCalla3f81372010-04-13 00:04:31 +00005864 // Diagnose "&operator bool()" and other such nonsense. This
5865 // is actually a gcc extension which we don't support.
5866 if (Proto->getResultType() != ConvType) {
5867 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5868 << Proto->getResultType();
5869 D.setInvalidType();
5870 ConvType = Proto->getResultType();
5871 }
5872
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005873 // C++ [class.conv.fct]p4:
5874 // The conversion-type-id shall not represent a function type nor
5875 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005876 if (ConvType->isArrayType()) {
5877 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5878 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005879 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005880 } else if (ConvType->isFunctionType()) {
5881 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5882 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005883 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005884 }
5885
5886 // Rebuild the function type "R" without any parameters (in case any
5887 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005888 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005889 if (D.isInvalidType())
5890 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005891
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005892 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005893 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005894 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005895 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005896 diag::warn_cxx98_compat_explicit_conversion_functions :
5897 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005898 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005899}
5900
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005901/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5902/// the declaration of the given C++ conversion function. This routine
5903/// is responsible for recording the conversion function in the C++
5904/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005905Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005906 assert(Conversion && "Expected to receive a conversion function declaration");
5907
Douglas Gregor9d350972008-12-12 08:25:50 +00005908 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005909
5910 // Make sure we aren't redeclaring the conversion function.
5911 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005912
5913 // C++ [class.conv.fct]p1:
5914 // [...] A conversion function is never used to convert a
5915 // (possibly cv-qualified) object to the (possibly cv-qualified)
5916 // same object type (or a reference to it), to a (possibly
5917 // cv-qualified) base class of that type (or a reference to it),
5918 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005919 // FIXME: Suppress this warning if the conversion function ends up being a
5920 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005921 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005922 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005923 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005924 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005925 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5926 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005927 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005928 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005929 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5930 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005931 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005932 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005933 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005934 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005935 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005936 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005937 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005938 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005939 }
5940
Douglas Gregore80622f2010-09-29 04:25:11 +00005941 if (FunctionTemplateDecl *ConversionTemplate
5942 = Conversion->getDescribedFunctionTemplate())
5943 return ConversionTemplate;
5944
John McCalld226f652010-08-21 09:40:31 +00005945 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005946}
5947
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005948//===----------------------------------------------------------------------===//
5949// Namespace Handling
5950//===----------------------------------------------------------------------===//
5951
Richard Smithd1a55a62012-10-04 22:13:39 +00005952/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5953/// reopened.
5954static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5955 SourceLocation Loc,
5956 IdentifierInfo *II, bool *IsInline,
5957 NamespaceDecl *PrevNS) {
5958 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00005959
Richard Smithc969e6a2012-10-05 01:46:25 +00005960 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5961 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5962 // inline namespaces, with the intention of bringing names into namespace std.
5963 //
5964 // We support this just well enough to get that case working; this is not
5965 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00005966 if (*IsInline && II && II->getName().startswith("__atomic") &&
5967 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00005968 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00005969 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5970 NS = NS->getPreviousDecl())
5971 NS->setInline(*IsInline);
5972 // Patch up the lookup table for the containing namespace. This isn't really
5973 // correct, but it's good enough for this particular case.
5974 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5975 E = PrevNS->decls_end(); I != E; ++I)
5976 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5977 PrevNS->getParent()->makeDeclVisibleInContext(ND);
5978 return;
5979 }
5980
5981 if (PrevNS->isInline())
5982 // The user probably just forgot the 'inline', so suggest that it
5983 // be added back.
5984 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5985 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
5986 else
5987 S.Diag(Loc, diag::err_inline_namespace_mismatch)
5988 << IsInline;
5989
5990 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
5991 *IsInline = PrevNS->isInline();
5992}
John McCallea318642010-08-26 09:15:37 +00005993
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005994/// ActOnStartNamespaceDef - This is called at the start of a namespace
5995/// definition.
John McCalld226f652010-08-21 09:40:31 +00005996Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005997 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005998 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005999 SourceLocation IdentLoc,
6000 IdentifierInfo *II,
6001 SourceLocation LBrace,
6002 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006003 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6004 // For anonymous namespace, take the location of the left brace.
6005 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006006 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006007 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006008 bool IsStd = false;
6009 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006010 Scope *DeclRegionScope = NamespcScope->getParent();
6011
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006012 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006013 if (II) {
6014 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006015 // The identifier in an original-namespace-definition shall not
6016 // have been previously defined in the declarative region in
6017 // which the original-namespace-definition appears. The
6018 // identifier in an original-namespace-definition is the name of
6019 // the namespace. Subsequently in that declarative region, it is
6020 // treated as an original-namespace-name.
6021 //
6022 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006023 // look through using directives, just look for any ordinary names.
6024
6025 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006026 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6027 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006028 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006029 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6030 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6031 ++I) {
6032 if ((*I)->getIdentifierNamespace() & IDNS) {
6033 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006034 break;
6035 }
6036 }
6037
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006038 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6039
6040 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006041 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006042 if (IsInline != PrevNS->isInline())
6043 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6044 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006045 } else if (PrevDecl) {
6046 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006047 Diag(Loc, diag::err_redefinition_different_kind)
6048 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006049 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006050 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006051 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006052 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006053 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006054 // This is the first "real" definition of the namespace "std", so update
6055 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006056 PrevNS = getStdNamespace();
6057 IsStd = true;
6058 AddToKnown = !IsInline;
6059 } else {
6060 // We've seen this namespace for the first time.
6061 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006062 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006063 } else {
John McCall9aeed322009-10-01 00:25:31 +00006064 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006065
6066 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006067 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006068 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006069 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006070 } else {
6071 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006072 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006073 }
6074
Richard Smithd1a55a62012-10-04 22:13:39 +00006075 if (PrevNS && IsInline != PrevNS->isInline())
6076 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6077 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006078 }
6079
6080 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6081 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006082 if (IsInvalid)
6083 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006084
6085 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006086
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006087 // FIXME: Should we be merging attributes?
6088 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006089 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006090
6091 if (IsStd)
6092 StdNamespace = Namespc;
6093 if (AddToKnown)
6094 KnownNamespaces[Namespc] = false;
6095
6096 if (II) {
6097 PushOnScopeChains(Namespc, DeclRegionScope);
6098 } else {
6099 // Link the anonymous namespace into its parent.
6100 DeclContext *Parent = CurContext->getRedeclContext();
6101 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6102 TU->setAnonymousNamespace(Namespc);
6103 } else {
6104 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006105 }
John McCall9aeed322009-10-01 00:25:31 +00006106
Douglas Gregora4181472010-03-24 00:46:35 +00006107 CurContext->addDecl(Namespc);
6108
John McCall9aeed322009-10-01 00:25:31 +00006109 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6110 // behaves as if it were replaced by
6111 // namespace unique { /* empty body */ }
6112 // using namespace unique;
6113 // namespace unique { namespace-body }
6114 // where all occurrences of 'unique' in a translation unit are
6115 // replaced by the same identifier and this identifier differs
6116 // from all other identifiers in the entire program.
6117
6118 // We just create the namespace with an empty name and then add an
6119 // implicit using declaration, just like the standard suggests.
6120 //
6121 // CodeGen enforces the "universally unique" aspect by giving all
6122 // declarations semantically contained within an anonymous
6123 // namespace internal linkage.
6124
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006125 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006126 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006127 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006128 /* 'using' */ LBrace,
6129 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006130 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006131 /* identifier */ SourceLocation(),
6132 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006133 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006134 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006135 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006136 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006137 }
6138
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006139 ActOnDocumentableDecl(Namespc);
6140
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006141 // Although we could have an invalid decl (i.e. the namespace name is a
6142 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006143 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6144 // for the namespace has the declarations that showed up in that particular
6145 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006146 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006147 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006148}
6149
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006150/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6151/// is a namespace alias, returns the namespace it points to.
6152static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6153 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6154 return AD->getNamespace();
6155 return dyn_cast_or_null<NamespaceDecl>(D);
6156}
6157
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006158/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6159/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006160void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006161 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6162 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006163 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006164 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006165 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006166 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006167}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006168
John McCall384aff82010-08-25 07:42:41 +00006169CXXRecordDecl *Sema::getStdBadAlloc() const {
6170 return cast_or_null<CXXRecordDecl>(
6171 StdBadAlloc.get(Context.getExternalSource()));
6172}
6173
6174NamespaceDecl *Sema::getStdNamespace() const {
6175 return cast_or_null<NamespaceDecl>(
6176 StdNamespace.get(Context.getExternalSource()));
6177}
6178
Douglas Gregor66992202010-06-29 17:53:46 +00006179/// \brief Retrieve the special "std" namespace, which may require us to
6180/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006181NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006182 if (!StdNamespace) {
6183 // The "std" namespace has not yet been defined, so build one implicitly.
6184 StdNamespace = NamespaceDecl::Create(Context,
6185 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006186 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006187 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006188 &PP.getIdentifierTable().get("std"),
6189 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006190 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006191 }
6192
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006193 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006194}
6195
Sebastian Redl395e04d2012-01-17 22:49:33 +00006196bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006197 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006198 "Looking for std::initializer_list outside of C++.");
6199
6200 // We're looking for implicit instantiations of
6201 // template <typename E> class std::initializer_list.
6202
6203 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6204 return false;
6205
Sebastian Redl84760e32012-01-17 22:49:58 +00006206 ClassTemplateDecl *Template = 0;
6207 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006208
Sebastian Redl84760e32012-01-17 22:49:58 +00006209 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006210
Sebastian Redl84760e32012-01-17 22:49:58 +00006211 ClassTemplateSpecializationDecl *Specialization =
6212 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6213 if (!Specialization)
6214 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006215
Sebastian Redl84760e32012-01-17 22:49:58 +00006216 Template = Specialization->getSpecializedTemplate();
6217 Arguments = Specialization->getTemplateArgs().data();
6218 } else if (const TemplateSpecializationType *TST =
6219 Ty->getAs<TemplateSpecializationType>()) {
6220 Template = dyn_cast_or_null<ClassTemplateDecl>(
6221 TST->getTemplateName().getAsTemplateDecl());
6222 Arguments = TST->getArgs();
6223 }
6224 if (!Template)
6225 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006226
6227 if (!StdInitializerList) {
6228 // Haven't recognized std::initializer_list yet, maybe this is it.
6229 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6230 if (TemplateClass->getIdentifier() !=
6231 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006232 !getStdNamespace()->InEnclosingNamespaceSetOf(
6233 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006234 return false;
6235 // This is a template called std::initializer_list, but is it the right
6236 // template?
6237 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006238 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006239 return false;
6240 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6241 return false;
6242
6243 // It's the right template.
6244 StdInitializerList = Template;
6245 }
6246
6247 if (Template != StdInitializerList)
6248 return false;
6249
6250 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006251 if (Element)
6252 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006253 return true;
6254}
6255
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006256static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6257 NamespaceDecl *Std = S.getStdNamespace();
6258 if (!Std) {
6259 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6260 return 0;
6261 }
6262
6263 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6264 Loc, Sema::LookupOrdinaryName);
6265 if (!S.LookupQualifiedName(Result, Std)) {
6266 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6267 return 0;
6268 }
6269 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6270 if (!Template) {
6271 Result.suppressDiagnostics();
6272 // We found something weird. Complain about the first thing we found.
6273 NamedDecl *Found = *Result.begin();
6274 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6275 return 0;
6276 }
6277
6278 // We found some template called std::initializer_list. Now verify that it's
6279 // correct.
6280 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006281 if (Params->getMinRequiredArguments() != 1 ||
6282 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006283 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6284 return 0;
6285 }
6286
6287 return Template;
6288}
6289
6290QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6291 if (!StdInitializerList) {
6292 StdInitializerList = LookupStdInitializerList(*this, Loc);
6293 if (!StdInitializerList)
6294 return QualType();
6295 }
6296
6297 TemplateArgumentListInfo Args(Loc, Loc);
6298 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6299 Context.getTrivialTypeSourceInfo(Element,
6300 Loc)));
6301 return Context.getCanonicalType(
6302 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6303}
6304
Sebastian Redl98d36062012-01-17 22:50:14 +00006305bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6306 // C++ [dcl.init.list]p2:
6307 // A constructor is an initializer-list constructor if its first parameter
6308 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6309 // std::initializer_list<E> for some type E, and either there are no other
6310 // parameters or else all other parameters have default arguments.
6311 if (Ctor->getNumParams() < 1 ||
6312 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6313 return false;
6314
6315 QualType ArgType = Ctor->getParamDecl(0)->getType();
6316 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6317 ArgType = RT->getPointeeType().getUnqualifiedType();
6318
6319 return isStdInitializerList(ArgType, 0);
6320}
6321
Douglas Gregor9172aa62011-03-26 22:25:30 +00006322/// \brief Determine whether a using statement is in a context where it will be
6323/// apply in all contexts.
6324static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6325 switch (CurContext->getDeclKind()) {
6326 case Decl::TranslationUnit:
6327 return true;
6328 case Decl::LinkageSpec:
6329 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6330 default:
6331 return false;
6332 }
6333}
6334
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006335namespace {
6336
6337// Callback to only accept typo corrections that are namespaces.
6338class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6339 public:
6340 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6341 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6342 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6343 }
6344 return false;
6345 }
6346};
6347
6348}
6349
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006350static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6351 CXXScopeSpec &SS,
6352 SourceLocation IdentLoc,
6353 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006354 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006355 R.clear();
6356 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006357 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006358 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006359 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6360 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006361 if (DeclContext *DC = S.computeDeclContext(SS, false))
6362 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6363 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006364 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6365 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006366 else
6367 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6368 << Ident << CorrectedQuotedStr
6369 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006370
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006371 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6372 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006373
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006374 R.addDecl(Corrected.getCorrectionDecl());
6375 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006376 }
6377 return false;
6378}
6379
John McCalld226f652010-08-21 09:40:31 +00006380Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006381 SourceLocation UsingLoc,
6382 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006383 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006384 SourceLocation IdentLoc,
6385 IdentifierInfo *NamespcName,
6386 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006387 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6388 assert(NamespcName && "Invalid NamespcName.");
6389 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006390
6391 // This can only happen along a recovery path.
6392 while (S->getFlags() & Scope::TemplateParamScope)
6393 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006394 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006395
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006396 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006397 NestedNameSpecifier *Qualifier = 0;
6398 if (SS.isSet())
6399 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6400
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006401 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006402 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6403 LookupParsedName(R, S, &SS);
6404 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006405 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006406
Douglas Gregor66992202010-06-29 17:53:46 +00006407 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006408 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006409 // Allow "using namespace std;" or "using namespace ::std;" even if
6410 // "std" hasn't been defined yet, for GCC compatibility.
6411 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6412 NamespcName->isStr("std")) {
6413 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006414 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006415 R.resolveKind();
6416 }
6417 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006418 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006419 }
6420
John McCallf36e02d2009-10-09 21:13:30 +00006421 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006422 NamedDecl *Named = R.getFoundDecl();
6423 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6424 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006425 // C++ [namespace.udir]p1:
6426 // A using-directive specifies that the names in the nominated
6427 // namespace can be used in the scope in which the
6428 // using-directive appears after the using-directive. During
6429 // unqualified name lookup (3.4.1), the names appear as if they
6430 // were declared in the nearest enclosing namespace which
6431 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006432 // namespace. [Note: in this context, "contains" means "contains
6433 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006434
6435 // Find enclosing context containing both using-directive and
6436 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006437 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006438 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6439 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6440 CommonAncestor = CommonAncestor->getParent();
6441
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006442 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006443 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006444 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006445
Douglas Gregor9172aa62011-03-26 22:25:30 +00006446 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006447 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006448 Diag(IdentLoc, diag::warn_using_directive_in_header);
6449 }
6450
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006451 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006452 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006453 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006454 }
6455
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006456 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006457 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006458}
6459
6460void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006461 // If the scope has an associated entity and the using directive is at
6462 // namespace or translation unit scope, add the UsingDirectiveDecl into
6463 // its lookup structure so qualified name lookup can find it.
6464 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6465 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006466 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006467 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006468 // Otherwise, it is at block sope. The using-directives will affect lookup
6469 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006470 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006471}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006472
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006473
John McCalld226f652010-08-21 09:40:31 +00006474Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006475 AccessSpecifier AS,
6476 bool HasUsingKeyword,
6477 SourceLocation UsingLoc,
6478 CXXScopeSpec &SS,
6479 UnqualifiedId &Name,
6480 AttributeList *AttrList,
6481 bool IsTypeName,
6482 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006483 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006484
Douglas Gregor12c118a2009-11-04 16:30:06 +00006485 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006486 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006487 case UnqualifiedId::IK_Identifier:
6488 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006489 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006490 case UnqualifiedId::IK_ConversionFunctionId:
6491 break;
6492
6493 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006494 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006495 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006496 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006497 getLangOpts().CPlusPlus0x ?
Richard Smitha1366cb2012-04-27 19:33:05 +00006498 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6499 // instead once inheriting constructors work.
6500 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00006501 diag::err_using_decl_constructor)
6502 << SS.getRange();
6503
David Blaikie4e4d0842012-03-11 07:00:24 +00006504 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00006505
John McCalld226f652010-08-21 09:40:31 +00006506 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006507
6508 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006509 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006510 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006511 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006512
6513 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006514 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006515 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006516 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006517 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006518
6519 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6520 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006521 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006522 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006523
John McCall60fa3cf2009-12-11 02:10:03 +00006524 // Warn about using declarations.
6525 // TODO: store that the declaration was written without 'using' and
6526 // talk about access decls instead of using decls in the
6527 // diagnostics.
6528 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006529 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006530
6531 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006532 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006533 }
6534
Douglas Gregor56c04582010-12-16 00:46:58 +00006535 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6536 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6537 return 0;
6538
John McCall9488ea12009-11-17 05:59:44 +00006539 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006540 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006541 /* IsInstantiation */ false,
6542 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006543 if (UD)
6544 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006545
John McCalld226f652010-08-21 09:40:31 +00006546 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006547}
6548
Douglas Gregor09acc982010-07-07 23:08:52 +00006549/// \brief Determine whether a using declaration considers the given
6550/// declarations as "equivalent", e.g., if they are redeclarations of
6551/// the same entity or are both typedefs of the same type.
6552static bool
6553IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6554 bool &SuppressRedeclaration) {
6555 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6556 SuppressRedeclaration = false;
6557 return true;
6558 }
6559
Richard Smith162e1c12011-04-15 14:24:37 +00006560 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6561 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006562 SuppressRedeclaration = true;
6563 return Context.hasSameType(TD1->getUnderlyingType(),
6564 TD2->getUnderlyingType());
6565 }
6566
6567 return false;
6568}
6569
6570
John McCall9f54ad42009-12-10 09:41:52 +00006571/// Determines whether to create a using shadow decl for a particular
6572/// decl, given the set of decls existing prior to this using lookup.
6573bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6574 const LookupResult &Previous) {
6575 // Diagnose finding a decl which is not from a base class of the
6576 // current class. We do this now because there are cases where this
6577 // function will silently decide not to build a shadow decl, which
6578 // will pre-empt further diagnostics.
6579 //
6580 // We don't need to do this in C++0x because we do the check once on
6581 // the qualifier.
6582 //
6583 // FIXME: diagnose the following if we care enough:
6584 // struct A { int foo; };
6585 // struct B : A { using A::foo; };
6586 // template <class T> struct C : A {};
6587 // template <class T> struct D : C<T> { using B::foo; } // <---
6588 // This is invalid (during instantiation) in C++03 because B::foo
6589 // resolves to the using decl in B, which is not a base class of D<T>.
6590 // We can't diagnose it immediately because C<T> is an unknown
6591 // specialization. The UsingShadowDecl in D<T> then points directly
6592 // to A::foo, which will look well-formed when we instantiate.
6593 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00006594 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006595 DeclContext *OrigDC = Orig->getDeclContext();
6596
6597 // Handle enums and anonymous structs.
6598 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6599 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6600 while (OrigRec->isAnonymousStructOrUnion())
6601 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6602
6603 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6604 if (OrigDC == CurContext) {
6605 Diag(Using->getLocation(),
6606 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006607 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006608 Diag(Orig->getLocation(), diag::note_using_decl_target);
6609 return true;
6610 }
6611
Douglas Gregordc355712011-02-25 00:36:19 +00006612 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006613 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006614 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006615 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006616 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006617 Diag(Orig->getLocation(), diag::note_using_decl_target);
6618 return true;
6619 }
6620 }
6621
6622 if (Previous.empty()) return false;
6623
6624 NamedDecl *Target = Orig;
6625 if (isa<UsingShadowDecl>(Target))
6626 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6627
John McCalld7533ec2009-12-11 02:33:26 +00006628 // If the target happens to be one of the previous declarations, we
6629 // don't have a conflict.
6630 //
6631 // FIXME: but we might be increasing its access, in which case we
6632 // should redeclare it.
6633 NamedDecl *NonTag = 0, *Tag = 0;
6634 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6635 I != E; ++I) {
6636 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006637 bool Result;
6638 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6639 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006640
6641 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6642 }
6643
John McCall9f54ad42009-12-10 09:41:52 +00006644 if (Target->isFunctionOrFunctionTemplate()) {
6645 FunctionDecl *FD;
6646 if (isa<FunctionTemplateDecl>(Target))
6647 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6648 else
6649 FD = cast<FunctionDecl>(Target);
6650
6651 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006652 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006653 case Ovl_Overload:
6654 return false;
6655
6656 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006657 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006658 break;
6659
6660 // We found a decl with the exact signature.
6661 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006662 // If we're in a record, we want to hide the target, so we
6663 // return true (without a diagnostic) to tell the caller not to
6664 // build a shadow decl.
6665 if (CurContext->isRecord())
6666 return true;
6667
6668 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006669 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006670 break;
6671 }
6672
6673 Diag(Target->getLocation(), diag::note_using_decl_target);
6674 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6675 return true;
6676 }
6677
6678 // Target is not a function.
6679
John McCall9f54ad42009-12-10 09:41:52 +00006680 if (isa<TagDecl>(Target)) {
6681 // No conflict between a tag and a non-tag.
6682 if (!Tag) return false;
6683
John McCall41ce66f2009-12-10 19:51:03 +00006684 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006685 Diag(Target->getLocation(), diag::note_using_decl_target);
6686 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6687 return true;
6688 }
6689
6690 // No conflict between a tag and a non-tag.
6691 if (!NonTag) return false;
6692
John McCall41ce66f2009-12-10 19:51:03 +00006693 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006694 Diag(Target->getLocation(), diag::note_using_decl_target);
6695 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6696 return true;
6697}
6698
John McCall9488ea12009-11-17 05:59:44 +00006699/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006700UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006701 UsingDecl *UD,
6702 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006703
6704 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006705 NamedDecl *Target = Orig;
6706 if (isa<UsingShadowDecl>(Target)) {
6707 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6708 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006709 }
6710
6711 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006712 = UsingShadowDecl::Create(Context, CurContext,
6713 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006714 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006715
6716 Shadow->setAccess(UD->getAccess());
6717 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6718 Shadow->setInvalidDecl();
6719
John McCall9488ea12009-11-17 05:59:44 +00006720 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006721 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006722 else
John McCall604e7f12009-12-08 07:46:18 +00006723 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006724
John McCall604e7f12009-12-08 07:46:18 +00006725
John McCall9f54ad42009-12-10 09:41:52 +00006726 return Shadow;
6727}
John McCall604e7f12009-12-08 07:46:18 +00006728
John McCall9f54ad42009-12-10 09:41:52 +00006729/// Hides a using shadow declaration. This is required by the current
6730/// using-decl implementation when a resolvable using declaration in a
6731/// class is followed by a declaration which would hide or override
6732/// one or more of the using decl's targets; for example:
6733///
6734/// struct Base { void foo(int); };
6735/// struct Derived : Base {
6736/// using Base::foo;
6737/// void foo(int);
6738/// };
6739///
6740/// The governing language is C++03 [namespace.udecl]p12:
6741///
6742/// When a using-declaration brings names from a base class into a
6743/// derived class scope, member functions in the derived class
6744/// override and/or hide member functions with the same name and
6745/// parameter types in a base class (rather than conflicting).
6746///
6747/// There are two ways to implement this:
6748/// (1) optimistically create shadow decls when they're not hidden
6749/// by existing declarations, or
6750/// (2) don't create any shadow decls (or at least don't make them
6751/// visible) until we've fully parsed/instantiated the class.
6752/// The problem with (1) is that we might have to retroactively remove
6753/// a shadow decl, which requires several O(n) operations because the
6754/// decl structures are (very reasonably) not designed for removal.
6755/// (2) avoids this but is very fiddly and phase-dependent.
6756void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006757 if (Shadow->getDeclName().getNameKind() ==
6758 DeclarationName::CXXConversionFunctionName)
6759 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6760
John McCall9f54ad42009-12-10 09:41:52 +00006761 // Remove it from the DeclContext...
6762 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006763
John McCall9f54ad42009-12-10 09:41:52 +00006764 // ...and the scope, if applicable...
6765 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006766 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006767 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006768 }
6769
John McCall9f54ad42009-12-10 09:41:52 +00006770 // ...and the using decl.
6771 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6772
6773 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006774 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006775}
6776
John McCall7ba107a2009-11-18 02:36:19 +00006777/// Builds a using declaration.
6778///
6779/// \param IsInstantiation - Whether this call arises from an
6780/// instantiation of an unresolved using declaration. We treat
6781/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006782NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6783 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006784 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006785 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006786 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006787 bool IsInstantiation,
6788 bool IsTypeName,
6789 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006790 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006791 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006792 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006793
Anders Carlsson550b14b2009-08-28 05:49:21 +00006794 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006795
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006796 if (SS.isEmpty()) {
6797 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006798 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006799 }
Mike Stump1eb44332009-09-09 15:08:12 +00006800
John McCall9f54ad42009-12-10 09:41:52 +00006801 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006802 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006803 ForRedeclaration);
6804 Previous.setHideTags(false);
6805 if (S) {
6806 LookupName(Previous, S);
6807
6808 // It is really dumb that we have to do this.
6809 LookupResult::Filter F = Previous.makeFilter();
6810 while (F.hasNext()) {
6811 NamedDecl *D = F.next();
6812 if (!isDeclInScope(D, CurContext, S))
6813 F.erase();
6814 }
6815 F.done();
6816 } else {
6817 assert(IsInstantiation && "no scope in non-instantiation");
6818 assert(CurContext->isRecord() && "scope not record in instantiation");
6819 LookupQualifiedName(Previous, CurContext);
6820 }
6821
John McCall9f54ad42009-12-10 09:41:52 +00006822 // Check for invalid redeclarations.
6823 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6824 return 0;
6825
6826 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006827 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6828 return 0;
6829
John McCallaf8e6ed2009-11-12 03:15:40 +00006830 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006831 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006832 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006833 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006834 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006835 // FIXME: not all declaration name kinds are legal here
6836 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6837 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006838 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006839 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006840 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006841 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6842 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006843 }
John McCalled976492009-12-04 22:46:56 +00006844 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006845 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6846 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006847 }
John McCalled976492009-12-04 22:46:56 +00006848 D->setAccess(AS);
6849 CurContext->addDecl(D);
6850
6851 if (!LookupContext) return D;
6852 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006853
John McCall77bb1aa2010-05-01 00:40:08 +00006854 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006855 UD->setInvalidDecl();
6856 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006857 }
6858
Richard Smithc5a89a12012-04-02 01:30:27 +00006859 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006860 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006861 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006862 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006863 return UD;
6864 }
6865
6866 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006867
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006868 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006869
John McCall604e7f12009-12-08 07:46:18 +00006870 // Unlike most lookups, we don't always want to hide tag
6871 // declarations: tag names are visible through the using declaration
6872 // even if hidden by ordinary names, *except* in a dependent context
6873 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006874 if (!IsInstantiation)
6875 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006876
John McCallb9abd8722012-04-07 03:04:20 +00006877 // For the purposes of this lookup, we have a base object type
6878 // equal to that of the current context.
6879 if (CurContext->isRecord()) {
6880 R.setBaseObjectType(
6881 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6882 }
6883
John McCalla24dc2e2009-11-17 02:14:36 +00006884 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006885
John McCallf36e02d2009-10-09 21:13:30 +00006886 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006887 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006888 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006889 UD->setInvalidDecl();
6890 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006891 }
6892
John McCalled976492009-12-04 22:46:56 +00006893 if (R.isAmbiguous()) {
6894 UD->setInvalidDecl();
6895 return UD;
6896 }
Mike Stump1eb44332009-09-09 15:08:12 +00006897
John McCall7ba107a2009-11-18 02:36:19 +00006898 if (IsTypeName) {
6899 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006900 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006901 Diag(IdentLoc, diag::err_using_typename_non_type);
6902 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6903 Diag((*I)->getUnderlyingDecl()->getLocation(),
6904 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006905 UD->setInvalidDecl();
6906 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006907 }
6908 } else {
6909 // If we asked for a non-typename and we got a type, error out,
6910 // but only if this is an instantiation of an unresolved using
6911 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006912 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006913 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6914 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006915 UD->setInvalidDecl();
6916 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006917 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006918 }
6919
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006920 // C++0x N2914 [namespace.udecl]p6:
6921 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006922 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006923 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6924 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006925 UD->setInvalidDecl();
6926 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006927 }
Mike Stump1eb44332009-09-09 15:08:12 +00006928
John McCall9f54ad42009-12-10 09:41:52 +00006929 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6930 if (!CheckUsingShadowDecl(UD, *I, Previous))
6931 BuildUsingShadowDecl(S, UD, *I);
6932 }
John McCall9488ea12009-11-17 05:59:44 +00006933
6934 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006935}
6936
Sebastian Redlf677ea32011-02-05 19:23:19 +00006937/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006938bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6939 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006940
Douglas Gregordc355712011-02-25 00:36:19 +00006941 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006942 assert(SourceType &&
6943 "Using decl naming constructor doesn't have type in scope spec.");
6944 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6945
6946 // Check whether the named type is a direct base class.
6947 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6948 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6949 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6950 BaseIt != BaseE; ++BaseIt) {
6951 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6952 if (CanonicalSourceType == BaseType)
6953 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006954 if (BaseIt->getType()->isDependentType())
6955 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006956 }
6957
6958 if (BaseIt == BaseE) {
6959 // Did not find SourceType in the bases.
6960 Diag(UD->getUsingLocation(),
6961 diag::err_using_decl_constructor_not_in_direct_base)
6962 << UD->getNameInfo().getSourceRange()
6963 << QualType(SourceType, 0) << TargetClass;
6964 return true;
6965 }
6966
Richard Smithc5a89a12012-04-02 01:30:27 +00006967 if (!CurContext->isDependentContext())
6968 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006969
6970 return false;
6971}
6972
John McCall9f54ad42009-12-10 09:41:52 +00006973/// Checks that the given using declaration is not an invalid
6974/// redeclaration. Note that this is checking only for the using decl
6975/// itself, not for any ill-formedness among the UsingShadowDecls.
6976bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6977 bool isTypeName,
6978 const CXXScopeSpec &SS,
6979 SourceLocation NameLoc,
6980 const LookupResult &Prev) {
6981 // C++03 [namespace.udecl]p8:
6982 // C++0x [namespace.udecl]p10:
6983 // A using-declaration is a declaration and can therefore be used
6984 // repeatedly where (and only where) multiple declarations are
6985 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006986 //
John McCall8a726212010-11-29 18:01:58 +00006987 // That's in non-member contexts.
6988 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006989 return false;
6990
6991 NestedNameSpecifier *Qual
6992 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6993
6994 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6995 NamedDecl *D = *I;
6996
6997 bool DTypename;
6998 NestedNameSpecifier *DQual;
6999 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7000 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007001 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007002 } else if (UnresolvedUsingValueDecl *UD
7003 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7004 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007005 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007006 } else if (UnresolvedUsingTypenameDecl *UD
7007 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7008 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007009 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007010 } else continue;
7011
7012 // using decls differ if one says 'typename' and the other doesn't.
7013 // FIXME: non-dependent using decls?
7014 if (isTypeName != DTypename) continue;
7015
7016 // using decls differ if they name different scopes (but note that
7017 // template instantiation can cause this check to trigger when it
7018 // didn't before instantiation).
7019 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7020 Context.getCanonicalNestedNameSpecifier(DQual))
7021 continue;
7022
7023 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007024 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007025 return true;
7026 }
7027
7028 return false;
7029}
7030
John McCall604e7f12009-12-08 07:46:18 +00007031
John McCalled976492009-12-04 22:46:56 +00007032/// Checks that the given nested-name qualifier used in a using decl
7033/// in the current context is appropriately related to the current
7034/// scope. If an error is found, diagnoses it and returns true.
7035bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7036 const CXXScopeSpec &SS,
7037 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007038 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007039
John McCall604e7f12009-12-08 07:46:18 +00007040 if (!CurContext->isRecord()) {
7041 // C++03 [namespace.udecl]p3:
7042 // C++0x [namespace.udecl]p8:
7043 // A using-declaration for a class member shall be a member-declaration.
7044
7045 // If we weren't able to compute a valid scope, it must be a
7046 // dependent class scope.
7047 if (!NamedContext || NamedContext->isRecord()) {
7048 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7049 << SS.getRange();
7050 return true;
7051 }
7052
7053 // Otherwise, everything is known to be fine.
7054 return false;
7055 }
7056
7057 // The current scope is a record.
7058
7059 // If the named context is dependent, we can't decide much.
7060 if (!NamedContext) {
7061 // FIXME: in C++0x, we can diagnose if we can prove that the
7062 // nested-name-specifier does not refer to a base class, which is
7063 // still possible in some cases.
7064
7065 // Otherwise we have to conservatively report that things might be
7066 // okay.
7067 return false;
7068 }
7069
7070 if (!NamedContext->isRecord()) {
7071 // Ideally this would point at the last name in the specifier,
7072 // but we don't have that level of source info.
7073 Diag(SS.getRange().getBegin(),
7074 diag::err_using_decl_nested_name_specifier_is_not_class)
7075 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7076 return true;
7077 }
7078
Douglas Gregor6fb07292010-12-21 07:41:49 +00007079 if (!NamedContext->isDependentContext() &&
7080 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7081 return true;
7082
David Blaikie4e4d0842012-03-11 07:00:24 +00007083 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00007084 // C++0x [namespace.udecl]p3:
7085 // In a using-declaration used as a member-declaration, the
7086 // nested-name-specifier shall name a base class of the class
7087 // being defined.
7088
7089 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7090 cast<CXXRecordDecl>(NamedContext))) {
7091 if (CurContext == NamedContext) {
7092 Diag(NameLoc,
7093 diag::err_using_decl_nested_name_specifier_is_current_class)
7094 << SS.getRange();
7095 return true;
7096 }
7097
7098 Diag(SS.getRange().getBegin(),
7099 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7100 << (NestedNameSpecifier*) SS.getScopeRep()
7101 << cast<CXXRecordDecl>(CurContext)
7102 << SS.getRange();
7103 return true;
7104 }
7105
7106 return false;
7107 }
7108
7109 // C++03 [namespace.udecl]p4:
7110 // A using-declaration used as a member-declaration shall refer
7111 // to a member of a base class of the class being defined [etc.].
7112
7113 // Salient point: SS doesn't have to name a base class as long as
7114 // lookup only finds members from base classes. Therefore we can
7115 // diagnose here only if we can prove that that can't happen,
7116 // i.e. if the class hierarchies provably don't intersect.
7117
7118 // TODO: it would be nice if "definitely valid" results were cached
7119 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7120 // need to be repeated.
7121
7122 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007123 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007124
7125 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7126 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7127 Data->Bases.insert(Base);
7128 return true;
7129 }
7130
7131 bool hasDependentBases(const CXXRecordDecl *Class) {
7132 return !Class->forallBases(collect, this);
7133 }
7134
7135 /// Returns true if the base is dependent or is one of the
7136 /// accumulated base classes.
7137 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7138 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7139 return !Data->Bases.count(Base);
7140 }
7141
7142 bool mightShareBases(const CXXRecordDecl *Class) {
7143 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7144 }
7145 };
7146
7147 UserData Data;
7148
7149 // Returns false if we find a dependent base.
7150 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7151 return false;
7152
7153 // Returns false if the class has a dependent base or if it or one
7154 // of its bases is present in the base set of the current context.
7155 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7156 return false;
7157
7158 Diag(SS.getRange().getBegin(),
7159 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7160 << (NestedNameSpecifier*) SS.getScopeRep()
7161 << cast<CXXRecordDecl>(CurContext)
7162 << SS.getRange();
7163
7164 return true;
John McCalled976492009-12-04 22:46:56 +00007165}
7166
Richard Smith162e1c12011-04-15 14:24:37 +00007167Decl *Sema::ActOnAliasDeclaration(Scope *S,
7168 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007169 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007170 SourceLocation UsingLoc,
7171 UnqualifiedId &Name,
7172 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007173 // Skip up to the relevant declaration scope.
7174 while (S->getFlags() & Scope::TemplateParamScope)
7175 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007176 assert((S->getFlags() & Scope::DeclScope) &&
7177 "got alias-declaration outside of declaration scope");
7178
7179 if (Type.isInvalid())
7180 return 0;
7181
7182 bool Invalid = false;
7183 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7184 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007185 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007186
7187 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7188 return 0;
7189
7190 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007191 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007192 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007193 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7194 TInfo->getTypeLoc().getBeginLoc());
7195 }
Richard Smith162e1c12011-04-15 14:24:37 +00007196
7197 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7198 LookupName(Previous, S);
7199
7200 // Warn about shadowing the name of a template parameter.
7201 if (Previous.isSingleResult() &&
7202 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007203 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007204 Previous.clear();
7205 }
7206
7207 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7208 "name in alias declaration must be an identifier");
7209 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7210 Name.StartLocation,
7211 Name.Identifier, TInfo);
7212
7213 NewTD->setAccess(AS);
7214
7215 if (Invalid)
7216 NewTD->setInvalidDecl();
7217
Richard Smith3e4c6c42011-05-05 21:57:07 +00007218 CheckTypedefForVariablyModifiedType(S, NewTD);
7219 Invalid |= NewTD->isInvalidDecl();
7220
Richard Smith162e1c12011-04-15 14:24:37 +00007221 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007222
7223 NamedDecl *NewND;
7224 if (TemplateParamLists.size()) {
7225 TypeAliasTemplateDecl *OldDecl = 0;
7226 TemplateParameterList *OldTemplateParams = 0;
7227
7228 if (TemplateParamLists.size() != 1) {
7229 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007230 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7231 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007232 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007233 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007234
7235 // Only consider previous declarations in the same scope.
7236 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7237 /*ExplicitInstantiationOrSpecialization*/false);
7238 if (!Previous.empty()) {
7239 Redeclaration = true;
7240
7241 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7242 if (!OldDecl && !Invalid) {
7243 Diag(UsingLoc, diag::err_redefinition_different_kind)
7244 << Name.Identifier;
7245
7246 NamedDecl *OldD = Previous.getRepresentativeDecl();
7247 if (OldD->getLocation().isValid())
7248 Diag(OldD->getLocation(), diag::note_previous_definition);
7249
7250 Invalid = true;
7251 }
7252
7253 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7254 if (TemplateParameterListsAreEqual(TemplateParams,
7255 OldDecl->getTemplateParameters(),
7256 /*Complain=*/true,
7257 TPL_TemplateMatch))
7258 OldTemplateParams = OldDecl->getTemplateParameters();
7259 else
7260 Invalid = true;
7261
7262 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7263 if (!Invalid &&
7264 !Context.hasSameType(OldTD->getUnderlyingType(),
7265 NewTD->getUnderlyingType())) {
7266 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7267 // but we can't reasonably accept it.
7268 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7269 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7270 if (OldTD->getLocation().isValid())
7271 Diag(OldTD->getLocation(), diag::note_previous_definition);
7272 Invalid = true;
7273 }
7274 }
7275 }
7276
7277 // Merge any previous default template arguments into our parameters,
7278 // and check the parameter list.
7279 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7280 TPC_TypeAliasTemplate))
7281 return 0;
7282
7283 TypeAliasTemplateDecl *NewDecl =
7284 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7285 Name.Identifier, TemplateParams,
7286 NewTD);
7287
7288 NewDecl->setAccess(AS);
7289
7290 if (Invalid)
7291 NewDecl->setInvalidDecl();
7292 else if (OldDecl)
7293 NewDecl->setPreviousDeclaration(OldDecl);
7294
7295 NewND = NewDecl;
7296 } else {
7297 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7298 NewND = NewTD;
7299 }
Richard Smith162e1c12011-04-15 14:24:37 +00007300
7301 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007302 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007303
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007304 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007305 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007306}
7307
John McCalld226f652010-08-21 09:40:31 +00007308Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007309 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007310 SourceLocation AliasLoc,
7311 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007312 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007313 SourceLocation IdentLoc,
7314 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007315
Anders Carlsson81c85c42009-03-28 23:53:49 +00007316 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007317 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7318 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007319
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007320 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007321 NamedDecl *PrevDecl
7322 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7323 ForRedeclaration);
7324 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7325 PrevDecl = 0;
7326
7327 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007328 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007329 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007330 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007331 // FIXME: At some point, we'll want to create the (redundant)
7332 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007333 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007334 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007335 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007336 }
Mike Stump1eb44332009-09-09 15:08:12 +00007337
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007338 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7339 diag::err_redefinition_different_kind;
7340 Diag(AliasLoc, DiagID) << Alias;
7341 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007342 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007343 }
7344
John McCalla24dc2e2009-11-17 02:14:36 +00007345 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007346 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007347
John McCallf36e02d2009-10-09 21:13:30 +00007348 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007349 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007350 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007351 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007352 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007353 }
Mike Stump1eb44332009-09-09 15:08:12 +00007354
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007355 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007356 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007357 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007358 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007359
John McCall3dbd3d52010-02-16 06:53:13 +00007360 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007361 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007362}
7363
Sean Hunt001cad92011-05-10 00:49:42 +00007364Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007365Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7366 CXXMethodDecl *MD) {
7367 CXXRecordDecl *ClassDecl = MD->getParent();
7368
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007369 // C++ [except.spec]p14:
7370 // An implicitly declared special member function (Clause 12) shall have an
7371 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007372 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007373 if (ClassDecl->isInvalidDecl())
7374 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007375
Sebastian Redl60618fa2011-03-12 11:50:43 +00007376 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007377 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7378 BEnd = ClassDecl->bases_end();
7379 B != BEnd; ++B) {
7380 if (B->isVirtual()) // Handled below.
7381 continue;
7382
Douglas Gregor18274032010-07-03 00:47:00 +00007383 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7384 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007385 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7386 // If this is a deleted function, add it anyway. This might be conformant
7387 // with the standard. This might not. I'm not sure. It might not matter.
7388 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007389 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007390 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007391 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007392
7393 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007394 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7395 BEnd = ClassDecl->vbases_end();
7396 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007397 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7398 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007399 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7400 // If this is a deleted function, add it anyway. This might be conformant
7401 // with the standard. This might not. I'm not sure. It might not matter.
7402 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007403 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007404 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007405 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007406
7407 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007408 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7409 FEnd = ClassDecl->field_end();
7410 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007411 if (F->hasInClassInitializer()) {
7412 if (Expr *E = F->getInClassInitializer())
7413 ExceptSpec.CalledExpr(E);
7414 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007415 // DR1351:
7416 // If the brace-or-equal-initializer of a non-static data member
7417 // invokes a defaulted default constructor of its class or of an
7418 // enclosing class in a potentially evaluated subexpression, the
7419 // program is ill-formed.
7420 //
7421 // This resolution is unworkable: the exception specification of the
7422 // default constructor can be needed in an unevaluated context, in
7423 // particular, in the operand of a noexcept-expression, and we can be
7424 // unable to compute an exception specification for an enclosed class.
7425 //
7426 // We do not allow an in-class initializer to require the evaluation
7427 // of the exception specification for any in-class initializer whose
7428 // definition is not lexically complete.
7429 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007430 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007431 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007432 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7433 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7434 // If this is a deleted function, add it anyway. This might be conformant
7435 // with the standard. This might not. I'm not sure. It might not matter.
7436 // In particular, the problem is that this function never gets called. It
7437 // might just be ill-formed because this function attempts to refer to
7438 // a deleted function here.
7439 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007440 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007441 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007442 }
John McCalle23cf432010-12-14 08:05:40 +00007443
Sean Hunt001cad92011-05-10 00:49:42 +00007444 return ExceptSpec;
7445}
7446
Richard Smithafb49182012-11-29 01:34:07 +00007447namespace {
7448/// RAII object to register a special member as being currently declared.
7449struct DeclaringSpecialMember {
7450 Sema &S;
7451 Sema::SpecialMemberDecl D;
7452 bool WasAlreadyBeingDeclared;
7453
7454 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7455 : S(S), D(RD, CSM) {
7456 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7457 if (WasAlreadyBeingDeclared)
7458 // This almost never happens, but if it does, ensure that our cache
7459 // doesn't contain a stale result.
7460 S.SpecialMemberCache.clear();
7461
7462 // FIXME: Register a note to be produced if we encounter an error while
7463 // declaring the special member.
7464 }
7465 ~DeclaringSpecialMember() {
7466 if (!WasAlreadyBeingDeclared)
7467 S.SpecialMembersBeingDeclared.erase(D);
7468 }
7469
7470 /// \brief Are we already trying to declare this special member?
7471 bool isAlreadyBeingDeclared() const {
7472 return WasAlreadyBeingDeclared;
7473 }
7474};
7475}
7476
Sean Hunt001cad92011-05-10 00:49:42 +00007477CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7478 CXXRecordDecl *ClassDecl) {
7479 // C++ [class.ctor]p5:
7480 // A default constructor for a class X is a constructor of class X
7481 // that can be called without an argument. If there is no
7482 // user-declared constructor for class X, a default constructor is
7483 // implicitly declared. An implicitly-declared default constructor
7484 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007485 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007486 "Should not build implicit default constructor!");
7487
Richard Smithafb49182012-11-29 01:34:07 +00007488 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7489 if (DSM.isAlreadyBeingDeclared())
7490 return 0;
7491
Richard Smith7756afa2012-06-10 05:43:50 +00007492 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7493 CXXDefaultConstructor,
7494 false);
7495
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007496 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007497 CanQualType ClassType
7498 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007499 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007500 DeclarationName Name
7501 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007502 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007503 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007504 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007505 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007506 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007507 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007508 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007509 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007510
7511 // Build an exception specification pointing back at this constructor.
7512 FunctionProtoType::ExtProtoInfo EPI;
7513 EPI.ExceptionSpecType = EST_Unevaluated;
7514 EPI.ExceptionSpecDecl = DefaultCon;
7515 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7516
Richard Smithbc2a35d2012-12-08 08:32:28 +00007517 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7518 // constructors is easy to compute.
7519 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7520
7521 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7522 DefaultCon->setDeletedAsWritten();
7523
Douglas Gregor18274032010-07-03 00:47:00 +00007524 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007525 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007526
Douglas Gregor23c94db2010-07-02 17:43:08 +00007527 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007528 PushOnScopeChains(DefaultCon, S, false);
7529 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007530
Douglas Gregor32df23e2010-07-01 22:02:46 +00007531 return DefaultCon;
7532}
7533
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007534void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7535 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007536 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007537 !Constructor->doesThisDeclarationHaveABody() &&
7538 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007539 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007540
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007541 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007542 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007543
Eli Friedman9a14db32012-10-18 20:14:08 +00007544 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007545 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007546 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007547 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007548 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007549 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007550 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007551 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007552 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007553
7554 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007555 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007556
7557 Constructor->setUsed();
7558 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007559
7560 if (ASTMutationListener *L = getASTMutationListener()) {
7561 L->CompletedImplicitDefinition(Constructor);
7562 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007563}
7564
Richard Smith7a614d82011-06-11 17:19:42 +00007565void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007566 // Check that any explicitly-defaulted methods have exception specifications
7567 // compatible with their implicit exception specifications.
7568 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007569}
7570
Sebastian Redlf677ea32011-02-05 19:23:19 +00007571void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7572 // We start with an initial pass over the base classes to collect those that
7573 // inherit constructors from. If there are none, we can forgo all further
7574 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007575 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007576 BasesVector BasesToInheritFrom;
7577 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7578 BaseE = ClassDecl->bases_end();
7579 BaseIt != BaseE; ++BaseIt) {
7580 if (BaseIt->getInheritConstructors()) {
7581 QualType Base = BaseIt->getType();
7582 if (Base->isDependentType()) {
7583 // If we inherit constructors from anything that is dependent, just
7584 // abort processing altogether. We'll get another chance for the
7585 // instantiations.
7586 return;
7587 }
7588 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7589 }
7590 }
7591 if (BasesToInheritFrom.empty())
7592 return;
7593
7594 // Now collect the constructors that we already have in the current class.
7595 // Those take precedence over inherited constructors.
7596 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7597 // unless there is a user-declared constructor with the same signature in
7598 // the class where the using-declaration appears.
7599 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7600 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7601 CtorE = ClassDecl->ctor_end();
7602 CtorIt != CtorE; ++CtorIt) {
7603 ExistingConstructors.insert(
7604 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7605 }
7606
Sebastian Redlf677ea32011-02-05 19:23:19 +00007607 DeclarationName CreatedCtorName =
7608 Context.DeclarationNames.getCXXConstructorName(
7609 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7610
7611 // Now comes the true work.
7612 // First, we keep a map from constructor types to the base that introduced
7613 // them. Needed for finding conflicting constructors. We also keep the
7614 // actually inserted declarations in there, for pretty diagnostics.
7615 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7616 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7617 ConstructorToSourceMap InheritedConstructors;
7618 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7619 BaseE = BasesToInheritFrom.end();
7620 BaseIt != BaseE; ++BaseIt) {
7621 const RecordType *Base = *BaseIt;
7622 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7623 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7624 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7625 CtorE = BaseDecl->ctor_end();
7626 CtorIt != CtorE; ++CtorIt) {
7627 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007628 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007629 DeclarationName Name =
7630 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007631 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7632 LookupQualifiedName(Result, CurContext);
7633 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007634 SourceLocation UsingLoc = UD ? UD->getLocation() :
7635 ClassDecl->getLocation();
7636
7637 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7638 // from the class X named in the using-declaration consists of actual
7639 // constructors and notional constructors that result from the
7640 // transformation of defaulted parameters as follows:
7641 // - all non-template default constructors of X, and
7642 // - for each non-template constructor of X that has at least one
7643 // parameter with a default argument, the set of constructors that
7644 // results from omitting any ellipsis parameter specification and
7645 // successively omitting parameters with a default argument from the
7646 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00007647 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007648 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7649 const FunctionProtoType *BaseCtorType =
7650 BaseCtor->getType()->getAs<FunctionProtoType>();
7651
7652 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7653 maxParams = BaseCtor->getNumParams();
7654 params <= maxParams; ++params) {
7655 // Skip default constructors. They're never inherited.
7656 if (params == 0)
7657 continue;
7658 // Skip copy and move constructors for the same reason.
7659 if (CanBeCopyOrMove && params == 1)
7660 continue;
7661
7662 // Build up a function type for this particular constructor.
7663 // FIXME: The working paper does not consider that the exception spec
7664 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007665 // source. This code doesn't yet, either. When it does, this code will
7666 // need to be delayed until after exception specifications and in-class
7667 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007668 const Type *NewCtorType;
7669 if (params == maxParams)
7670 NewCtorType = BaseCtorType;
7671 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007672 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007673 for (unsigned i = 0; i < params; ++i) {
7674 Args.push_back(BaseCtorType->getArgType(i));
7675 }
7676 FunctionProtoType::ExtProtoInfo ExtInfo =
7677 BaseCtorType->getExtProtoInfo();
7678 ExtInfo.Variadic = false;
7679 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7680 Args.data(), params, ExtInfo)
7681 .getTypePtr();
7682 }
7683 const Type *CanonicalNewCtorType =
7684 Context.getCanonicalType(NewCtorType);
7685
7686 // Now that we have the type, first check if the class already has a
7687 // constructor with this signature.
7688 if (ExistingConstructors.count(CanonicalNewCtorType))
7689 continue;
7690
7691 // Then we check if we have already declared an inherited constructor
7692 // with this signature.
7693 std::pair<ConstructorToSourceMap::iterator, bool> result =
7694 InheritedConstructors.insert(std::make_pair(
7695 CanonicalNewCtorType,
7696 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7697 if (!result.second) {
7698 // Already in the map. If it came from a different class, that's an
7699 // error. Not if it's from the same.
7700 CanQualType PreviousBase = result.first->second.first;
7701 if (CanonicalBase != PreviousBase) {
7702 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7703 const CXXConstructorDecl *PrevBaseCtor =
7704 PrevCtor->getInheritedConstructor();
7705 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7706
7707 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7708 Diag(BaseCtor->getLocation(),
7709 diag::note_using_decl_constructor_conflict_current_ctor);
7710 Diag(PrevBaseCtor->getLocation(),
7711 diag::note_using_decl_constructor_conflict_previous_ctor);
7712 Diag(PrevCtor->getLocation(),
7713 diag::note_using_decl_constructor_conflict_previous_using);
7714 }
7715 continue;
7716 }
7717
7718 // OK, we're there, now add the constructor.
7719 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007720 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007721 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7722 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007723 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7724 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007725 /*ImplicitlyDeclared=*/true,
7726 // FIXME: Due to a defect in the standard, we treat inherited
7727 // constructors as constexpr even if that makes them ill-formed.
7728 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007729 NewCtor->setAccess(BaseCtor->getAccess());
7730
7731 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007732 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007733 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007734 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7735 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007736 /*IdentifierInfo=*/0,
7737 BaseCtorType->getArgType(i),
7738 /*TInfo=*/0, SC_None,
7739 SC_None, /*DefaultArg=*/0));
7740 }
David Blaikie4278c652011-09-21 18:16:56 +00007741 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007742 NewCtor->setInheritedConstructor(BaseCtor);
7743
Sebastian Redlf677ea32011-02-05 19:23:19 +00007744 ClassDecl->addDecl(NewCtor);
7745 result.first->second.second = NewCtor;
7746 }
7747 }
7748 }
7749}
7750
Sean Huntcb45a0f2011-05-12 22:46:25 +00007751Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007752Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7753 CXXRecordDecl *ClassDecl = MD->getParent();
7754
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007755 // C++ [except.spec]p14:
7756 // An implicitly declared special member function (Clause 12) shall have
7757 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007758 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007759 if (ClassDecl->isInvalidDecl())
7760 return ExceptSpec;
7761
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007762 // Direct base-class destructors.
7763 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7764 BEnd = ClassDecl->bases_end();
7765 B != BEnd; ++B) {
7766 if (B->isVirtual()) // Handled below.
7767 continue;
7768
7769 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007770 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007771 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007772 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007773
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007774 // Virtual base-class destructors.
7775 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7776 BEnd = ClassDecl->vbases_end();
7777 B != BEnd; ++B) {
7778 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007779 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007780 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007781 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007782
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007783 // Field destructors.
7784 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7785 FEnd = ClassDecl->field_end();
7786 F != FEnd; ++F) {
7787 if (const RecordType *RecordTy
7788 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007789 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007790 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007791 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007792
Sean Huntcb45a0f2011-05-12 22:46:25 +00007793 return ExceptSpec;
7794}
7795
7796CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7797 // C++ [class.dtor]p2:
7798 // If a class has no user-declared destructor, a destructor is
7799 // declared implicitly. An implicitly-declared destructor is an
7800 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007801 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007802
Richard Smithafb49182012-11-29 01:34:07 +00007803 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7804 if (DSM.isAlreadyBeingDeclared())
7805 return 0;
7806
Douglas Gregor4923aa22010-07-02 20:37:36 +00007807 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007808 CanQualType ClassType
7809 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007810 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007811 DeclarationName Name
7812 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007813 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007814 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007815 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7816 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007817 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007818 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007819 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007820 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007821
7822 // Build an exception specification pointing back at this destructor.
7823 FunctionProtoType::ExtProtoInfo EPI;
7824 EPI.ExceptionSpecType = EST_Unevaluated;
7825 EPI.ExceptionSpecDecl = Destructor;
7826 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7827
Richard Smithbc2a35d2012-12-08 08:32:28 +00007828 AddOverriddenMethods(ClassDecl, Destructor);
7829
7830 // We don't need to use SpecialMemberIsTrivial here; triviality for
7831 // destructors is easy to compute.
7832 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7833
7834 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7835 Destructor->setDeletedAsWritten();
7836
Douglas Gregor4923aa22010-07-02 20:37:36 +00007837 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007838 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007839
Douglas Gregor4923aa22010-07-02 20:37:36 +00007840 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007841 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007842 PushOnScopeChains(Destructor, S, false);
7843 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007844
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007845 return Destructor;
7846}
7847
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007848void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007849 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007850 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007851 !Destructor->doesThisDeclarationHaveABody() &&
7852 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007853 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007854 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007855 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007856
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007857 if (Destructor->isInvalidDecl())
7858 return;
7859
Eli Friedman9a14db32012-10-18 20:14:08 +00007860 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007861
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007862 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007863 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7864 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007865
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007866 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007867 Diag(CurrentLocation, diag::note_member_synthesized_at)
7868 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7869
7870 Destructor->setInvalidDecl();
7871 return;
7872 }
7873
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007874 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007875 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007876 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007877 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007878 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007879
7880 if (ASTMutationListener *L = getASTMutationListener()) {
7881 L->CompletedImplicitDefinition(Destructor);
7882 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007883}
7884
Richard Smitha4156b82012-04-21 18:42:51 +00007885/// \brief Perform any semantic analysis which needs to be delayed until all
7886/// pending class member declarations have been parsed.
7887void Sema::ActOnFinishCXXMemberDecls() {
Richard Smitha4156b82012-04-21 18:42:51 +00007888 // Perform any deferred checking of exception specifications for virtual
7889 // destructors.
7890 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7891 i != e; ++i) {
7892 const CXXDestructorDecl *Dtor =
7893 DelayedDestructorExceptionSpecChecks[i].first;
7894 assert(!Dtor->getParent()->isDependentType() &&
7895 "Should not ever add destructors of templates into the list.");
7896 CheckOverridingFunctionExceptionSpec(Dtor,
7897 DelayedDestructorExceptionSpecChecks[i].second);
7898 }
7899 DelayedDestructorExceptionSpecChecks.clear();
7900}
7901
Richard Smithb9d0b762012-07-27 04:22:15 +00007902void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7903 CXXDestructorDecl *Destructor) {
7904 assert(getLangOpts().CPlusPlus0x &&
7905 "adjusting dtor exception specs was introduced in c++11");
7906
Sebastian Redl0ee33912011-05-19 05:13:44 +00007907 // C++11 [class.dtor]p3:
7908 // A declaration of a destructor that does not have an exception-
7909 // specification is implicitly considered to have the same exception-
7910 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007911 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007912 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007913 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007914 return;
7915
Chandler Carruth3f224b22011-09-20 04:55:26 +00007916 // Replace the destructor's type, building off the existing one. Fortunately,
7917 // the only thing of interest in the destructor type is its extended info.
7918 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007919 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7920 EPI.ExceptionSpecType = EST_Unevaluated;
7921 EPI.ExceptionSpecDecl = Destructor;
7922 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007923
Sebastian Redl0ee33912011-05-19 05:13:44 +00007924 // FIXME: If the destructor has a body that could throw, and the newly created
7925 // spec doesn't allow exceptions, we should emit a warning, because this
7926 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007927 // However, we don't have a body or an exception specification yet, so it
7928 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007929}
7930
Richard Smith8c889532012-11-14 00:50:40 +00007931/// When generating a defaulted copy or move assignment operator, if a field
7932/// should be copied with __builtin_memcpy rather than via explicit assignments,
7933/// do so. This optimization only applies for arrays of scalars, and for arrays
7934/// of class type where the selected copy/move-assignment operator is trivial.
7935static StmtResult
7936buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7937 Expr *To, Expr *From) {
7938 // Compute the size of the memory buffer to be copied.
7939 QualType SizeType = S.Context.getSizeType();
7940 llvm::APInt Size(S.Context.getTypeSize(SizeType),
7941 S.Context.getTypeSizeInChars(T).getQuantity());
7942
7943 // Take the address of the field references for "from" and "to". We
7944 // directly construct UnaryOperators here because semantic analysis
7945 // does not permit us to take the address of an xvalue.
7946 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7947 S.Context.getPointerType(From->getType()),
7948 VK_RValue, OK_Ordinary, Loc);
7949 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7950 S.Context.getPointerType(To->getType()),
7951 VK_RValue, OK_Ordinary, Loc);
7952
7953 const Type *E = T->getBaseElementTypeUnsafe();
7954 bool NeedsCollectableMemCpy =
7955 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7956
7957 // Create a reference to the __builtin_objc_memmove_collectable function
7958 StringRef MemCpyName = NeedsCollectableMemCpy ?
7959 "__builtin_objc_memmove_collectable" :
7960 "__builtin_memcpy";
7961 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
7962 Sema::LookupOrdinaryName);
7963 S.LookupName(R, S.TUScope, true);
7964
7965 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
7966 if (!MemCpy)
7967 // Something went horribly wrong earlier, and we will have complained
7968 // about it.
7969 return StmtError();
7970
7971 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
7972 VK_RValue, Loc, 0);
7973 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
7974
7975 Expr *CallArgs[] = {
7976 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
7977 };
7978 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
7979 Loc, CallArgs, Loc);
7980
7981 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7982 return S.Owned(Call.takeAs<Stmt>());
7983}
7984
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007985/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007986/// \c To.
7987///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007988/// This routine is used to copy/move the members of a class with an
7989/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007990/// copied are arrays, this routine builds for loops to copy them.
7991///
7992/// \param S The Sema object used for type-checking.
7993///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007994/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007995///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007996/// \param T The type of the expressions being copied/moved. Both expressions
7997/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007998///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007999/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008000///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008001/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008002///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008003/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008004/// Otherwise, it's a non-static member subobject.
8005///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008006/// \param Copying Whether we're copying or moving.
8007///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008008/// \param Depth Internal parameter recording the depth of the recursion.
8009///
Richard Smith8c889532012-11-14 00:50:40 +00008010/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8011/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008012static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008013buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8014 Expr *To, Expr *From,
8015 bool CopyingBaseSubobject, bool Copying,
8016 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008017 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008018 // Each subobject is assigned in the manner appropriate to its type:
8019 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008020 // - if the subobject is of class type, as if by a call to operator= with
8021 // the subobject as the object expression and the corresponding
8022 // subobject of x as a single function argument (as if by explicit
8023 // qualification; that is, ignoring any possible virtual overriding
8024 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008025 //
8026 // C++03 [class.copy]p13:
8027 // - if the subobject is of class type, the copy assignment operator for
8028 // the class is used (as if by explicit qualification; that is,
8029 // ignoring any possible virtual overriding functions in more derived
8030 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008031 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8032 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008033
Douglas Gregor06a9f362010-05-01 20:49:11 +00008034 // Look for operator=.
8035 DeclarationName Name
8036 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8037 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8038 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008039
Richard Smith044c8aa2012-11-13 00:54:12 +00008040 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8041 // operator.
8042 if (!S.getLangOpts().CPlusPlus0x) {
8043 LookupResult::Filter F = OpLookup.makeFilter();
8044 while (F.hasNext()) {
8045 NamedDecl *D = F.next();
8046 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8047 if (Method->isCopyAssignmentOperator() ||
8048 (!Copying && Method->isMoveAssignmentOperator()))
8049 continue;
8050
8051 F.erase();
8052 }
8053 F.done();
John McCallb0207482010-03-16 06:11:48 +00008054 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008055
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008056 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008057 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008058 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008059 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008060 // ambiguities), we need to cast "this" to that subobject type; to
8061 // ensure that we don't go through the virtual call mechanism, we need
8062 // to qualify the operator= name with the base class (see below). However,
8063 // this means that if the base class has a protected copy assignment
8064 // operator, the protected member access check will fail. So, we
8065 // rewrite "protected" access to "public" access in this case, since we
8066 // know by construction that we're calling from a derived class.
8067 if (CopyingBaseSubobject) {
8068 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8069 L != LEnd; ++L) {
8070 if (L.getAccess() == AS_protected)
8071 L.setAccess(AS_public);
8072 }
8073 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008074
Douglas Gregor06a9f362010-05-01 20:49:11 +00008075 // Create the nested-name-specifier that will be used to qualify the
8076 // reference to operator=; this is required to suppress the virtual
8077 // call mechanism.
8078 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008079 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008080 SS.MakeTrivial(S.Context,
8081 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008082 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008083 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008084
Douglas Gregor06a9f362010-05-01 20:49:11 +00008085 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008086 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008087 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008088 /*TemplateKWLoc=*/SourceLocation(),
8089 /*FirstQualifierInScope=*/0,
8090 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008091 /*TemplateArgs=*/0,
8092 /*SuppressQualifierCheck=*/true);
8093 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008094 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008095
Douglas Gregor06a9f362010-05-01 20:49:11 +00008096 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008097
Richard Smith044c8aa2012-11-13 00:54:12 +00008098 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008099 OpEqualRef.takeAs<Expr>(),
8100 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008101 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008102 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008103
Richard Smith8c889532012-11-14 00:50:40 +00008104 // If we built a call to a trivial 'operator=' while copying an array,
8105 // bail out. We'll replace the whole shebang with a memcpy.
8106 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8107 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8108 return StmtResult((Stmt*)0);
8109
Richard Smith044c8aa2012-11-13 00:54:12 +00008110 // Convert to an expression-statement, and clean up any produced
8111 // temporaries.
8112 return S.ActOnExprStmt(S.MakeFullExpr(Call.take(), Loc));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008113 }
John McCallb0207482010-03-16 06:11:48 +00008114
Richard Smith044c8aa2012-11-13 00:54:12 +00008115 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008116 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008117 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008118 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008119 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008120 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008121 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008122 return S.ActOnExprStmt(S.MakeFullExpr(Assignment.take(), Loc));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008123 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008124
8125 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008126 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008127
Douglas Gregor06a9f362010-05-01 20:49:11 +00008128 // Construct a loop over the array bounds, e.g.,
8129 //
8130 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8131 //
8132 // that will copy each of the array elements.
8133 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008134
Douglas Gregor06a9f362010-05-01 20:49:11 +00008135 // Create the iteration variable.
8136 IdentifierInfo *IterationVarName = 0;
8137 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008138 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008139 llvm::raw_svector_ostream OS(Str);
8140 OS << "__i" << Depth;
8141 IterationVarName = &S.Context.Idents.get(OS.str());
8142 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008143 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008144 IterationVarName, SizeType,
8145 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00008146 SC_None, SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008147
Douglas Gregor06a9f362010-05-01 20:49:11 +00008148 // Initialize the iteration variable to zero.
8149 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008150 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008151
8152 // Create a reference to the iteration variable; we'll use this several
8153 // times throughout.
8154 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008155 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008156 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008157 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8158 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8159
Douglas Gregor06a9f362010-05-01 20:49:11 +00008160 // Create the DeclStmt that holds the iteration variable.
8161 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008162
Douglas Gregor06a9f362010-05-01 20:49:11 +00008163 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008164 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008165 IterationVarRefRVal,
8166 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008167 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008168 IterationVarRefRVal,
8169 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008170 if (!Copying) // Cast to rvalue
8171 From = CastForMoving(S, From);
8172
8173 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008174 StmtResult Copy =
8175 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8176 To, From, CopyingBaseSubobject,
8177 Copying, Depth + 1);
8178 // Bail out if copying fails or if we determined that we should use memcpy.
8179 if (Copy.isInvalid() || !Copy.get())
8180 return Copy;
8181
8182 // Create the comparison against the array bound.
8183 llvm::APInt Upper
8184 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8185 Expr *Comparison
8186 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8187 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8188 BO_NE, S.Context.BoolTy,
8189 VK_RValue, OK_Ordinary, Loc, false);
8190
8191 // Create the pre-increment of the iteration variable.
8192 Expr *Increment
8193 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8194 VK_LValue, OK_Ordinary, Loc);
8195
Douglas Gregor06a9f362010-05-01 20:49:11 +00008196 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008197 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008198 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00008199 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008200 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008201}
8202
Richard Smith8c889532012-11-14 00:50:40 +00008203static StmtResult
8204buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8205 Expr *To, Expr *From,
8206 bool CopyingBaseSubobject, bool Copying) {
8207 // Maybe we should use a memcpy?
8208 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8209 T.isTriviallyCopyableType(S.Context))
8210 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8211
8212 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8213 CopyingBaseSubobject,
8214 Copying, 0));
8215
8216 // If we ended up picking a trivial assignment operator for an array of a
8217 // non-trivially-copyable class type, just emit a memcpy.
8218 if (!Result.isInvalid() && !Result.get())
8219 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8220
8221 return Result;
8222}
8223
Richard Smithb9d0b762012-07-27 04:22:15 +00008224Sema::ImplicitExceptionSpecification
8225Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8226 CXXRecordDecl *ClassDecl = MD->getParent();
8227
8228 ImplicitExceptionSpecification ExceptSpec(*this);
8229 if (ClassDecl->isInvalidDecl())
8230 return ExceptSpec;
8231
8232 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8233 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8234 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8235
Douglas Gregorb87786f2010-07-01 17:48:08 +00008236 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008237 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008238 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008239
8240 // It is unspecified whether or not an implicit copy assignment operator
8241 // attempts to deduplicate calls to assignment operators of virtual bases are
8242 // made. As such, this exception specification is effectively unspecified.
8243 // Based on a similar decision made for constness in C++0x, we're erring on
8244 // the side of assuming such calls to be made regardless of whether they
8245 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008246 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8247 BaseEnd = ClassDecl->bases_end();
8248 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008249 if (Base->isVirtual())
8250 continue;
8251
Douglas Gregora376d102010-07-02 21:50:04 +00008252 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008253 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008254 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8255 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008256 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008257 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008258
8259 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8260 BaseEnd = ClassDecl->vbases_end();
8261 Base != BaseEnd; ++Base) {
8262 CXXRecordDecl *BaseClassDecl
8263 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8264 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8265 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008266 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008267 }
8268
Douglas Gregorb87786f2010-07-01 17:48:08 +00008269 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8270 FieldEnd = ClassDecl->field_end();
8271 Field != FieldEnd;
8272 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008273 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008274 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8275 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008276 LookupCopyingAssignment(FieldClassDecl,
8277 ArgQuals | FieldType.getCVRQualifiers(),
8278 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008279 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008280 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008281 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008282
Richard Smithb9d0b762012-07-27 04:22:15 +00008283 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008284}
8285
8286CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8287 // Note: The following rules are largely analoguous to the copy
8288 // constructor rules. Note that virtual bases are not taken into account
8289 // for determining the argument type of the operator. Note also that
8290 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008291 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008292
Richard Smithafb49182012-11-29 01:34:07 +00008293 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8294 if (DSM.isAlreadyBeingDeclared())
8295 return 0;
8296
Sean Hunt30de05c2011-05-14 05:23:20 +00008297 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8298 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008299 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008300 ArgType = ArgType.withConst();
8301 ArgType = Context.getLValueReferenceType(ArgType);
8302
Douglas Gregord3c35902010-07-01 16:36:15 +00008303 // An implicitly-declared copy assignment operator is an inline public
8304 // member of its class.
8305 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008306 SourceLocation ClassLoc = ClassDecl->getLocation();
8307 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008308 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008309 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00008310 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00008311 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008312 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008313 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008314 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008315 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008316 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008317
8318 // Build an exception specification pointing back at this member.
8319 FunctionProtoType::ExtProtoInfo EPI;
8320 EPI.ExceptionSpecType = EST_Unevaluated;
8321 EPI.ExceptionSpecDecl = CopyAssignment;
8322 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8323
Douglas Gregord3c35902010-07-01 16:36:15 +00008324 // Add the parameter to the operator.
8325 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008326 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008327 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008328 SC_None,
8329 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008330 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008331
Richard Smithbc2a35d2012-12-08 08:32:28 +00008332 AddOverriddenMethods(ClassDecl, CopyAssignment);
8333
8334 CopyAssignment->setTrivial(
8335 ClassDecl->needsOverloadResolutionForCopyAssignment()
8336 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8337 : ClassDecl->hasTrivialCopyAssignment());
8338
Nico Weberafcc96a2012-01-23 03:19:29 +00008339 // C++0x [class.copy]p19:
8340 // .... If the class definition does not explicitly declare a copy
8341 // assignment operator, there is no user-declared move constructor, and
8342 // there is no user-declared move assignment operator, a copy assignment
8343 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008344 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00008345 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008346
Richard Smithbc2a35d2012-12-08 08:32:28 +00008347 // Note that we have added this copy-assignment operator.
8348 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8349
8350 if (Scope *S = getScopeForContext(ClassDecl))
8351 PushOnScopeChains(CopyAssignment, S, false);
8352 ClassDecl->addDecl(CopyAssignment);
8353
Douglas Gregord3c35902010-07-01 16:36:15 +00008354 return CopyAssignment;
8355}
8356
Douglas Gregor06a9f362010-05-01 20:49:11 +00008357void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8358 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008359 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008360 CopyAssignOperator->isOverloadedOperator() &&
8361 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008362 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8363 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008364 "DefineImplicitCopyAssignment called for wrong function");
8365
8366 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8367
8368 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8369 CopyAssignOperator->setInvalidDecl();
8370 return;
8371 }
8372
8373 CopyAssignOperator->setUsed();
8374
Eli Friedman9a14db32012-10-18 20:14:08 +00008375 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008376 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008377
8378 // C++0x [class.copy]p30:
8379 // The implicitly-defined or explicitly-defaulted copy assignment operator
8380 // for a non-union class X performs memberwise copy assignment of its
8381 // subobjects. The direct base classes of X are assigned first, in the
8382 // order of their declaration in the base-specifier-list, and then the
8383 // immediate non-static data members of X are assigned, in the order in
8384 // which they were declared in the class definition.
8385
8386 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008387 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008388
8389 // The parameter for the "other" object, which we are copying from.
8390 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8391 Qualifiers OtherQuals = Other->getType().getQualifiers();
8392 QualType OtherRefType = Other->getType();
8393 if (const LValueReferenceType *OtherRef
8394 = OtherRefType->getAs<LValueReferenceType>()) {
8395 OtherRefType = OtherRef->getPointeeType();
8396 OtherQuals = OtherRefType.getQualifiers();
8397 }
8398
8399 // Our location for everything implicitly-generated.
8400 SourceLocation Loc = CopyAssignOperator->getLocation();
8401
8402 // Construct a reference to the "other" object. We'll be using this
8403 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008404 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008405 assert(OtherRef && "Reference to parameter cannot fail!");
8406
8407 // Construct the "this" pointer. We'll be using this throughout the generated
8408 // ASTs.
8409 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8410 assert(This && "Reference to this cannot fail!");
8411
8412 // Assign base classes.
8413 bool Invalid = false;
8414 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8415 E = ClassDecl->bases_end(); Base != E; ++Base) {
8416 // Form the assignment:
8417 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8418 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008419 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008420 Invalid = true;
8421 continue;
8422 }
8423
John McCallf871d0c2010-08-07 06:22:56 +00008424 CXXCastPath BasePath;
8425 BasePath.push_back(Base);
8426
Douglas Gregor06a9f362010-05-01 20:49:11 +00008427 // Construct the "from" expression, which is an implicit cast to the
8428 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008429 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008430 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8431 CK_UncheckedDerivedToBase,
8432 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008433
8434 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008435 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008436
8437 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008438 To = ImpCastExprToType(To.take(),
8439 Context.getCVRQualifiedType(BaseType,
8440 CopyAssignOperator->getTypeQualifiers()),
8441 CK_UncheckedDerivedToBase,
8442 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008443
8444 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008445 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008446 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008447 /*CopyingBaseSubobject=*/true,
8448 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008449 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008450 Diag(CurrentLocation, diag::note_member_synthesized_at)
8451 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8452 CopyAssignOperator->setInvalidDecl();
8453 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008454 }
8455
8456 // Success! Record the copy.
8457 Statements.push_back(Copy.takeAs<Expr>());
8458 }
8459
Douglas Gregor06a9f362010-05-01 20:49:11 +00008460 // Assign non-static members.
8461 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8462 FieldEnd = ClassDecl->field_end();
8463 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008464 if (Field->isUnnamedBitfield())
8465 continue;
8466
Douglas Gregor06a9f362010-05-01 20:49:11 +00008467 // Check for members of reference type; we can't copy those.
8468 if (Field->getType()->isReferenceType()) {
8469 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8470 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8471 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008472 Diag(CurrentLocation, diag::note_member_synthesized_at)
8473 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008474 Invalid = true;
8475 continue;
8476 }
8477
8478 // Check for members of const-qualified, non-class type.
8479 QualType BaseType = Context.getBaseElementType(Field->getType());
8480 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8481 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8482 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8483 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008484 Diag(CurrentLocation, diag::note_member_synthesized_at)
8485 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008486 Invalid = true;
8487 continue;
8488 }
John McCallb77115d2011-06-17 00:18:42 +00008489
8490 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008491 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8492 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008493
8494 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008495 if (FieldType->isIncompleteArrayType()) {
8496 assert(ClassDecl->hasFlexibleArrayMember() &&
8497 "Incomplete array type is not valid");
8498 continue;
8499 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008500
8501 // Build references to the field in the object we're copying from and to.
8502 CXXScopeSpec SS; // Intentionally empty
8503 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8504 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008505 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008506 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008507 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008508 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008509 SS, SourceLocation(), 0,
8510 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008511 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008512 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008513 SS, SourceLocation(), 0,
8514 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008515 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8516 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008517
Douglas Gregor06a9f362010-05-01 20:49:11 +00008518 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008519 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008520 To.get(), From.get(),
8521 /*CopyingBaseSubobject=*/false,
8522 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008523 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008524 Diag(CurrentLocation, diag::note_member_synthesized_at)
8525 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8526 CopyAssignOperator->setInvalidDecl();
8527 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008528 }
8529
8530 // Success! Record the copy.
8531 Statements.push_back(Copy.takeAs<Stmt>());
8532 }
8533
8534 if (!Invalid) {
8535 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008536 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008537
John McCall60d7b3a2010-08-24 06:29:42 +00008538 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008539 if (Return.isInvalid())
8540 Invalid = true;
8541 else {
8542 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008543
8544 if (Trap.hasErrorOccurred()) {
8545 Diag(CurrentLocation, diag::note_member_synthesized_at)
8546 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8547 Invalid = true;
8548 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008549 }
8550 }
8551
8552 if (Invalid) {
8553 CopyAssignOperator->setInvalidDecl();
8554 return;
8555 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008556
8557 StmtResult Body;
8558 {
8559 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008560 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008561 /*isStmtExpr=*/false);
8562 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8563 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008564 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008565
8566 if (ASTMutationListener *L = getASTMutationListener()) {
8567 L->CompletedImplicitDefinition(CopyAssignOperator);
8568 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008569}
8570
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008571Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008572Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8573 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008574
Richard Smithb9d0b762012-07-27 04:22:15 +00008575 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008576 if (ClassDecl->isInvalidDecl())
8577 return ExceptSpec;
8578
8579 // C++0x [except.spec]p14:
8580 // An implicitly declared special member function (Clause 12) shall have an
8581 // exception-specification. [...]
8582
8583 // It is unspecified whether or not an implicit move assignment operator
8584 // attempts to deduplicate calls to assignment operators of virtual bases are
8585 // made. As such, this exception specification is effectively unspecified.
8586 // Based on a similar decision made for constness in C++0x, we're erring on
8587 // the side of assuming such calls to be made regardless of whether they
8588 // actually happen.
8589 // Note that a move constructor is not implicitly declared when there are
8590 // virtual bases, but it can still be user-declared and explicitly defaulted.
8591 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8592 BaseEnd = ClassDecl->bases_end();
8593 Base != BaseEnd; ++Base) {
8594 if (Base->isVirtual())
8595 continue;
8596
8597 CXXRecordDecl *BaseClassDecl
8598 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8599 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008600 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008601 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008602 }
8603
8604 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8605 BaseEnd = ClassDecl->vbases_end();
8606 Base != BaseEnd; ++Base) {
8607 CXXRecordDecl *BaseClassDecl
8608 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8609 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008610 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008611 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008612 }
8613
8614 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8615 FieldEnd = ClassDecl->field_end();
8616 Field != FieldEnd;
8617 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008618 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008619 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008620 if (CXXMethodDecl *MoveAssign =
8621 LookupMovingAssignment(FieldClassDecl,
8622 FieldType.getCVRQualifiers(),
8623 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008624 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008625 }
8626 }
8627
8628 return ExceptSpec;
8629}
8630
Richard Smith1c931be2012-04-02 18:40:40 +00008631/// Determine whether the class type has any direct or indirect virtual base
8632/// classes which have a non-trivial move assignment operator.
8633static bool
8634hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8635 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8636 BaseEnd = ClassDecl->vbases_end();
8637 Base != BaseEnd; ++Base) {
8638 CXXRecordDecl *BaseClass =
8639 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8640
8641 // Try to declare the move assignment. If it would be deleted, then the
8642 // class does not have a non-trivial move assignment.
8643 if (BaseClass->needsImplicitMoveAssignment())
8644 S.DeclareImplicitMoveAssignment(BaseClass);
8645
Richard Smith426391c2012-11-16 00:53:38 +00008646 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008647 return true;
8648 }
8649
8650 return false;
8651}
8652
8653/// Determine whether the given type either has a move constructor or is
8654/// trivially copyable.
8655static bool
8656hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8657 Type = S.Context.getBaseElementType(Type);
8658
8659 // FIXME: Technically, non-trivially-copyable non-class types, such as
8660 // reference types, are supposed to return false here, but that appears
8661 // to be a standard defect.
8662 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008663 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008664 return true;
8665
8666 if (Type.isTriviallyCopyableType(S.Context))
8667 return true;
8668
8669 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008670 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8671 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008672 if (ClassDecl->needsImplicitMoveConstructor())
8673 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008674 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008675 }
8676
Richard Smithe5411b72012-12-01 02:35:44 +00008677 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8678 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008679 if (ClassDecl->needsImplicitMoveAssignment())
8680 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008681 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008682}
8683
8684/// Determine whether all non-static data members and direct or virtual bases
8685/// of class \p ClassDecl have either a move operation, or are trivially
8686/// copyable.
8687static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8688 bool IsConstructor) {
8689 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8690 BaseEnd = ClassDecl->bases_end();
8691 Base != BaseEnd; ++Base) {
8692 if (Base->isVirtual())
8693 continue;
8694
8695 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8696 return false;
8697 }
8698
8699 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8700 BaseEnd = ClassDecl->vbases_end();
8701 Base != BaseEnd; ++Base) {
8702 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8703 return false;
8704 }
8705
8706 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8707 FieldEnd = ClassDecl->field_end();
8708 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008709 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008710 return false;
8711 }
8712
8713 return true;
8714}
8715
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008716CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008717 // C++11 [class.copy]p20:
8718 // If the definition of a class X does not explicitly declare a move
8719 // assignment operator, one will be implicitly declared as defaulted
8720 // if and only if:
8721 //
8722 // - [first 4 bullets]
8723 assert(ClassDecl->needsImplicitMoveAssignment());
8724
Richard Smithafb49182012-11-29 01:34:07 +00008725 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8726 if (DSM.isAlreadyBeingDeclared())
8727 return 0;
8728
Richard Smith1c931be2012-04-02 18:40:40 +00008729 // [Checked after we build the declaration]
8730 // - the move assignment operator would not be implicitly defined as
8731 // deleted,
8732
8733 // [DR1402]:
8734 // - X has no direct or indirect virtual base class with a non-trivial
8735 // move assignment operator, and
8736 // - each of X's non-static data members and direct or virtual base classes
8737 // has a type that either has a move assignment operator or is trivially
8738 // copyable.
8739 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8740 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8741 ClassDecl->setFailedImplicitMoveAssignment();
8742 return 0;
8743 }
8744
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008745 // Note: The following rules are largely analoguous to the move
8746 // constructor rules.
8747
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008748 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8749 QualType RetType = Context.getLValueReferenceType(ArgType);
8750 ArgType = Context.getRValueReferenceType(ArgType);
8751
8752 // An implicitly-declared move assignment operator is an inline public
8753 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008754 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8755 SourceLocation ClassLoc = ClassDecl->getLocation();
8756 DeclarationNameInfo NameInfo(Name, ClassLoc);
8757 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008758 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008759 /*TInfo=*/0, /*isStatic=*/false,
8760 /*StorageClassAsWritten=*/SC_None,
8761 /*isInline=*/true,
8762 /*isConstexpr=*/false,
8763 SourceLocation());
8764 MoveAssignment->setAccess(AS_public);
8765 MoveAssignment->setDefaulted();
8766 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008767
Richard Smithb9d0b762012-07-27 04:22:15 +00008768 // Build an exception specification pointing back at this member.
8769 FunctionProtoType::ExtProtoInfo EPI;
8770 EPI.ExceptionSpecType = EST_Unevaluated;
8771 EPI.ExceptionSpecDecl = MoveAssignment;
8772 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8773
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008774 // Add the parameter to the operator.
8775 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8776 ClassLoc, ClassLoc, /*Id=*/0,
8777 ArgType, /*TInfo=*/0,
8778 SC_None,
8779 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008780 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008781
Richard Smithbc2a35d2012-12-08 08:32:28 +00008782 AddOverriddenMethods(ClassDecl, MoveAssignment);
8783
8784 MoveAssignment->setTrivial(
8785 ClassDecl->needsOverloadResolutionForMoveAssignment()
8786 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8787 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008788
8789 // C++0x [class.copy]p9:
8790 // If the definition of a class X does not explicitly declare a move
8791 // assignment operator, one will be implicitly declared as defaulted if and
8792 // only if:
8793 // [...]
8794 // - the move assignment operator would not be implicitly defined as
8795 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008796 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008797 // Cache this result so that we don't try to generate this over and over
8798 // on every lookup, leaking memory and wasting time.
8799 ClassDecl->setFailedImplicitMoveAssignment();
8800 return 0;
8801 }
8802
Richard Smithbc2a35d2012-12-08 08:32:28 +00008803 // Note that we have added this copy-assignment operator.
8804 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8805
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008806 if (Scope *S = getScopeForContext(ClassDecl))
8807 PushOnScopeChains(MoveAssignment, S, false);
8808 ClassDecl->addDecl(MoveAssignment);
8809
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008810 return MoveAssignment;
8811}
8812
8813void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8814 CXXMethodDecl *MoveAssignOperator) {
8815 assert((MoveAssignOperator->isDefaulted() &&
8816 MoveAssignOperator->isOverloadedOperator() &&
8817 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008818 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8819 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008820 "DefineImplicitMoveAssignment called for wrong function");
8821
8822 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8823
8824 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8825 MoveAssignOperator->setInvalidDecl();
8826 return;
8827 }
8828
8829 MoveAssignOperator->setUsed();
8830
Eli Friedman9a14db32012-10-18 20:14:08 +00008831 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008832 DiagnosticErrorTrap Trap(Diags);
8833
8834 // C++0x [class.copy]p28:
8835 // The implicitly-defined or move assignment operator for a non-union class
8836 // X performs memberwise move assignment of its subobjects. The direct base
8837 // classes of X are assigned first, in the order of their declaration in the
8838 // base-specifier-list, and then the immediate non-static data members of X
8839 // are assigned, in the order in which they were declared in the class
8840 // definition.
8841
8842 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008843 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008844
8845 // The parameter for the "other" object, which we are move from.
8846 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8847 QualType OtherRefType = Other->getType()->
8848 getAs<RValueReferenceType>()->getPointeeType();
8849 assert(OtherRefType.getQualifiers() == 0 &&
8850 "Bad argument type of defaulted move assignment");
8851
8852 // Our location for everything implicitly-generated.
8853 SourceLocation Loc = MoveAssignOperator->getLocation();
8854
8855 // Construct a reference to the "other" object. We'll be using this
8856 // throughout the generated ASTs.
8857 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8858 assert(OtherRef && "Reference to parameter cannot fail!");
8859 // Cast to rvalue.
8860 OtherRef = CastForMoving(*this, OtherRef);
8861
8862 // Construct the "this" pointer. We'll be using this throughout the generated
8863 // ASTs.
8864 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8865 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008866
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008867 // Assign base classes.
8868 bool Invalid = false;
8869 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8870 E = ClassDecl->bases_end(); Base != E; ++Base) {
8871 // Form the assignment:
8872 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8873 QualType BaseType = Base->getType().getUnqualifiedType();
8874 if (!BaseType->isRecordType()) {
8875 Invalid = true;
8876 continue;
8877 }
8878
8879 CXXCastPath BasePath;
8880 BasePath.push_back(Base);
8881
8882 // Construct the "from" expression, which is an implicit cast to the
8883 // appropriately-qualified base type.
8884 Expr *From = OtherRef;
8885 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008886 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008887
8888 // Dereference "this".
8889 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8890
8891 // Implicitly cast "this" to the appropriately-qualified base type.
8892 To = ImpCastExprToType(To.take(),
8893 Context.getCVRQualifiedType(BaseType,
8894 MoveAssignOperator->getTypeQualifiers()),
8895 CK_UncheckedDerivedToBase,
8896 VK_LValue, &BasePath);
8897
8898 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00008899 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008900 To.get(), From,
8901 /*CopyingBaseSubobject=*/true,
8902 /*Copying=*/false);
8903 if (Move.isInvalid()) {
8904 Diag(CurrentLocation, diag::note_member_synthesized_at)
8905 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8906 MoveAssignOperator->setInvalidDecl();
8907 return;
8908 }
8909
8910 // Success! Record the move.
8911 Statements.push_back(Move.takeAs<Expr>());
8912 }
8913
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008914 // Assign non-static members.
8915 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8916 FieldEnd = ClassDecl->field_end();
8917 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008918 if (Field->isUnnamedBitfield())
8919 continue;
8920
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008921 // Check for members of reference type; we can't move those.
8922 if (Field->getType()->isReferenceType()) {
8923 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8924 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8925 Diag(Field->getLocation(), diag::note_declared_at);
8926 Diag(CurrentLocation, diag::note_member_synthesized_at)
8927 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8928 Invalid = true;
8929 continue;
8930 }
8931
8932 // Check for members of const-qualified, non-class type.
8933 QualType BaseType = Context.getBaseElementType(Field->getType());
8934 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8935 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8936 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8937 Diag(Field->getLocation(), diag::note_declared_at);
8938 Diag(CurrentLocation, diag::note_member_synthesized_at)
8939 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8940 Invalid = true;
8941 continue;
8942 }
8943
8944 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008945 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8946 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008947
8948 QualType FieldType = Field->getType().getNonReferenceType();
8949 if (FieldType->isIncompleteArrayType()) {
8950 assert(ClassDecl->hasFlexibleArrayMember() &&
8951 "Incomplete array type is not valid");
8952 continue;
8953 }
8954
8955 // Build references to the field in the object we're copying from and to.
8956 CXXScopeSpec SS; // Intentionally empty
8957 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8958 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008959 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008960 MemberLookup.resolveKind();
8961 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8962 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008963 SS, SourceLocation(), 0,
8964 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008965 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8966 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008967 SS, SourceLocation(), 0,
8968 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008969 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8970 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8971
8972 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8973 "Member reference with rvalue base must be rvalue except for reference "
8974 "members, which aren't allowed for move assignment.");
8975
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008976 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008977 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008978 To.get(), From.get(),
8979 /*CopyingBaseSubobject=*/false,
8980 /*Copying=*/false);
8981 if (Move.isInvalid()) {
8982 Diag(CurrentLocation, diag::note_member_synthesized_at)
8983 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8984 MoveAssignOperator->setInvalidDecl();
8985 return;
8986 }
Richard Smithe7ce7092012-11-12 23:33:00 +00008987
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008988 // Success! Record the copy.
8989 Statements.push_back(Move.takeAs<Stmt>());
8990 }
8991
8992 if (!Invalid) {
8993 // Add a "return *this;"
8994 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8995
8996 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8997 if (Return.isInvalid())
8998 Invalid = true;
8999 else {
9000 Statements.push_back(Return.takeAs<Stmt>());
9001
9002 if (Trap.hasErrorOccurred()) {
9003 Diag(CurrentLocation, diag::note_member_synthesized_at)
9004 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9005 Invalid = true;
9006 }
9007 }
9008 }
9009
9010 if (Invalid) {
9011 MoveAssignOperator->setInvalidDecl();
9012 return;
9013 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009014
9015 StmtResult Body;
9016 {
9017 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009018 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009019 /*isStmtExpr=*/false);
9020 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9021 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009022 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9023
9024 if (ASTMutationListener *L = getASTMutationListener()) {
9025 L->CompletedImplicitDefinition(MoveAssignOperator);
9026 }
9027}
9028
Richard Smithb9d0b762012-07-27 04:22:15 +00009029Sema::ImplicitExceptionSpecification
9030Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9031 CXXRecordDecl *ClassDecl = MD->getParent();
9032
9033 ImplicitExceptionSpecification ExceptSpec(*this);
9034 if (ClassDecl->isInvalidDecl())
9035 return ExceptSpec;
9036
9037 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9038 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9039 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9040
Douglas Gregor0d405db2010-07-01 20:59:04 +00009041 // C++ [except.spec]p14:
9042 // An implicitly declared special member function (Clause 12) shall have an
9043 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009044 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9045 BaseEnd = ClassDecl->bases_end();
9046 Base != BaseEnd;
9047 ++Base) {
9048 // Virtual bases are handled below.
9049 if (Base->isVirtual())
9050 continue;
9051
Douglas Gregor22584312010-07-02 23:41:54 +00009052 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009053 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009054 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009055 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009056 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009057 }
9058 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9059 BaseEnd = ClassDecl->vbases_end();
9060 Base != BaseEnd;
9061 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009062 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009063 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009064 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009065 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009066 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009067 }
9068 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9069 FieldEnd = ClassDecl->field_end();
9070 Field != FieldEnd;
9071 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009072 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009073 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9074 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009075 LookupCopyingConstructor(FieldClassDecl,
9076 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009077 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009078 }
9079 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009080
Richard Smithb9d0b762012-07-27 04:22:15 +00009081 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009082}
9083
9084CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9085 CXXRecordDecl *ClassDecl) {
9086 // C++ [class.copy]p4:
9087 // If the class definition does not explicitly declare a copy
9088 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009089 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009090
Richard Smithafb49182012-11-29 01:34:07 +00009091 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9092 if (DSM.isAlreadyBeingDeclared())
9093 return 0;
9094
Sean Hunt49634cf2011-05-13 06:10:58 +00009095 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9096 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009097 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009098 if (Const)
9099 ArgType = ArgType.withConst();
9100 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009101
Richard Smith7756afa2012-06-10 05:43:50 +00009102 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9103 CXXCopyConstructor,
9104 Const);
9105
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009106 DeclarationName Name
9107 = Context.DeclarationNames.getCXXConstructorName(
9108 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009109 SourceLocation ClassLoc = ClassDecl->getLocation();
9110 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009111
9112 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009113 // member of its class.
9114 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009115 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009116 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009117 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009118 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009119 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009120
Richard Smithb9d0b762012-07-27 04:22:15 +00009121 // Build an exception specification pointing back at this member.
9122 FunctionProtoType::ExtProtoInfo EPI;
9123 EPI.ExceptionSpecType = EST_Unevaluated;
9124 EPI.ExceptionSpecDecl = CopyConstructor;
9125 CopyConstructor->setType(
9126 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9127
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009128 // Add the parameter to the constructor.
9129 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009130 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009131 /*IdentifierInfo=*/0,
9132 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009133 SC_None,
9134 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009135 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009136
Richard Smithbc2a35d2012-12-08 08:32:28 +00009137 CopyConstructor->setTrivial(
9138 ClassDecl->needsOverloadResolutionForCopyConstructor()
9139 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9140 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009141
Nico Weberafcc96a2012-01-23 03:19:29 +00009142 // C++11 [class.copy]p8:
9143 // ... If the class definition does not explicitly declare a copy
9144 // constructor, there is no user-declared move constructor, and there is no
9145 // user-declared move assignment operator, a copy constructor is implicitly
9146 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009147 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00009148 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00009149
Richard Smithbc2a35d2012-12-08 08:32:28 +00009150 // Note that we have declared this constructor.
9151 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9152
9153 if (Scope *S = getScopeForContext(ClassDecl))
9154 PushOnScopeChains(CopyConstructor, S, false);
9155 ClassDecl->addDecl(CopyConstructor);
9156
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009157 return CopyConstructor;
9158}
9159
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009160void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009161 CXXConstructorDecl *CopyConstructor) {
9162 assert((CopyConstructor->isDefaulted() &&
9163 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009164 !CopyConstructor->doesThisDeclarationHaveABody() &&
9165 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009166 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009167
Anders Carlsson63010a72010-04-23 16:24:12 +00009168 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009169 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009170
Eli Friedman9a14db32012-10-18 20:14:08 +00009171 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009172 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009173
Sean Huntcbb67482011-01-08 20:30:50 +00009174 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009175 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009176 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009177 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009178 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009179 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009180 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009181 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9182 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009183 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009184 /*isStmtExpr=*/false)
9185 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009186 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009187 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009188
9189 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009190 if (ASTMutationListener *L = getASTMutationListener()) {
9191 L->CompletedImplicitDefinition(CopyConstructor);
9192 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009193}
9194
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009195Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009196Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9197 CXXRecordDecl *ClassDecl = MD->getParent();
9198
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009199 // C++ [except.spec]p14:
9200 // An implicitly declared special member function (Clause 12) shall have an
9201 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009202 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009203 if (ClassDecl->isInvalidDecl())
9204 return ExceptSpec;
9205
9206 // Direct base-class constructors.
9207 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9208 BEnd = ClassDecl->bases_end();
9209 B != BEnd; ++B) {
9210 if (B->isVirtual()) // Handled below.
9211 continue;
9212
9213 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9214 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009215 CXXConstructorDecl *Constructor =
9216 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009217 // If this is a deleted function, add it anyway. This might be conformant
9218 // with the standard. This might not. I'm not sure. It might not matter.
9219 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009220 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009221 }
9222 }
9223
9224 // Virtual base-class constructors.
9225 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9226 BEnd = ClassDecl->vbases_end();
9227 B != BEnd; ++B) {
9228 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9229 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009230 CXXConstructorDecl *Constructor =
9231 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009232 // If this is a deleted function, add it anyway. This might be conformant
9233 // with the standard. This might not. I'm not sure. It might not matter.
9234 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009235 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009236 }
9237 }
9238
9239 // Field constructors.
9240 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9241 FEnd = ClassDecl->field_end();
9242 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009243 QualType FieldType = Context.getBaseElementType(F->getType());
9244 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9245 CXXConstructorDecl *Constructor =
9246 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009247 // If this is a deleted function, add it anyway. This might be conformant
9248 // with the standard. This might not. I'm not sure. It might not matter.
9249 // In particular, the problem is that this function never gets called. It
9250 // might just be ill-formed because this function attempts to refer to
9251 // a deleted function here.
9252 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009253 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009254 }
9255 }
9256
9257 return ExceptSpec;
9258}
9259
9260CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9261 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009262 // C++11 [class.copy]p9:
9263 // If the definition of a class X does not explicitly declare a move
9264 // constructor, one will be implicitly declared as defaulted if and only if:
9265 //
9266 // - [first 4 bullets]
9267 assert(ClassDecl->needsImplicitMoveConstructor());
9268
Richard Smithafb49182012-11-29 01:34:07 +00009269 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9270 if (DSM.isAlreadyBeingDeclared())
9271 return 0;
9272
Richard Smith1c931be2012-04-02 18:40:40 +00009273 // [Checked after we build the declaration]
9274 // - the move assignment operator would not be implicitly defined as
9275 // deleted,
9276
9277 // [DR1402]:
9278 // - each of X's non-static data members and direct or virtual base classes
9279 // has a type that either has a move constructor or is trivially copyable.
9280 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9281 ClassDecl->setFailedImplicitMoveConstructor();
9282 return 0;
9283 }
9284
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009285 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9286 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009287
Richard Smith7756afa2012-06-10 05:43:50 +00009288 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9289 CXXMoveConstructor,
9290 false);
9291
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009292 DeclarationName Name
9293 = Context.DeclarationNames.getCXXConstructorName(
9294 Context.getCanonicalType(ClassType));
9295 SourceLocation ClassLoc = ClassDecl->getLocation();
9296 DeclarationNameInfo NameInfo(Name, ClassLoc);
9297
9298 // C++0x [class.copy]p11:
9299 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009300 // member of its class.
9301 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009302 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009303 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009304 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009305 MoveConstructor->setAccess(AS_public);
9306 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009307
Richard Smithb9d0b762012-07-27 04:22:15 +00009308 // Build an exception specification pointing back at this member.
9309 FunctionProtoType::ExtProtoInfo EPI;
9310 EPI.ExceptionSpecType = EST_Unevaluated;
9311 EPI.ExceptionSpecDecl = MoveConstructor;
9312 MoveConstructor->setType(
9313 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9314
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009315 // Add the parameter to the constructor.
9316 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9317 ClassLoc, ClassLoc,
9318 /*IdentifierInfo=*/0,
9319 ArgType, /*TInfo=*/0,
9320 SC_None,
9321 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009322 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009323
Richard Smithbc2a35d2012-12-08 08:32:28 +00009324 MoveConstructor->setTrivial(
9325 ClassDecl->needsOverloadResolutionForMoveConstructor()
9326 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9327 : ClassDecl->hasTrivialMoveConstructor());
9328
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009329 // C++0x [class.copy]p9:
9330 // If the definition of a class X does not explicitly declare a move
9331 // constructor, one will be implicitly declared as defaulted if and only if:
9332 // [...]
9333 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009334 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009335 // Cache this result so that we don't try to generate this over and over
9336 // on every lookup, leaking memory and wasting time.
9337 ClassDecl->setFailedImplicitMoveConstructor();
9338 return 0;
9339 }
9340
9341 // Note that we have declared this constructor.
9342 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9343
9344 if (Scope *S = getScopeForContext(ClassDecl))
9345 PushOnScopeChains(MoveConstructor, S, false);
9346 ClassDecl->addDecl(MoveConstructor);
9347
9348 return MoveConstructor;
9349}
9350
9351void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9352 CXXConstructorDecl *MoveConstructor) {
9353 assert((MoveConstructor->isDefaulted() &&
9354 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009355 !MoveConstructor->doesThisDeclarationHaveABody() &&
9356 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009357 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9358
9359 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9360 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9361
Eli Friedman9a14db32012-10-18 20:14:08 +00009362 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009363 DiagnosticErrorTrap Trap(Diags);
9364
9365 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
9366 Trap.hasErrorOccurred()) {
9367 Diag(CurrentLocation, diag::note_member_synthesized_at)
9368 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9369 MoveConstructor->setInvalidDecl();
9370 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009371 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009372 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9373 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009374 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009375 /*isStmtExpr=*/false)
9376 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009377 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009378 }
9379
9380 MoveConstructor->setUsed();
9381
9382 if (ASTMutationListener *L = getASTMutationListener()) {
9383 L->CompletedImplicitDefinition(MoveConstructor);
9384 }
9385}
9386
Douglas Gregore4e68d42012-02-15 19:33:52 +00009387bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9388 return FD->isDeleted() &&
9389 (FD->isDefaulted() || FD->isImplicit()) &&
9390 isa<CXXMethodDecl>(FD);
9391}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009392
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009393/// \brief Mark the call operator of the given lambda closure type as "used".
9394static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9395 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009396 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009397 Lambda->lookup(
9398 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009399 CallOperator->setReferenced();
9400 CallOperator->setUsed();
9401}
9402
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009403void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9404 SourceLocation CurrentLocation,
9405 CXXConversionDecl *Conv)
9406{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009407 CXXRecordDecl *Lambda = Conv->getParent();
9408
9409 // Make sure that the lambda call operator is marked used.
9410 markLambdaCallOperatorUsed(*this, Lambda);
9411
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009412 Conv->setUsed();
9413
Eli Friedman9a14db32012-10-18 20:14:08 +00009414 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009415 DiagnosticErrorTrap Trap(Diags);
9416
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009417 // Return the address of the __invoke function.
9418 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9419 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009420 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009421 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9422 VK_LValue, Conv->getLocation()).take();
9423 assert(FunctionRef && "Can't refer to __invoke function?");
9424 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9425 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
9426 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009427 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009428
9429 // Fill in the __invoke function with a dummy implementation. IR generation
9430 // will fill in the actual details.
9431 Invoke->setUsed();
9432 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009433 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009434
9435 if (ASTMutationListener *L = getASTMutationListener()) {
9436 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009437 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009438 }
9439}
9440
9441void Sema::DefineImplicitLambdaToBlockPointerConversion(
9442 SourceLocation CurrentLocation,
9443 CXXConversionDecl *Conv)
9444{
9445 Conv->setUsed();
9446
Eli Friedman9a14db32012-10-18 20:14:08 +00009447 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009448 DiagnosticErrorTrap Trap(Diags);
9449
Douglas Gregorac1303e2012-02-22 05:02:47 +00009450 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009451 Expr *This = ActOnCXXThis(CurrentLocation).take();
9452 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009453
Eli Friedman23f02672012-03-01 04:01:32 +00009454 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9455 Conv->getLocation(),
9456 Conv, DerefThis);
9457
9458 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9459 // behavior. Note that only the general conversion function does this
9460 // (since it's unusable otherwise); in the case where we inline the
9461 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009462 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009463 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9464 CK_CopyAndAutoreleaseBlockObject,
9465 BuildBlock.get(), 0, VK_RValue);
9466
9467 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009468 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009469 Conv->setInvalidDecl();
9470 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009471 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009472
Douglas Gregorac1303e2012-02-22 05:02:47 +00009473 // Create the return statement that returns the block from the conversion
9474 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009475 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009476 if (Return.isInvalid()) {
9477 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9478 Conv->setInvalidDecl();
9479 return;
9480 }
9481
9482 // Set the body of the conversion function.
9483 Stmt *ReturnS = Return.take();
9484 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9485 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009486 Conv->getLocation()));
9487
Douglas Gregorac1303e2012-02-22 05:02:47 +00009488 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009489 if (ASTMutationListener *L = getASTMutationListener()) {
9490 L->CompletedImplicitDefinition(Conv);
9491 }
9492}
9493
Douglas Gregorf52757d2012-03-10 06:53:13 +00009494/// \brief Determine whether the given list arguments contains exactly one
9495/// "real" (non-default) argument.
9496static bool hasOneRealArgument(MultiExprArg Args) {
9497 switch (Args.size()) {
9498 case 0:
9499 return false;
9500
9501 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009502 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009503 return false;
9504
9505 // fall through
9506 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009507 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009508 }
9509
9510 return false;
9511}
9512
John McCall60d7b3a2010-08-24 06:29:42 +00009513ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009514Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009515 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009516 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009517 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009518 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009519 unsigned ConstructKind,
9520 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009521 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009522
Douglas Gregor2f599792010-04-02 18:24:57 +00009523 // C++0x [class.copy]p34:
9524 // When certain criteria are met, an implementation is allowed to
9525 // omit the copy/move construction of a class object, even if the
9526 // copy/move constructor and/or destructor for the object have
9527 // side effects. [...]
9528 // - when a temporary class object that has not been bound to a
9529 // reference (12.2) would be copied/moved to a class object
9530 // with the same cv-unqualified type, the copy/move operation
9531 // can be omitted by constructing the temporary object
9532 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009533 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009534 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009535 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009536 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009537 }
Mike Stump1eb44332009-09-09 15:08:12 +00009538
9539 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009540 Elidable, ExprArgs, HadMultipleCandidates,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009541 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009542}
9543
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009544/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9545/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009546ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009547Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9548 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009549 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009550 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009551 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009552 unsigned ConstructKind,
9553 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009554 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009555 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009556 Constructor, Elidable, ExprArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009557 HadMultipleCandidates, /*FIXME*/false,
9558 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009559 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9560 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009561}
9562
Mike Stump1eb44332009-09-09 15:08:12 +00009563bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009564 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009565 MultiExprArg Exprs,
9566 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009567 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009568 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009569 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009570 Exprs, HadMultipleCandidates, false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009571 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009572 if (TempResult.isInvalid())
9573 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009574
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009575 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009576 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009577 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009578 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009579 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009580
Anders Carlssonfe2de492009-08-25 05:18:00 +00009581 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009582}
9583
John McCall68c6c9a2010-02-02 09:10:11 +00009584void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009585 if (VD->isInvalidDecl()) return;
9586
John McCall68c6c9a2010-02-02 09:10:11 +00009587 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009588 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009589 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009590 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009591
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009592 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009593 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009594 CheckDestructorAccess(VD->getLocation(), Destructor,
9595 PDiag(diag::err_access_dtor_var)
9596 << VD->getDeclName()
9597 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009598 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009599
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009600 if (!VD->hasGlobalStorage()) return;
9601
9602 // Emit warning for non-trivial dtor in global scope (a real global,
9603 // class-static, function-static).
9604 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9605
9606 // TODO: this should be re-enabled for static locals by !CXAAtExit
9607 if (!VD->isStaticLocal())
9608 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009609}
9610
Douglas Gregor39da0b82009-09-09 23:08:42 +00009611/// \brief Given a constructor and the set of arguments provided for the
9612/// constructor, convert the arguments and add any required default arguments
9613/// to form a proper call to this constructor.
9614///
9615/// \returns true if an error occurred, false otherwise.
9616bool
9617Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9618 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009619 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009620 SmallVectorImpl<Expr*> &ConvertedArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009621 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009622 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9623 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009624 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009625
9626 const FunctionProtoType *Proto
9627 = Constructor->getType()->getAs<FunctionProtoType>();
9628 assert(Proto && "Constructor without a prototype?");
9629 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009630
9631 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009632 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009633 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009634 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009635 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009636
9637 VariadicCallType CallType =
9638 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009639 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009640 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9641 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009642 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009643 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009644
9645 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9646
Richard Smith831421f2012-06-25 20:30:08 +00009647 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9648 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009649
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009650 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009651}
9652
Anders Carlsson20d45d22009-12-12 00:32:00 +00009653static inline bool
9654CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9655 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009656 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009657 if (isa<NamespaceDecl>(DC)) {
9658 return SemaRef.Diag(FnDecl->getLocation(),
9659 diag::err_operator_new_delete_declared_in_namespace)
9660 << FnDecl->getDeclName();
9661 }
9662
9663 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009664 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009665 return SemaRef.Diag(FnDecl->getLocation(),
9666 diag::err_operator_new_delete_declared_static)
9667 << FnDecl->getDeclName();
9668 }
9669
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009670 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009671}
9672
Anders Carlsson156c78e2009-12-13 17:53:43 +00009673static inline bool
9674CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9675 CanQualType ExpectedResultType,
9676 CanQualType ExpectedFirstParamType,
9677 unsigned DependentParamTypeDiag,
9678 unsigned InvalidParamTypeDiag) {
9679 QualType ResultType =
9680 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9681
9682 // Check that the result type is not dependent.
9683 if (ResultType->isDependentType())
9684 return SemaRef.Diag(FnDecl->getLocation(),
9685 diag::err_operator_new_delete_dependent_result_type)
9686 << FnDecl->getDeclName() << ExpectedResultType;
9687
9688 // Check that the result type is what we expect.
9689 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9690 return SemaRef.Diag(FnDecl->getLocation(),
9691 diag::err_operator_new_delete_invalid_result_type)
9692 << FnDecl->getDeclName() << ExpectedResultType;
9693
9694 // A function template must have at least 2 parameters.
9695 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9696 return SemaRef.Diag(FnDecl->getLocation(),
9697 diag::err_operator_new_delete_template_too_few_parameters)
9698 << FnDecl->getDeclName();
9699
9700 // The function decl must have at least 1 parameter.
9701 if (FnDecl->getNumParams() == 0)
9702 return SemaRef.Diag(FnDecl->getLocation(),
9703 diag::err_operator_new_delete_too_few_parameters)
9704 << FnDecl->getDeclName();
9705
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009706 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009707 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9708 if (FirstParamType->isDependentType())
9709 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9710 << FnDecl->getDeclName() << ExpectedFirstParamType;
9711
9712 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009713 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009714 ExpectedFirstParamType)
9715 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9716 << FnDecl->getDeclName() << ExpectedFirstParamType;
9717
9718 return false;
9719}
9720
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009721static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009722CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009723 // C++ [basic.stc.dynamic.allocation]p1:
9724 // A program is ill-formed if an allocation function is declared in a
9725 // namespace scope other than global scope or declared static in global
9726 // scope.
9727 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9728 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009729
9730 CanQualType SizeTy =
9731 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9732
9733 // C++ [basic.stc.dynamic.allocation]p1:
9734 // The return type shall be void*. The first parameter shall have type
9735 // std::size_t.
9736 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9737 SizeTy,
9738 diag::err_operator_new_dependent_param_type,
9739 diag::err_operator_new_param_type))
9740 return true;
9741
9742 // C++ [basic.stc.dynamic.allocation]p1:
9743 // The first parameter shall not have an associated default argument.
9744 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009745 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009746 diag::err_operator_new_default_arg)
9747 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9748
9749 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009750}
9751
9752static bool
Richard Smith444d3842012-10-20 08:26:51 +00009753CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009754 // C++ [basic.stc.dynamic.deallocation]p1:
9755 // A program is ill-formed if deallocation functions are declared in a
9756 // namespace scope other than global scope or declared static in global
9757 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009758 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9759 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009760
9761 // C++ [basic.stc.dynamic.deallocation]p2:
9762 // Each deallocation function shall return void and its first parameter
9763 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009764 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9765 SemaRef.Context.VoidPtrTy,
9766 diag::err_operator_delete_dependent_param_type,
9767 diag::err_operator_delete_param_type))
9768 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009769
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009770 return false;
9771}
9772
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009773/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9774/// of this overloaded operator is well-formed. If so, returns false;
9775/// otherwise, emits appropriate diagnostics and returns true.
9776bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009777 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009778 "Expected an overloaded operator declaration");
9779
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009780 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9781
Mike Stump1eb44332009-09-09 15:08:12 +00009782 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009783 // The allocation and deallocation functions, operator new,
9784 // operator new[], operator delete and operator delete[], are
9785 // described completely in 3.7.3. The attributes and restrictions
9786 // found in the rest of this subclause do not apply to them unless
9787 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009788 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009789 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009790
Anders Carlssona3ccda52009-12-12 00:26:23 +00009791 if (Op == OO_New || Op == OO_Array_New)
9792 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009793
9794 // C++ [over.oper]p6:
9795 // An operator function shall either be a non-static member
9796 // function or be a non-member function and have at least one
9797 // parameter whose type is a class, a reference to a class, an
9798 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009799 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9800 if (MethodDecl->isStatic())
9801 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009802 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009803 } else {
9804 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009805 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9806 ParamEnd = FnDecl->param_end();
9807 Param != ParamEnd; ++Param) {
9808 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009809 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9810 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009811 ClassOrEnumParam = true;
9812 break;
9813 }
9814 }
9815
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009816 if (!ClassOrEnumParam)
9817 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009818 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009819 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009820 }
9821
9822 // C++ [over.oper]p8:
9823 // An operator function cannot have default arguments (8.3.6),
9824 // except where explicitly stated below.
9825 //
Mike Stump1eb44332009-09-09 15:08:12 +00009826 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009827 // (C++ [over.call]p1).
9828 if (Op != OO_Call) {
9829 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9830 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009831 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009832 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009833 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009834 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009835 }
9836 }
9837
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009838 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9839 { false, false, false }
9840#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9841 , { Unary, Binary, MemberOnly }
9842#include "clang/Basic/OperatorKinds.def"
9843 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009844
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009845 bool CanBeUnaryOperator = OperatorUses[Op][0];
9846 bool CanBeBinaryOperator = OperatorUses[Op][1];
9847 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009848
9849 // C++ [over.oper]p8:
9850 // [...] Operator functions cannot have more or fewer parameters
9851 // than the number required for the corresponding operator, as
9852 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009853 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009854 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009855 if (Op != OO_Call &&
9856 ((NumParams == 1 && !CanBeUnaryOperator) ||
9857 (NumParams == 2 && !CanBeBinaryOperator) ||
9858 (NumParams < 1) || (NumParams > 2))) {
9859 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009860 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009861 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009862 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009863 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009864 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009865 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009866 assert(CanBeBinaryOperator &&
9867 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009868 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009869 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009870
Chris Lattner416e46f2008-11-21 07:57:12 +00009871 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009872 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009873 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009874
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009875 // Overloaded operators other than operator() cannot be variadic.
9876 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009877 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009878 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009879 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009880 }
9881
9882 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009883 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9884 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009885 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009886 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009887 }
9888
9889 // C++ [over.inc]p1:
9890 // The user-defined function called operator++ implements the
9891 // prefix and postfix ++ operator. If this function is a member
9892 // function with no parameters, or a non-member function with one
9893 // parameter of class or enumeration type, it defines the prefix
9894 // increment operator ++ for objects of that type. If the function
9895 // is a member function with one parameter (which shall be of type
9896 // int) or a non-member function with two parameters (the second
9897 // of which shall be of type int), it defines the postfix
9898 // increment operator ++ for objects of that type.
9899 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9900 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9901 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009902 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009903 ParamIsInt = BT->getKind() == BuiltinType::Int;
9904
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009905 if (!ParamIsInt)
9906 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009907 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009908 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009909 }
9910
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009911 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009912}
Chris Lattner5a003a42008-12-17 07:09:26 +00009913
Sean Hunta6c058d2010-01-13 09:01:02 +00009914/// CheckLiteralOperatorDeclaration - Check whether the declaration
9915/// of this literal operator function is well-formed. If so, returns
9916/// false; otherwise, emits appropriate diagnostics and returns true.
9917bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009918 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009919 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9920 << FnDecl->getDeclName();
9921 return true;
9922 }
9923
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009924 if (FnDecl->isExternC()) {
9925 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9926 return true;
9927 }
9928
Sean Hunta6c058d2010-01-13 09:01:02 +00009929 bool Valid = false;
9930
Richard Smith36f5cfe2012-03-09 08:00:36 +00009931 // This might be the definition of a literal operator template.
9932 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9933 // This might be a specialization of a literal operator template.
9934 if (!TpDecl)
9935 TpDecl = FnDecl->getPrimaryTemplate();
9936
Sean Hunt216c2782010-04-07 23:11:06 +00009937 // template <char...> type operator "" name() is the only valid template
9938 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009939 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009940 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009941 // Must have only one template parameter
9942 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9943 if (Params->size() == 1) {
9944 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009945 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009946
Sean Hunt216c2782010-04-07 23:11:06 +00009947 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009948 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9949 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9950 Valid = true;
9951 }
9952 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009953 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009954 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009955 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9956
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009957 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009958
Sean Hunt30019c02010-04-07 22:57:35 +00009959 // unsigned long long int, long double, and any character type are allowed
9960 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009961 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9962 Context.hasSameType(T, Context.LongDoubleTy) ||
9963 Context.hasSameType(T, Context.CharTy) ||
9964 Context.hasSameType(T, Context.WCharTy) ||
9965 Context.hasSameType(T, Context.Char16Ty) ||
9966 Context.hasSameType(T, Context.Char32Ty)) {
9967 if (++Param == FnDecl->param_end())
9968 Valid = true;
9969 goto FinishedParams;
9970 }
9971
Sean Hunt30019c02010-04-07 22:57:35 +00009972 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009973 const PointerType *PT = T->getAs<PointerType>();
9974 if (!PT)
9975 goto FinishedParams;
9976 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009977 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009978 goto FinishedParams;
9979 T = T.getUnqualifiedType();
9980
9981 // Move on to the second parameter;
9982 ++Param;
9983
9984 // If there is no second parameter, the first must be a const char *
9985 if (Param == FnDecl->param_end()) {
9986 if (Context.hasSameType(T, Context.CharTy))
9987 Valid = true;
9988 goto FinishedParams;
9989 }
9990
9991 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9992 // are allowed as the first parameter to a two-parameter function
9993 if (!(Context.hasSameType(T, Context.CharTy) ||
9994 Context.hasSameType(T, Context.WCharTy) ||
9995 Context.hasSameType(T, Context.Char16Ty) ||
9996 Context.hasSameType(T, Context.Char32Ty)))
9997 goto FinishedParams;
9998
9999 // The second and final parameter must be an std::size_t
10000 T = (*Param)->getType().getUnqualifiedType();
10001 if (Context.hasSameType(T, Context.getSizeType()) &&
10002 ++Param == FnDecl->param_end())
10003 Valid = true;
10004 }
10005
10006 // FIXME: This diagnostic is absolutely terrible.
10007FinishedParams:
10008 if (!Valid) {
10009 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10010 << FnDecl->getDeclName();
10011 return true;
10012 }
10013
Richard Smitha9e88b22012-03-09 08:16:22 +000010014 // A parameter-declaration-clause containing a default argument is not
10015 // equivalent to any of the permitted forms.
10016 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10017 ParamEnd = FnDecl->param_end();
10018 Param != ParamEnd; ++Param) {
10019 if ((*Param)->hasDefaultArg()) {
10020 Diag((*Param)->getDefaultArgRange().getBegin(),
10021 diag::err_literal_operator_default_argument)
10022 << (*Param)->getDefaultArgRange();
10023 break;
10024 }
10025 }
10026
Richard Smith2fb4ae32012-03-08 02:39:21 +000010027 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010028 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10029 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010030 // C++11 [usrlit.suffix]p1:
10031 // Literal suffix identifiers that do not start with an underscore
10032 // are reserved for future standardization.
10033 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010034 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010035
Sean Hunta6c058d2010-01-13 09:01:02 +000010036 return false;
10037}
10038
Douglas Gregor074149e2009-01-05 19:45:36 +000010039/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10040/// linkage specification, including the language and (if present)
10041/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10042/// the location of the language string literal, which is provided
10043/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10044/// the '{' brace. Otherwise, this linkage specification does not
10045/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010046Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10047 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010048 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010049 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010050 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010051 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010052 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010053 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010054 Language = LinkageSpecDecl::lang_cxx;
10055 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010056 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010057 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010058 }
Mike Stump1eb44332009-09-09 15:08:12 +000010059
Chris Lattnercc98eac2008-12-17 07:13:27 +000010060 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010061
Douglas Gregor074149e2009-01-05 19:45:36 +000010062 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010063 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010064 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010065 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010066 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010067}
10068
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010069/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010070/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10071/// valid, it's the position of the closing '}' brace in a linkage
10072/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010073Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010074 Decl *LinkageSpec,
10075 SourceLocation RBraceLoc) {
10076 if (LinkageSpec) {
10077 if (RBraceLoc.isValid()) {
10078 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10079 LSDecl->setRBraceLoc(RBraceLoc);
10080 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010081 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010082 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010083 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010084}
10085
Douglas Gregord308e622009-05-18 20:51:54 +000010086/// \brief Perform semantic analysis for the variable declaration that
10087/// occurs within a C++ catch clause, returning the newly-created
10088/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010089VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010090 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010091 SourceLocation StartLoc,
10092 SourceLocation Loc,
10093 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010094 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010095 QualType ExDeclType = TInfo->getType();
10096
Sebastian Redl4b07b292008-12-22 19:15:10 +000010097 // Arrays and functions decay.
10098 if (ExDeclType->isArrayType())
10099 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10100 else if (ExDeclType->isFunctionType())
10101 ExDeclType = Context.getPointerType(ExDeclType);
10102
10103 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10104 // The exception-declaration shall not denote a pointer or reference to an
10105 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010106 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010107 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010108 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010109 Invalid = true;
10110 }
Douglas Gregord308e622009-05-18 20:51:54 +000010111
Sebastian Redl4b07b292008-12-22 19:15:10 +000010112 QualType BaseType = ExDeclType;
10113 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010114 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010115 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010116 BaseType = Ptr->getPointeeType();
10117 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010118 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010119 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010120 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010121 BaseType = Ref->getPointeeType();
10122 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010123 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010124 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010125 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010126 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010127 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010128
Mike Stump1eb44332009-09-09 15:08:12 +000010129 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010130 RequireNonAbstractType(Loc, ExDeclType,
10131 diag::err_abstract_type_in_decl,
10132 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010133 Invalid = true;
10134
John McCall5a180392010-07-24 00:37:23 +000010135 // Only the non-fragile NeXT runtime currently supports C++ catches
10136 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010137 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010138 QualType T = ExDeclType;
10139 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10140 T = RT->getPointeeType();
10141
10142 if (T->isObjCObjectType()) {
10143 Diag(Loc, diag::err_objc_object_catch);
10144 Invalid = true;
10145 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010146 // FIXME: should this be a test for macosx-fragile specifically?
10147 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010148 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010149 }
10150 }
10151
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010152 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10153 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010154 ExDecl->setExceptionVariable(true);
10155
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010156 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010157 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010158 Invalid = true;
10159
Douglas Gregorc41b8782011-07-06 18:14:43 +000010160 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010161 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +000010162 // C++ [except.handle]p16:
10163 // The object declared in an exception-declaration or, if the
10164 // exception-declaration does not specify a name, a temporary (12.2) is
10165 // copy-initialized (8.5) from the exception object. [...]
10166 // The object is destroyed when the handler exits, after the destruction
10167 // of any automatic objects initialized within the handler.
10168 //
10169 // We just pretend to initialize the object with itself, then make sure
10170 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010171 QualType initType = ExDeclType;
10172
10173 InitializedEntity entity =
10174 InitializedEntity::InitializeVariable(ExDecl);
10175 InitializationKind initKind =
10176 InitializationKind::CreateCopy(Loc, SourceLocation());
10177
10178 Expr *opaqueValue =
10179 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10180 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10181 ExprResult result = sequence.Perform(*this, entity, initKind,
10182 MultiExprArg(&opaqueValue, 1));
10183 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010184 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010185 else {
10186 // If the constructor used was non-trivial, set this as the
10187 // "initializer".
10188 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10189 if (!construct->getConstructor()->isTrivial()) {
10190 Expr *init = MaybeCreateExprWithCleanups(construct);
10191 ExDecl->setInit(init);
10192 }
10193
10194 // And make sure it's destructable.
10195 FinalizeVarWithDestructor(ExDecl, recordType);
10196 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010197 }
10198 }
10199
Douglas Gregord308e622009-05-18 20:51:54 +000010200 if (Invalid)
10201 ExDecl->setInvalidDecl();
10202
10203 return ExDecl;
10204}
10205
10206/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10207/// handler.
John McCalld226f652010-08-21 09:40:31 +000010208Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010209 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010210 bool Invalid = D.isInvalidType();
10211
10212 // Check for unexpanded parameter packs.
10213 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10214 UPPC_ExceptionType)) {
10215 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10216 D.getIdentifierLoc());
10217 Invalid = true;
10218 }
10219
Sebastian Redl4b07b292008-12-22 19:15:10 +000010220 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010221 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010222 LookupOrdinaryName,
10223 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010224 // The scope should be freshly made just for us. There is just no way
10225 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010226 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010227 if (PrevDecl->isTemplateParameter()) {
10228 // Maybe we will complain about the shadowed template parameter.
10229 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010230 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010231 }
10232 }
10233
Chris Lattnereaaebc72009-04-25 08:06:05 +000010234 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010235 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10236 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010237 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010238 }
10239
Douglas Gregor83cb9422010-09-09 17:09:21 +000010240 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010241 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010242 D.getIdentifierLoc(),
10243 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010244 if (Invalid)
10245 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010246
Sebastian Redl4b07b292008-12-22 19:15:10 +000010247 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010248 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010249 PushOnScopeChains(ExDecl, S);
10250 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010251 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010252
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010253 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010254 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010255}
Anders Carlssonfb311762009-03-14 00:25:26 +000010256
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010257Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010258 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010259 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010260 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010261 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010262
Richard Smithe3f470a2012-07-11 22:37:56 +000010263 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10264 return 0;
10265
10266 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10267 AssertMessage, RParenLoc, false);
10268}
10269
10270Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10271 Expr *AssertExpr,
10272 StringLiteral *AssertMessage,
10273 SourceLocation RParenLoc,
10274 bool Failed) {
10275 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10276 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010277 // In a static_assert-declaration, the constant-expression shall be a
10278 // constant expression that can be contextually converted to bool.
10279 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10280 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010281 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010282
Richard Smithdaaefc52011-12-14 23:32:26 +000010283 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010284 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010285 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010286 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010287 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010288
Richard Smithe3f470a2012-07-11 22:37:56 +000010289 if (!Failed && !Cond) {
Richard Smith0cc323c2012-03-05 23:20:05 +000010290 llvm::SmallString<256> MsgBuffer;
10291 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010292 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010293 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010294 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010295 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010296 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010297 }
Mike Stump1eb44332009-09-09 15:08:12 +000010298
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010299 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010300 AssertExpr, AssertMessage, RParenLoc,
10301 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010302
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010303 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010304 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010305}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010306
Douglas Gregor1d869352010-04-07 16:53:43 +000010307/// \brief Perform semantic analysis of the given friend type declaration.
10308///
10309/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010310FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010311 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010312 TypeSourceInfo *TSInfo) {
10313 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10314
10315 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010316 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010317
Richard Smith6b130222011-10-18 21:39:00 +000010318 // C++03 [class.friend]p2:
10319 // An elaborated-type-specifier shall be used in a friend declaration
10320 // for a class.*
10321 //
10322 // * The class-key of the elaborated-type-specifier is required.
10323 if (!ActiveTemplateInstantiations.empty()) {
10324 // Do not complain about the form of friend template types during
10325 // template instantiation; we will already have complained when the
10326 // template was declared.
10327 } else if (!T->isElaboratedTypeSpecifier()) {
10328 // If we evaluated the type to a record type, suggest putting
10329 // a tag in front.
10330 if (const RecordType *RT = T->getAs<RecordType>()) {
10331 RecordDecl *RD = RT->getDecl();
10332
10333 std::string InsertionText = std::string(" ") + RD->getKindName();
10334
10335 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010336 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010337 diag::warn_cxx98_compat_unelaborated_friend_type :
10338 diag::ext_unelaborated_friend_type)
10339 << (unsigned) RD->getTagKind()
10340 << T
10341 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10342 InsertionText);
10343 } else {
10344 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +000010345 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010346 diag::warn_cxx98_compat_nonclass_type_friend :
10347 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010348 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010349 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010350 }
Richard Smith6b130222011-10-18 21:39:00 +000010351 } else if (T->getAs<EnumType>()) {
10352 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +000010353 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010354 diag::warn_cxx98_compat_enum_friend :
10355 diag::ext_enum_friend)
10356 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010357 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010358 }
10359
Richard Smithd6f80da2012-09-20 01:31:00 +000010360 // C++11 [class.friend]p3:
10361 // A friend declaration that does not declare a function shall have one
10362 // of the following forms:
10363 // friend elaborated-type-specifier ;
10364 // friend simple-type-specifier ;
10365 // friend typename-specifier ;
10366 if (getLangOpts().CPlusPlus0x && LocStart != FriendLoc)
10367 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10368
Douglas Gregor06245bf2010-04-07 17:57:12 +000010369 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010370 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010371 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010372 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010373}
10374
John McCall9a34edb2010-10-19 01:40:49 +000010375/// Handle a friend tag declaration where the scope specifier was
10376/// templated.
10377Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10378 unsigned TagSpec, SourceLocation TagLoc,
10379 CXXScopeSpec &SS,
10380 IdentifierInfo *Name, SourceLocation NameLoc,
10381 AttributeList *Attr,
10382 MultiTemplateParamsArg TempParamLists) {
10383 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10384
10385 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010386 bool Invalid = false;
10387
10388 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010389 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010390 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010391 TempParamLists.size(),
10392 /*friend*/ true,
10393 isExplicitSpecialization,
10394 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010395 if (TemplateParams->size() > 0) {
10396 // This is a declaration of a class template.
10397 if (Invalid)
10398 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010399
Eric Christopher4110e132011-07-21 05:34:24 +000010400 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10401 SS, Name, NameLoc, Attr,
10402 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010403 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010404 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010405 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010406 } else {
10407 // The "template<>" header is extraneous.
10408 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10409 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10410 isExplicitSpecialization = true;
10411 }
10412 }
10413
10414 if (Invalid) return 0;
10415
John McCall9a34edb2010-10-19 01:40:49 +000010416 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010417 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010418 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010419 isAllExplicitSpecializations = false;
10420 break;
10421 }
10422 }
10423
10424 // FIXME: don't ignore attributes.
10425
10426 // If it's explicit specializations all the way down, just forget
10427 // about the template header and build an appropriate non-templated
10428 // friend. TODO: for source fidelity, remember the headers.
10429 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010430 if (SS.isEmpty()) {
10431 bool Owned = false;
10432 bool IsDependent = false;
10433 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10434 Attr, AS_public,
10435 /*ModulePrivateLoc=*/SourceLocation(),
10436 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010437 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010438 /*ScopedEnumUsesClassTag=*/false,
10439 /*UnderlyingType=*/TypeResult());
10440 }
10441
Douglas Gregor2494dd02011-03-01 01:34:45 +000010442 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010443 ElaboratedTypeKeyword Keyword
10444 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010445 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010446 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010447 if (T.isNull())
10448 return 0;
10449
10450 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10451 if (isa<DependentNameType>(T)) {
10452 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010453 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010454 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010455 TL.setNameLoc(NameLoc);
10456 } else {
10457 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010458 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010459 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010460 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10461 }
10462
10463 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10464 TSI, FriendLoc);
10465 Friend->setAccess(AS_public);
10466 CurContext->addDecl(Friend);
10467 return Friend;
10468 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010469
10470 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10471
10472
John McCall9a34edb2010-10-19 01:40:49 +000010473
10474 // Handle the case of a templated-scope friend class. e.g.
10475 // template <class T> class A<T>::B;
10476 // FIXME: we don't support these right now.
10477 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10478 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10479 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10480 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010481 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010482 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010483 TL.setNameLoc(NameLoc);
10484
10485 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10486 TSI, FriendLoc);
10487 Friend->setAccess(AS_public);
10488 Friend->setUnsupportedFriend(true);
10489 CurContext->addDecl(Friend);
10490 return Friend;
10491}
10492
10493
John McCalldd4a3b02009-09-16 22:47:08 +000010494/// Handle a friend type declaration. This works in tandem with
10495/// ActOnTag.
10496///
10497/// Notes on friend class templates:
10498///
10499/// We generally treat friend class declarations as if they were
10500/// declaring a class. So, for example, the elaborated type specifier
10501/// in a friend declaration is required to obey the restrictions of a
10502/// class-head (i.e. no typedefs in the scope chain), template
10503/// parameters are required to match up with simple template-ids, &c.
10504/// However, unlike when declaring a template specialization, it's
10505/// okay to refer to a template specialization without an empty
10506/// template parameter declaration, e.g.
10507/// friend class A<T>::B<unsigned>;
10508/// We permit this as a special case; if there are any template
10509/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010510/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010511Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010512 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010513 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010514
10515 assert(DS.isFriendSpecified());
10516 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10517
John McCalldd4a3b02009-09-16 22:47:08 +000010518 // Try to convert the decl specifier to a type. This works for
10519 // friend templates because ActOnTag never produces a ClassTemplateDecl
10520 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010521 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010522 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10523 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010524 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010525 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010526
Douglas Gregor6ccab972010-12-16 01:14:37 +000010527 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10528 return 0;
10529
John McCalldd4a3b02009-09-16 22:47:08 +000010530 // This is definitely an error in C++98. It's probably meant to
10531 // be forbidden in C++0x, too, but the specification is just
10532 // poorly written.
10533 //
10534 // The problem is with declarations like the following:
10535 // template <T> friend A<T>::foo;
10536 // where deciding whether a class C is a friend or not now hinges
10537 // on whether there exists an instantiation of A that causes
10538 // 'foo' to equal C. There are restrictions on class-heads
10539 // (which we declare (by fiat) elaborated friend declarations to
10540 // be) that makes this tractable.
10541 //
10542 // FIXME: handle "template <> friend class A<T>;", which
10543 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010544 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010545 Diag(Loc, diag::err_tagless_friend_type_template)
10546 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010547 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010548 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010549
John McCall02cace72009-08-28 07:59:38 +000010550 // C++98 [class.friend]p1: A friend of a class is a function
10551 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010552 // This is fixed in DR77, which just barely didn't make the C++03
10553 // deadline. It's also a very silly restriction that seriously
10554 // affects inner classes and which nobody else seems to implement;
10555 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010556 //
10557 // But note that we could warn about it: it's always useless to
10558 // friend one of your own members (it's not, however, worthless to
10559 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010560
John McCalldd4a3b02009-09-16 22:47:08 +000010561 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010562 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010563 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010564 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010565 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010566 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010567 DS.getFriendSpecLoc());
10568 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010569 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010570
10571 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010572 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010573
John McCalldd4a3b02009-09-16 22:47:08 +000010574 D->setAccess(AS_public);
10575 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010576
John McCalld226f652010-08-21 09:40:31 +000010577 return D;
John McCall02cace72009-08-28 07:59:38 +000010578}
10579
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010580Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010581 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010582 const DeclSpec &DS = D.getDeclSpec();
10583
10584 assert(DS.isFriendSpecified());
10585 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10586
10587 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010588 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010589
10590 // C++ [class.friend]p1
10591 // A friend of a class is a function or class....
10592 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010593 // It *doesn't* see through dependent types, which is correct
10594 // according to [temp.arg.type]p3:
10595 // If a declaration acquires a function type through a
10596 // type dependent on a template-parameter and this causes
10597 // a declaration that does not use the syntactic form of a
10598 // function declarator to have a function type, the program
10599 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010600 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010601 Diag(Loc, diag::err_unexpected_friend);
10602
10603 // It might be worthwhile to try to recover by creating an
10604 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010605 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010606 }
10607
10608 // C++ [namespace.memdef]p3
10609 // - If a friend declaration in a non-local class first declares a
10610 // class or function, the friend class or function is a member
10611 // of the innermost enclosing namespace.
10612 // - The name of the friend is not found by simple name lookup
10613 // until a matching declaration is provided in that namespace
10614 // scope (either before or after the class declaration granting
10615 // friendship).
10616 // - If a friend function is called, its name may be found by the
10617 // name lookup that considers functions from namespaces and
10618 // classes associated with the types of the function arguments.
10619 // - When looking for a prior declaration of a class or a function
10620 // declared as a friend, scopes outside the innermost enclosing
10621 // namespace scope are not considered.
10622
John McCall337ec3d2010-10-12 23:13:28 +000010623 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010624 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10625 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010626 assert(Name);
10627
Douglas Gregor6ccab972010-12-16 01:14:37 +000010628 // Check for unexpanded parameter packs.
10629 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10630 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10631 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10632 return 0;
10633
John McCall67d1a672009-08-06 02:15:43 +000010634 // The context we found the declaration in, or in which we should
10635 // create the declaration.
10636 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010637 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010638 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010639 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010640
John McCall337ec3d2010-10-12 23:13:28 +000010641 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010642
John McCall337ec3d2010-10-12 23:13:28 +000010643 // There are four cases here.
10644 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010645 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010646 // there as appropriate.
10647 // Recover from invalid scope qualifiers as if they just weren't there.
10648 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010649 // C++0x [namespace.memdef]p3:
10650 // If the name in a friend declaration is neither qualified nor
10651 // a template-id and the declaration is a function or an
10652 // elaborated-type-specifier, the lookup to determine whether
10653 // the entity has been previously declared shall not consider
10654 // any scopes outside the innermost enclosing namespace.
10655 // C++0x [class.friend]p11:
10656 // If a friend declaration appears in a local class and the name
10657 // specified is an unqualified name, a prior declaration is
10658 // looked up without considering scopes that are outside the
10659 // innermost enclosing non-class scope. For a friend function
10660 // declaration, if there is no prior declaration, the program is
10661 // ill-formed.
10662 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010663 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010664
John McCall29ae6e52010-10-13 05:45:15 +000010665 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010666 DC = CurContext;
10667 while (true) {
10668 // Skip class contexts. If someone can cite chapter and verse
10669 // for this behavior, that would be nice --- it's what GCC and
10670 // EDG do, and it seems like a reasonable intent, but the spec
10671 // really only says that checks for unqualified existing
10672 // declarations should stop at the nearest enclosing namespace,
10673 // not that they should only consider the nearest enclosing
10674 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010675 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010676 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010677
John McCall68263142009-11-18 22:49:29 +000010678 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010679
10680 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010681 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010682 break;
John McCall29ae6e52010-10-13 05:45:15 +000010683
John McCall8a407372010-10-14 22:22:28 +000010684 if (isTemplateId) {
10685 if (isa<TranslationUnitDecl>(DC)) break;
10686 } else {
10687 if (DC->isFileContext()) break;
10688 }
John McCall67d1a672009-08-06 02:15:43 +000010689 DC = DC->getParent();
10690 }
10691
10692 // C++ [class.friend]p1: A friend of a class is a function or
10693 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010694 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010695 // Most C++ 98 compilers do seem to give an error here, so
10696 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010697 if (!Previous.empty() && DC->Equals(CurContext))
10698 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010699 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010700 diag::warn_cxx98_compat_friend_is_member :
10701 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010702
John McCall380aaa42010-10-13 06:22:15 +000010703 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010704
Douglas Gregor883af832011-10-10 01:11:59 +000010705 // C++ [class.friend]p6:
10706 // A function can be defined in a friend declaration of a class if and
10707 // only if the class is a non-local class (9.8), the function name is
10708 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010709 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010710 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10711 }
10712
John McCall337ec3d2010-10-12 23:13:28 +000010713 // - There's a non-dependent scope specifier, in which case we
10714 // compute it and do a previous lookup there for a function
10715 // or function template.
10716 } else if (!SS.getScopeRep()->isDependent()) {
10717 DC = computeDeclContext(SS);
10718 if (!DC) return 0;
10719
10720 if (RequireCompleteDeclContext(SS, DC)) return 0;
10721
10722 LookupQualifiedName(Previous, DC);
10723
10724 // Ignore things found implicitly in the wrong scope.
10725 // TODO: better diagnostics for this case. Suggesting the right
10726 // qualified scope would be nice...
10727 LookupResult::Filter F = Previous.makeFilter();
10728 while (F.hasNext()) {
10729 NamedDecl *D = F.next();
10730 if (!DC->InEnclosingNamespaceSetOf(
10731 D->getDeclContext()->getRedeclContext()))
10732 F.erase();
10733 }
10734 F.done();
10735
10736 if (Previous.empty()) {
10737 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010738 Diag(Loc, diag::err_qualified_friend_not_found)
10739 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010740 return 0;
10741 }
10742
10743 // C++ [class.friend]p1: A friend of a class is a function or
10744 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010745 if (DC->Equals(CurContext))
10746 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010747 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010748 diag::warn_cxx98_compat_friend_is_member :
10749 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010750
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010751 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010752 // C++ [class.friend]p6:
10753 // A function can be defined in a friend declaration of a class if and
10754 // only if the class is a non-local class (9.8), the function name is
10755 // unqualified, and the function has namespace scope.
10756 SemaDiagnosticBuilder DB
10757 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10758
10759 DB << SS.getScopeRep();
10760 if (DC->isFileContext())
10761 DB << FixItHint::CreateRemoval(SS.getRange());
10762 SS.clear();
10763 }
John McCall337ec3d2010-10-12 23:13:28 +000010764
10765 // - There's a scope specifier that does not match any template
10766 // parameter lists, in which case we use some arbitrary context,
10767 // create a method or method template, and wait for instantiation.
10768 // - There's a scope specifier that does match some template
10769 // parameter lists, which we don't handle right now.
10770 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010771 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010772 // C++ [class.friend]p6:
10773 // A function can be defined in a friend declaration of a class if and
10774 // only if the class is a non-local class (9.8), the function name is
10775 // unqualified, and the function has namespace scope.
10776 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10777 << SS.getScopeRep();
10778 }
10779
John McCall337ec3d2010-10-12 23:13:28 +000010780 DC = CurContext;
10781 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010782 }
Douglas Gregor883af832011-10-10 01:11:59 +000010783
John McCall29ae6e52010-10-13 05:45:15 +000010784 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010785 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010786 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10787 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10788 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010789 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010790 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10791 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010792 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010793 }
John McCall67d1a672009-08-06 02:15:43 +000010794 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010795
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010796 // FIXME: This is an egregious hack to cope with cases where the scope stack
10797 // does not contain the declaration context, i.e., in an out-of-line
10798 // definition of a class.
10799 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10800 if (!DCScope) {
10801 FakeDCScope.setEntity(DC);
10802 DCScope = &FakeDCScope;
10803 }
10804
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010805 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010806 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010807 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010808 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010809
Douglas Gregor182ddf02009-09-28 00:08:27 +000010810 assert(ND->getDeclContext() == DC);
10811 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010812
John McCallab88d972009-08-31 22:39:49 +000010813 // Add the function declaration to the appropriate lookup tables,
10814 // adjusting the redeclarations list as necessary. We don't
10815 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010816 //
John McCallab88d972009-08-31 22:39:49 +000010817 // Also update the scope-based lookup if the target context's
10818 // lookup context is in lexical scope.
10819 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010820 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010821 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010822 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010823 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010824 }
John McCall02cace72009-08-28 07:59:38 +000010825
10826 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010827 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010828 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010829 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010830 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010831
John McCall1f2e1a92012-08-10 03:15:35 +000010832 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010833 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010834 } else {
10835 if (DC->isRecord()) CheckFriendAccess(ND);
10836
John McCall6102ca12010-10-16 06:59:13 +000010837 FunctionDecl *FD;
10838 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10839 FD = FTD->getTemplatedDecl();
10840 else
10841 FD = cast<FunctionDecl>(ND);
10842
10843 // Mark templated-scope function declarations as unsupported.
10844 if (FD->getNumTemplateParameterLists())
10845 FrD->setUnsupportedFriend(true);
10846 }
John McCall337ec3d2010-10-12 23:13:28 +000010847
John McCalld226f652010-08-21 09:40:31 +000010848 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010849}
10850
John McCalld226f652010-08-21 09:40:31 +000010851void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10852 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010853
Sebastian Redl50de12f2009-03-24 22:27:57 +000010854 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10855 if (!Fn) {
10856 Diag(DelLoc, diag::err_deleted_non_function);
10857 return;
10858 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010859 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010860 // Don't consider the implicit declaration we generate for explicit
10861 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010862 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10863 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010864 Diag(DelLoc, diag::err_deleted_decl_not_first);
10865 Diag(Prev->getLocation(), diag::note_previous_declaration);
10866 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010867 // If the declaration wasn't the first, we delete the function anyway for
10868 // recovery.
10869 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010870 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010871}
Sebastian Redl13e88542009-04-27 21:33:24 +000010872
Sean Hunte4246a62011-05-12 06:15:49 +000010873void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10874 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10875
10876 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010877 if (MD->getParent()->isDependentType()) {
10878 MD->setDefaulted();
10879 MD->setExplicitlyDefaulted();
10880 return;
10881 }
10882
Sean Hunte4246a62011-05-12 06:15:49 +000010883 CXXSpecialMember Member = getSpecialMember(MD);
10884 if (Member == CXXInvalid) {
10885 Diag(DefaultLoc, diag::err_default_special_members);
10886 return;
10887 }
10888
10889 MD->setDefaulted();
10890 MD->setExplicitlyDefaulted();
10891
Sean Huntcd10dec2011-05-23 23:14:04 +000010892 // If this definition appears within the record, do the checking when
10893 // the record is complete.
10894 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010895 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010896 // Find the uninstantiated declaration that actually had the '= default'
10897 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010898 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010899
10900 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010901 return;
10902
Richard Smithb9d0b762012-07-27 04:22:15 +000010903 CheckExplicitlyDefaultedSpecialMember(MD);
10904
Richard Smith1d28caf2012-12-11 01:14:52 +000010905 // The exception specification is needed because we are defining the
10906 // function.
10907 ResolveExceptionSpec(DefaultLoc,
10908 MD->getType()->castAs<FunctionProtoType>());
10909
Sean Hunte4246a62011-05-12 06:15:49 +000010910 switch (Member) {
10911 case CXXDefaultConstructor: {
10912 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010913 if (!CD->isInvalidDecl())
10914 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10915 break;
10916 }
10917
10918 case CXXCopyConstructor: {
10919 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010920 if (!CD->isInvalidDecl())
10921 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010922 break;
10923 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010924
Sean Hunt2b188082011-05-14 05:23:28 +000010925 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010926 if (!MD->isInvalidDecl())
10927 DefineImplicitCopyAssignment(DefaultLoc, MD);
10928 break;
10929 }
10930
Sean Huntcb45a0f2011-05-12 22:46:25 +000010931 case CXXDestructor: {
10932 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010933 if (!DD->isInvalidDecl())
10934 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010935 break;
10936 }
10937
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010938 case CXXMoveConstructor: {
10939 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010940 if (!CD->isInvalidDecl())
10941 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010942 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010943 }
Sean Hunt82713172011-05-25 23:16:36 +000010944
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010945 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010946 if (!MD->isInvalidDecl())
10947 DefineImplicitMoveAssignment(DefaultLoc, MD);
10948 break;
10949 }
10950
10951 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010952 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010953 }
10954 } else {
10955 Diag(DefaultLoc, diag::err_default_special_members);
10956 }
10957}
10958
Sebastian Redl13e88542009-04-27 21:33:24 +000010959static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010960 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010961 Stmt *SubStmt = *CI;
10962 if (!SubStmt)
10963 continue;
10964 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010965 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010966 diag::err_return_in_constructor_handler);
10967 if (!isa<Expr>(SubStmt))
10968 SearchForReturnInStmt(Self, SubStmt);
10969 }
10970}
10971
10972void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10973 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10974 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10975 SearchForReturnInStmt(*this, Handler);
10976 }
10977}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010978
Aaron Ballmanfff32482012-12-09 17:45:41 +000010979bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
10980 const CXXMethodDecl *Old) {
10981 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
10982 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
10983
10984 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
10985
10986 // If the calling conventions match, everything is fine
10987 if (NewCC == OldCC)
10988 return false;
10989
10990 // If either of the calling conventions are set to "default", we need to pick
10991 // something more sensible based on the target. This supports code where the
10992 // one method explicitly sets thiscall, and another has no explicit calling
10993 // convention.
10994 CallingConv Default =
10995 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
10996 if (NewCC == CC_Default)
10997 NewCC = Default;
10998 if (OldCC == CC_Default)
10999 OldCC = Default;
11000
11001 // If the calling conventions still don't match, then report the error
11002 if (NewCC != OldCC) {
11003 Diag(New->getLocation(),
11004 diag::err_conflicting_overriding_cc_attributes)
11005 << New->getDeclName() << New->getType() << Old->getType();
11006 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11007 return true;
11008 }
11009
11010 return false;
11011}
11012
Mike Stump1eb44332009-09-09 15:08:12 +000011013bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011014 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011015 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11016 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011017
Chandler Carruth73857792010-02-15 11:53:20 +000011018 if (Context.hasSameType(NewTy, OldTy) ||
11019 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011020 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011021
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011022 // Check if the return types are covariant
11023 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011024
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011025 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011026 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11027 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011028 NewClassTy = NewPT->getPointeeType();
11029 OldClassTy = OldPT->getPointeeType();
11030 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011031 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11032 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11033 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11034 NewClassTy = NewRT->getPointeeType();
11035 OldClassTy = OldRT->getPointeeType();
11036 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011037 }
11038 }
Mike Stump1eb44332009-09-09 15:08:12 +000011039
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011040 // The return types aren't either both pointers or references to a class type.
11041 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011042 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011043 diag::err_different_return_type_for_overriding_virtual_function)
11044 << New->getDeclName() << NewTy << OldTy;
11045 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011046
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011047 return true;
11048 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011049
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011050 // C++ [class.virtual]p6:
11051 // If the return type of D::f differs from the return type of B::f, the
11052 // class type in the return type of D::f shall be complete at the point of
11053 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011054 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11055 if (!RT->isBeingDefined() &&
11056 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011057 diag::err_covariant_return_incomplete,
11058 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011059 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011060 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011061
Douglas Gregora4923eb2009-11-16 21:35:15 +000011062 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011063 // Check if the new class derives from the old class.
11064 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11065 Diag(New->getLocation(),
11066 diag::err_covariant_return_not_derived)
11067 << New->getDeclName() << NewTy << OldTy;
11068 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11069 return true;
11070 }
Mike Stump1eb44332009-09-09 15:08:12 +000011071
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011072 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011073 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011074 diag::err_covariant_return_inaccessible_base,
11075 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11076 // FIXME: Should this point to the return type?
11077 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011078 // FIXME: this note won't trigger for delayed access control
11079 // diagnostics, and it's impossible to get an undelayed error
11080 // here from access control during the original parse because
11081 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011082 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11083 return true;
11084 }
11085 }
Mike Stump1eb44332009-09-09 15:08:12 +000011086
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011087 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011088 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011089 Diag(New->getLocation(),
11090 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011091 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011092 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11093 return true;
11094 };
Mike Stump1eb44332009-09-09 15:08:12 +000011095
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011096
11097 // The new class type must have the same or less qualifiers as the old type.
11098 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11099 Diag(New->getLocation(),
11100 diag::err_covariant_return_type_class_type_more_qualified)
11101 << New->getDeclName() << NewTy << OldTy;
11102 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11103 return true;
11104 };
Mike Stump1eb44332009-09-09 15:08:12 +000011105
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011106 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011107}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011108
Douglas Gregor4ba31362009-12-01 17:24:26 +000011109/// \brief Mark the given method pure.
11110///
11111/// \param Method the method to be marked pure.
11112///
11113/// \param InitRange the source range that covers the "0" initializer.
11114bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011115 SourceLocation EndLoc = InitRange.getEnd();
11116 if (EndLoc.isValid())
11117 Method->setRangeEnd(EndLoc);
11118
Douglas Gregor4ba31362009-12-01 17:24:26 +000011119 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11120 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011121 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011122 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011123
11124 if (!Method->isInvalidDecl())
11125 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11126 << Method->getDeclName() << InitRange;
11127 return true;
11128}
11129
Douglas Gregor552e2992012-02-21 02:22:07 +000011130/// \brief Determine whether the given declaration is a static data member.
11131static bool isStaticDataMember(Decl *D) {
11132 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11133 if (!Var)
11134 return false;
11135
11136 return Var->isStaticDataMember();
11137}
John McCall731ad842009-12-19 09:28:58 +000011138/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11139/// an initializer for the out-of-line declaration 'Dcl'. The scope
11140/// is a fresh scope pushed for just this purpose.
11141///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011142/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11143/// static data member of class X, names should be looked up in the scope of
11144/// class X.
John McCalld226f652010-08-21 09:40:31 +000011145void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011146 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011147 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011148
John McCall731ad842009-12-19 09:28:58 +000011149 // We should only get called for declarations with scope specifiers, like:
11150 // int foo::bar;
11151 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011152 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011153
11154 // If we are parsing the initializer for a static data member, push a
11155 // new expression evaluation context that is associated with this static
11156 // data member.
11157 if (isStaticDataMember(D))
11158 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011159}
11160
11161/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011162/// initializer for the out-of-line declaration 'D'.
11163void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011164 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011165 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011166
Douglas Gregor552e2992012-02-21 02:22:07 +000011167 if (isStaticDataMember(D))
11168 PopExpressionEvaluationContext();
11169
John McCall731ad842009-12-19 09:28:58 +000011170 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011171 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011172}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011173
11174/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11175/// C++ if/switch/while/for statement.
11176/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011177DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011178 // C++ 6.4p2:
11179 // The declarator shall not specify a function or an array.
11180 // The type-specifier-seq shall not contain typedef and shall not declare a
11181 // new class or enumeration.
11182 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11183 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011184
11185 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011186 if (!Dcl)
11187 return true;
11188
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011189 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11190 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011191 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011192 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011193 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011194
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011195 return Dcl;
11196}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011197
Douglas Gregordfe65432011-07-28 19:11:31 +000011198void Sema::LoadExternalVTableUses() {
11199 if (!ExternalSource)
11200 return;
11201
11202 SmallVector<ExternalVTableUse, 4> VTables;
11203 ExternalSource->ReadUsedVTables(VTables);
11204 SmallVector<VTableUse, 4> NewUses;
11205 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11206 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11207 = VTablesUsed.find(VTables[I].Record);
11208 // Even if a definition wasn't required before, it may be required now.
11209 if (Pos != VTablesUsed.end()) {
11210 if (!Pos->second && VTables[I].DefinitionRequired)
11211 Pos->second = true;
11212 continue;
11213 }
11214
11215 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11216 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11217 }
11218
11219 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11220}
11221
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011222void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11223 bool DefinitionRequired) {
11224 // Ignore any vtable uses in unevaluated operands or for classes that do
11225 // not have a vtable.
11226 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11227 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011228 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011229 return;
11230
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011231 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011232 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011233 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11234 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11235 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11236 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011237 // If we already had an entry, check to see if we are promoting this vtable
11238 // to required a definition. If so, we need to reappend to the VTableUses
11239 // list, since we may have already processed the first entry.
11240 if (DefinitionRequired && !Pos.first->second) {
11241 Pos.first->second = true;
11242 } else {
11243 // Otherwise, we can early exit.
11244 return;
11245 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011246 }
11247
11248 // Local classes need to have their virtual members marked
11249 // immediately. For all other classes, we mark their virtual members
11250 // at the end of the translation unit.
11251 if (Class->isLocalClass())
11252 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011253 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011254 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011255}
11256
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011257bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011258 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011259 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011260 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011261
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011262 // Note: The VTableUses vector could grow as a result of marking
11263 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011264 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011265 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011266 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011267 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011268 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011269 if (!Class)
11270 continue;
11271
11272 SourceLocation Loc = VTableUses[I].second;
11273
Richard Smithb9d0b762012-07-27 04:22:15 +000011274 bool DefineVTable = true;
11275
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011276 // If this class has a key function, but that key function is
11277 // defined in another translation unit, we don't need to emit the
11278 // vtable even though we're using it.
11279 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011280 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011281 switch (KeyFunction->getTemplateSpecializationKind()) {
11282 case TSK_Undeclared:
11283 case TSK_ExplicitSpecialization:
11284 case TSK_ExplicitInstantiationDeclaration:
11285 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011286 DefineVTable = false;
11287 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011288
11289 case TSK_ExplicitInstantiationDefinition:
11290 case TSK_ImplicitInstantiation:
11291 // We will be instantiating the key function.
11292 break;
11293 }
11294 } else if (!KeyFunction) {
11295 // If we have a class with no key function that is the subject
11296 // of an explicit instantiation declaration, suppress the
11297 // vtable; it will live with the explicit instantiation
11298 // definition.
11299 bool IsExplicitInstantiationDeclaration
11300 = Class->getTemplateSpecializationKind()
11301 == TSK_ExplicitInstantiationDeclaration;
11302 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11303 REnd = Class->redecls_end();
11304 R != REnd; ++R) {
11305 TemplateSpecializationKind TSK
11306 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11307 if (TSK == TSK_ExplicitInstantiationDeclaration)
11308 IsExplicitInstantiationDeclaration = true;
11309 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11310 IsExplicitInstantiationDeclaration = false;
11311 break;
11312 }
11313 }
11314
11315 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011316 DefineVTable = false;
11317 }
11318
11319 // The exception specifications for all virtual members may be needed even
11320 // if we are not providing an authoritative form of the vtable in this TU.
11321 // We may choose to emit it available_externally anyway.
11322 if (!DefineVTable) {
11323 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11324 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011325 }
11326
11327 // Mark all of the virtual members of this class as referenced, so
11328 // that we can build a vtable. Then, tell the AST consumer that a
11329 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011330 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011331 MarkVirtualMembersReferenced(Loc, Class);
11332 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11333 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11334
11335 // Optionally warn if we're emitting a weak vtable.
11336 if (Class->getLinkage() == ExternalLinkage &&
11337 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011338 const FunctionDecl *KeyFunctionDef = 0;
11339 if (!KeyFunction ||
11340 (KeyFunction->hasBody(KeyFunctionDef) &&
11341 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011342 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11343 TSK_ExplicitInstantiationDefinition
11344 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11345 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011346 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011347 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011348 VTableUses.clear();
11349
Douglas Gregor78844032011-04-22 22:25:37 +000011350 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011351}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011352
Richard Smithb9d0b762012-07-27 04:22:15 +000011353void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11354 const CXXRecordDecl *RD) {
11355 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11356 E = RD->method_end(); I != E; ++I)
11357 if ((*I)->isVirtual() && !(*I)->isPure())
11358 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11359}
11360
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011361void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11362 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011363 // Mark all functions which will appear in RD's vtable as used.
11364 CXXFinalOverriderMap FinalOverriders;
11365 RD->getFinalOverriders(FinalOverriders);
11366 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11367 E = FinalOverriders.end();
11368 I != E; ++I) {
11369 for (OverridingMethods::const_iterator OI = I->second.begin(),
11370 OE = I->second.end();
11371 OI != OE; ++OI) {
11372 assert(OI->second.size() > 0 && "no final overrider");
11373 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011374
Richard Smithff817f72012-07-07 06:59:51 +000011375 // C++ [basic.def.odr]p2:
11376 // [...] A virtual member function is used if it is not pure. [...]
11377 if (!Overrider->isPure())
11378 MarkFunctionReferenced(Loc, Overrider);
11379 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011380 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011381
11382 // Only classes that have virtual bases need a VTT.
11383 if (RD->getNumVBases() == 0)
11384 return;
11385
11386 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11387 e = RD->bases_end(); i != e; ++i) {
11388 const CXXRecordDecl *Base =
11389 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011390 if (Base->getNumVBases() == 0)
11391 continue;
11392 MarkVirtualMembersReferenced(Loc, Base);
11393 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011394}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011395
11396/// SetIvarInitializers - This routine builds initialization ASTs for the
11397/// Objective-C implementation whose ivars need be initialized.
11398void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011399 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011400 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011401 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011402 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011403 CollectIvarsToConstructOrDestruct(OID, ivars);
11404 if (ivars.empty())
11405 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011406 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011407 for (unsigned i = 0; i < ivars.size(); i++) {
11408 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011409 if (Field->isInvalidDecl())
11410 continue;
11411
Sean Huntcbb67482011-01-08 20:30:50 +000011412 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011413 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11414 InitializationKind InitKind =
11415 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11416
11417 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011418 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011419 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011420 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011421 // Note, MemberInit could actually come back empty if no initialization
11422 // is required (e.g., because it would call a trivial default constructor)
11423 if (!MemberInit.get() || MemberInit.isInvalid())
11424 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011425
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011426 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011427 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11428 SourceLocation(),
11429 MemberInit.takeAs<Expr>(),
11430 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011431 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011432
11433 // Be sure that the destructor is accessible and is marked as referenced.
11434 if (const RecordType *RecordTy
11435 = Context.getBaseElementType(Field->getType())
11436 ->getAs<RecordType>()) {
11437 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011438 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011439 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011440 CheckDestructorAccess(Field->getLocation(), Destructor,
11441 PDiag(diag::err_access_dtor_ivar)
11442 << Context.getBaseElementType(Field->getType()));
11443 }
11444 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011445 }
11446 ObjCImplementation->setIvarInitializers(Context,
11447 AllToInit.data(), AllToInit.size());
11448 }
11449}
Sean Huntfe57eef2011-05-04 05:57:24 +000011450
Sean Huntebcbe1d2011-05-04 23:29:54 +000011451static
11452void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11453 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11454 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11455 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11456 Sema &S) {
11457 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11458 CE = Current.end();
11459 if (Ctor->isInvalidDecl())
11460 return;
11461
Richard Smitha8eaf002012-08-23 06:16:52 +000011462 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11463
11464 // Target may not be determinable yet, for instance if this is a dependent
11465 // call in an uninstantiated template.
11466 if (Target) {
11467 const FunctionDecl *FNTarget = 0;
11468 (void)Target->hasBody(FNTarget);
11469 Target = const_cast<CXXConstructorDecl*>(
11470 cast_or_null<CXXConstructorDecl>(FNTarget));
11471 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011472
11473 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11474 // Avoid dereferencing a null pointer here.
11475 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11476
11477 if (!Current.insert(Canonical))
11478 return;
11479
11480 // We know that beyond here, we aren't chaining into a cycle.
11481 if (!Target || !Target->isDelegatingConstructor() ||
11482 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11483 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11484 Valid.insert(*CI);
11485 Current.clear();
11486 // We've hit a cycle.
11487 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11488 Current.count(TCanonical)) {
11489 // If we haven't diagnosed this cycle yet, do so now.
11490 if (!Invalid.count(TCanonical)) {
11491 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011492 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011493 << Ctor;
11494
Richard Smitha8eaf002012-08-23 06:16:52 +000011495 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011496 if (TCanonical != Canonical)
11497 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11498
11499 CXXConstructorDecl *C = Target;
11500 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011501 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011502 (void)C->getTargetConstructor()->hasBody(FNTarget);
11503 assert(FNTarget && "Ctor cycle through bodiless function");
11504
Richard Smitha8eaf002012-08-23 06:16:52 +000011505 C = const_cast<CXXConstructorDecl*>(
11506 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011507 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11508 }
11509 }
11510
11511 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11512 Invalid.insert(*CI);
11513 Current.clear();
11514 } else {
11515 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11516 }
11517}
11518
11519
Sean Huntfe57eef2011-05-04 05:57:24 +000011520void Sema::CheckDelegatingCtorCycles() {
11521 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11522
Sean Huntebcbe1d2011-05-04 23:29:54 +000011523 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11524 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011525
Douglas Gregor0129b562011-07-27 21:57:17 +000011526 for (DelegatingCtorDeclsType::iterator
11527 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011528 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011529 I != E; ++I)
11530 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011531
11532 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11533 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011534}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011535
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011536namespace {
11537 /// \brief AST visitor that finds references to the 'this' expression.
11538 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11539 Sema &S;
11540
11541 public:
11542 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11543
11544 bool VisitCXXThisExpr(CXXThisExpr *E) {
11545 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11546 << E->isImplicit();
11547 return false;
11548 }
11549 };
11550}
11551
11552bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11553 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11554 if (!TSInfo)
11555 return false;
11556
11557 TypeLoc TL = TSInfo->getTypeLoc();
11558 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11559 if (!ProtoTL)
11560 return false;
11561
11562 // C++11 [expr.prim.general]p3:
11563 // [The expression this] shall not appear before the optional
11564 // cv-qualifier-seq and it shall not appear within the declaration of a
11565 // static member function (although its type and value category are defined
11566 // within a static member function as they are within a non-static member
11567 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011568 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011569 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11570 FindCXXThisExpr Finder(*this);
11571
11572 // If the return type came after the cv-qualifier-seq, check it now.
11573 if (Proto->hasTrailingReturn() &&
11574 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11575 return true;
11576
11577 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011578 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11579 return true;
11580
11581 return checkThisInStaticMemberFunctionAttributes(Method);
11582}
11583
11584bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11585 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11586 if (!TSInfo)
11587 return false;
11588
11589 TypeLoc TL = TSInfo->getTypeLoc();
11590 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11591 if (!ProtoTL)
11592 return false;
11593
11594 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11595 FindCXXThisExpr Finder(*this);
11596
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011597 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011598 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011599 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011600 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011601 case EST_DynamicNone:
11602 case EST_MSAny:
11603 case EST_None:
11604 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011605
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011606 case EST_ComputedNoexcept:
11607 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11608 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011609
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011610 case EST_Dynamic:
11611 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011612 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011613 E != EEnd; ++E) {
11614 if (!Finder.TraverseType(*E))
11615 return true;
11616 }
11617 break;
11618 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011619
11620 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011621}
11622
11623bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11624 FindCXXThisExpr Finder(*this);
11625
11626 // Check attributes.
11627 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11628 A != AEnd; ++A) {
11629 // FIXME: This should be emitted by tblgen.
11630 Expr *Arg = 0;
11631 ArrayRef<Expr *> Args;
11632 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11633 Arg = G->getArg();
11634 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11635 Arg = G->getArg();
11636 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11637 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11638 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11639 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11640 else if (ExclusiveLockFunctionAttr *ELF
11641 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11642 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11643 else if (SharedLockFunctionAttr *SLF
11644 = dyn_cast<SharedLockFunctionAttr>(*A))
11645 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11646 else if (ExclusiveTrylockFunctionAttr *ETLF
11647 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11648 Arg = ETLF->getSuccessValue();
11649 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11650 } else if (SharedTrylockFunctionAttr *STLF
11651 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11652 Arg = STLF->getSuccessValue();
11653 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11654 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11655 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11656 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11657 Arg = LR->getArg();
11658 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11659 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11660 else if (ExclusiveLocksRequiredAttr *ELR
11661 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11662 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11663 else if (SharedLocksRequiredAttr *SLR
11664 = dyn_cast<SharedLocksRequiredAttr>(*A))
11665 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11666
11667 if (Arg && !Finder.TraverseStmt(Arg))
11668 return true;
11669
11670 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11671 if (!Finder.TraverseStmt(Args[I]))
11672 return true;
11673 }
11674 }
11675
11676 return false;
11677}
11678
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011679void
11680Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11681 ArrayRef<ParsedType> DynamicExceptions,
11682 ArrayRef<SourceRange> DynamicExceptionRanges,
11683 Expr *NoexceptExpr,
11684 llvm::SmallVectorImpl<QualType> &Exceptions,
11685 FunctionProtoType::ExtProtoInfo &EPI) {
11686 Exceptions.clear();
11687 EPI.ExceptionSpecType = EST;
11688 if (EST == EST_Dynamic) {
11689 Exceptions.reserve(DynamicExceptions.size());
11690 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11691 // FIXME: Preserve type source info.
11692 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11693
11694 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11695 collectUnexpandedParameterPacks(ET, Unexpanded);
11696 if (!Unexpanded.empty()) {
11697 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11698 UPPC_ExceptionType,
11699 Unexpanded);
11700 continue;
11701 }
11702
11703 // Check that the type is valid for an exception spec, and
11704 // drop it if not.
11705 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11706 Exceptions.push_back(ET);
11707 }
11708 EPI.NumExceptions = Exceptions.size();
11709 EPI.Exceptions = Exceptions.data();
11710 return;
11711 }
11712
11713 if (EST == EST_ComputedNoexcept) {
11714 // If an error occurred, there's no expression here.
11715 if (NoexceptExpr) {
11716 assert((NoexceptExpr->isTypeDependent() ||
11717 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11718 Context.BoolTy) &&
11719 "Parser should have made sure that the expression is boolean");
11720 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11721 EPI.ExceptionSpecType = EST_BasicNoexcept;
11722 return;
11723 }
11724
11725 if (!NoexceptExpr->isValueDependent())
11726 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011727 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011728 /*AllowFold*/ false).take();
11729 EPI.NoexceptExpr = NoexceptExpr;
11730 }
11731 return;
11732 }
11733}
11734
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011735/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11736Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11737 // Implicitly declared functions (e.g. copy constructors) are
11738 // __host__ __device__
11739 if (D->isImplicit())
11740 return CFT_HostDevice;
11741
11742 if (D->hasAttr<CUDAGlobalAttr>())
11743 return CFT_Global;
11744
11745 if (D->hasAttr<CUDADeviceAttr>()) {
11746 if (D->hasAttr<CUDAHostAttr>())
11747 return CFT_HostDevice;
11748 else
11749 return CFT_Device;
11750 }
11751
11752 return CFT_Host;
11753}
11754
11755bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11756 CUDAFunctionTarget CalleeTarget) {
11757 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11758 // Callable from the device only."
11759 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11760 return true;
11761
11762 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11763 // Callable from the host only."
11764 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11765 // Callable from the host only."
11766 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11767 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11768 return true;
11769
11770 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11771 return true;
11772
11773 return false;
11774}