blob: 027491cbbe41174aa2c66f912e07667aec698d56 [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);
Francois Pichet87c2e122010-11-21 06:08:52 +00002122 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002123 ValueDecl *Member;
2124 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
2125 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
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.
3959 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003960 R.first != R.second; ++R.first) {
3961 NamedDecl *D = *R.first;
3962 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3963 isa<IndirectFieldDecl>(D)) {
3964 Diag(D->getLocation(), diag::err_member_name_of_class)
3965 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003966 break;
3967 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003968 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003969 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003970
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003971 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003972 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003973 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003974 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003975 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3976 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3977 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003978
David Blaikieb6b5b972012-09-21 03:21:07 +00003979 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3980 Diag(Record->getLocation(), diag::warn_abstract_final_class);
3981 DiagnoseAbstractType(Record);
3982 }
3983
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003984 if (!Record->isDependentType()) {
3985 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3986 MEnd = Record->method_end();
3987 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00003988 // See if a method overloads virtual methods in a base
3989 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00003990 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003991 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00003992
3993 // Check whether the explicitly-defaulted special members are valid.
3994 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
3995 CheckExplicitlyDefaultedSpecialMember(*M);
3996
3997 // For an explicitly defaulted or deleted special member, we defer
3998 // determining triviality until the class is complete. That time is now!
3999 if (!M->isImplicit() && !M->isUserProvided()) {
4000 CXXSpecialMember CSM = getSpecialMember(*M);
4001 if (CSM != CXXInvalid) {
4002 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4003
4004 // Inform the class that we've finished declaring this member.
4005 Record->finishedDefaultedOrDeletedMember(*M);
4006 }
4007 }
4008 }
4009 }
4010
4011 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4012 // function that is not a constructor declares that member function to be
4013 // const. [...] The class of which that function is a member shall be
4014 // a literal type.
4015 //
4016 // If the class has virtual bases, any constexpr members will already have
4017 // been diagnosed by the checks performed on the member declaration, so
4018 // suppress this (less useful) diagnostic.
4019 //
4020 // We delay this until we know whether an explicitly-defaulted (or deleted)
4021 // destructor for the class is trivial.
4022 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
4023 !Record->isLiteral() && !Record->getNumVBases()) {
4024 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4025 MEnd = Record->method_end();
4026 M != MEnd; ++M) {
4027 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4028 switch (Record->getTemplateSpecializationKind()) {
4029 case TSK_ImplicitInstantiation:
4030 case TSK_ExplicitInstantiationDeclaration:
4031 case TSK_ExplicitInstantiationDefinition:
4032 // If a template instantiates to a non-literal type, but its members
4033 // instantiate to constexpr functions, the template is technically
4034 // ill-formed, but we allow it for sanity.
4035 continue;
4036
4037 case TSK_Undeclared:
4038 case TSK_ExplicitSpecialization:
4039 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4040 diag::err_constexpr_method_non_literal);
4041 break;
4042 }
4043
4044 // Only produce one error per class.
4045 break;
4046 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004047 }
4048 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004049
4050 // Declare inherited constructors. We do this eagerly here because:
4051 // - The standard requires an eager diagnostic for conflicting inherited
4052 // constructors from different classes.
4053 // - The lazy declaration of the other implicit constructors is so as to not
4054 // waste space and performance on classes that are not meant to be
4055 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4056 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004057 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004058}
4059
Richard Smith7756afa2012-06-10 05:43:50 +00004060/// Is the special member function which would be selected to perform the
4061/// specified operation on the specified class type a constexpr constructor?
4062static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4063 Sema::CXXSpecialMember CSM,
4064 bool ConstArg) {
4065 Sema::SpecialMemberOverloadResult *SMOR =
4066 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4067 false, false, false, false);
4068 if (!SMOR || !SMOR->getMethod())
4069 // A constructor we wouldn't select can't be "involved in initializing"
4070 // anything.
4071 return true;
4072 return SMOR->getMethod()->isConstexpr();
4073}
4074
4075/// Determine whether the specified special member function would be constexpr
4076/// if it were implicitly defined.
4077static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4078 Sema::CXXSpecialMember CSM,
4079 bool ConstArg) {
4080 if (!S.getLangOpts().CPlusPlus0x)
4081 return false;
4082
4083 // C++11 [dcl.constexpr]p4:
4084 // In the definition of a constexpr constructor [...]
4085 switch (CSM) {
4086 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004087 // Since default constructor lookup is essentially trivial (and cannot
4088 // involve, for instance, template instantiation), we compute whether a
4089 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4090 //
4091 // This is important for performance; we need to know whether the default
4092 // constructor is constexpr to determine whether the type is a literal type.
4093 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4094
Richard Smith7756afa2012-06-10 05:43:50 +00004095 case Sema::CXXCopyConstructor:
4096 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004097 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004098 break;
4099
4100 case Sema::CXXCopyAssignment:
4101 case Sema::CXXMoveAssignment:
4102 case Sema::CXXDestructor:
4103 case Sema::CXXInvalid:
4104 return false;
4105 }
4106
4107 // -- if the class is a non-empty union, or for each non-empty anonymous
4108 // union member of a non-union class, exactly one non-static data member
4109 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004110 //
4111 // If we squint, this is guaranteed, since exactly one non-static data member
4112 // will be initialized (if the constructor isn't deleted), we just don't know
4113 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004114 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004115 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004116
4117 // -- the class shall not have any virtual base classes;
4118 if (ClassDecl->getNumVBases())
4119 return false;
4120
4121 // -- every constructor involved in initializing [...] base class
4122 // sub-objects shall be a constexpr constructor;
4123 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4124 BEnd = ClassDecl->bases_end();
4125 B != BEnd; ++B) {
4126 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4127 if (!BaseType) continue;
4128
4129 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4130 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4131 return false;
4132 }
4133
4134 // -- every constructor involved in initializing non-static data members
4135 // [...] shall be a constexpr constructor;
4136 // -- every non-static data member and base class sub-object shall be
4137 // initialized
4138 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4139 FEnd = ClassDecl->field_end();
4140 F != FEnd; ++F) {
4141 if (F->isInvalidDecl())
4142 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004143 if (const RecordType *RecordTy =
4144 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004145 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4146 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4147 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004148 }
4149 }
4150
4151 // All OK, it's constexpr!
4152 return true;
4153}
4154
Richard Smithb9d0b762012-07-27 04:22:15 +00004155static Sema::ImplicitExceptionSpecification
4156computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4157 switch (S.getSpecialMember(MD)) {
4158 case Sema::CXXDefaultConstructor:
4159 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4160 case Sema::CXXCopyConstructor:
4161 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4162 case Sema::CXXCopyAssignment:
4163 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4164 case Sema::CXXMoveConstructor:
4165 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4166 case Sema::CXXMoveAssignment:
4167 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4168 case Sema::CXXDestructor:
4169 return S.ComputeDefaultedDtorExceptionSpec(MD);
4170 case Sema::CXXInvalid:
4171 break;
4172 }
4173 llvm_unreachable("only special members have implicit exception specs");
4174}
4175
Richard Smithdd25e802012-07-30 23:48:14 +00004176static void
4177updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4178 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4179 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4180 ExceptSpec.getEPI(EPI);
4181 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4182 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4183 FPT->getNumArgs(), EPI));
4184 FD->setType(QualType(NewFPT, 0));
4185}
4186
Richard Smithb9d0b762012-07-27 04:22:15 +00004187void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4188 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4189 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4190 return;
4191
Richard Smithdd25e802012-07-30 23:48:14 +00004192 // Evaluate the exception specification.
4193 ImplicitExceptionSpecification ExceptSpec =
4194 computeImplicitExceptionSpec(*this, Loc, MD);
4195
4196 // Update the type of the special member to use it.
4197 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4198
4199 // A user-provided destructor can be defined outside the class. When that
4200 // happens, be sure to update the exception specification on both
4201 // declarations.
4202 const FunctionProtoType *CanonicalFPT =
4203 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4204 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4205 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4206 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004207}
4208
Richard Smith3003e1d2012-05-15 04:39:51 +00004209void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4210 CXXRecordDecl *RD = MD->getParent();
4211 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004212
Richard Smith3003e1d2012-05-15 04:39:51 +00004213 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4214 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004215
4216 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004217 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004218 bool First = MD == MD->getCanonicalDecl();
4219
4220 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004221
4222 // C++11 [dcl.fct.def.default]p1:
4223 // A function that is explicitly defaulted shall
4224 // -- be a special member function (checked elsewhere),
4225 // -- have the same type (except for ref-qualifiers, and except that a
4226 // copy operation can take a non-const reference) as an implicit
4227 // declaration, and
4228 // -- not have default arguments.
4229 unsigned ExpectedParams = 1;
4230 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4231 ExpectedParams = 0;
4232 if (MD->getNumParams() != ExpectedParams) {
4233 // This also checks for default arguments: a copy or move constructor with a
4234 // default argument is classified as a default constructor, and assignment
4235 // operations and destructors can't have default arguments.
4236 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4237 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004238 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004239 } else if (MD->isVariadic()) {
4240 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4241 << CSM << MD->getSourceRange();
4242 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004243 }
4244
Richard Smith3003e1d2012-05-15 04:39:51 +00004245 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004246
Richard Smith7756afa2012-06-10 05:43:50 +00004247 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004248 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004249 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004250 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004251 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004252
Richard Smith3003e1d2012-05-15 04:39:51 +00004253 QualType ReturnType = Context.VoidTy;
4254 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4255 // Check for return type matching.
4256 ReturnType = Type->getResultType();
4257 QualType ExpectedReturnType =
4258 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4259 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4260 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4261 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4262 HadError = true;
4263 }
4264
4265 // A defaulted special member cannot have cv-qualifiers.
4266 if (Type->getTypeQuals()) {
4267 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4268 << (CSM == CXXMoveAssignment);
4269 HadError = true;
4270 }
4271 }
4272
4273 // Check for parameter type matching.
4274 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004275 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004276 if (ExpectedParams && ArgType->isReferenceType()) {
4277 // Argument must be reference to possibly-const T.
4278 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004279 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004280
4281 if (ReferentType.isVolatileQualified()) {
4282 Diag(MD->getLocation(),
4283 diag::err_defaulted_special_member_volatile_param) << CSM;
4284 HadError = true;
4285 }
4286
Richard Smith7756afa2012-06-10 05:43:50 +00004287 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004288 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4289 Diag(MD->getLocation(),
4290 diag::err_defaulted_special_member_copy_const_param)
4291 << (CSM == CXXCopyAssignment);
4292 // FIXME: Explain why this special member can't be const.
4293 } else {
4294 Diag(MD->getLocation(),
4295 diag::err_defaulted_special_member_move_const_param)
4296 << (CSM == CXXMoveAssignment);
4297 }
4298 HadError = true;
4299 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004300 } else if (ExpectedParams) {
4301 // A copy assignment operator can take its argument by value, but a
4302 // defaulted one cannot.
4303 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004304 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004305 HadError = true;
4306 }
Sean Huntbe631222011-05-17 20:44:43 +00004307
Richard Smith61802452011-12-22 02:22:31 +00004308 // C++11 [dcl.fct.def.default]p2:
4309 // An explicitly-defaulted function may be declared constexpr only if it
4310 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004311 // Do not apply this rule to members of class templates, since core issue 1358
4312 // makes such functions always instantiate to constexpr functions. For
4313 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004314 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4315 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004316 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4317 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4318 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004319 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004320 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004321 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004322
Richard Smith61802452011-12-22 02:22:31 +00004323 // and may have an explicit exception-specification only if it is compatible
4324 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004325 if (Type->hasExceptionSpec()) {
4326 // Delay the check if this is the first declaration of the special member,
4327 // since we may not have parsed some necessary in-class initializers yet.
4328 if (First)
4329 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4330 else
4331 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4332 }
Richard Smith61802452011-12-22 02:22:31 +00004333
4334 // If a function is explicitly defaulted on its first declaration,
4335 if (First) {
4336 // -- it is implicitly considered to be constexpr if the implicit
4337 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004338 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004339
Richard Smith3003e1d2012-05-15 04:39:51 +00004340 // -- it is implicitly considered to have the same exception-specification
4341 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004342 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4343 EPI.ExceptionSpecType = EST_Unevaluated;
4344 EPI.ExceptionSpecDecl = MD;
4345 MD->setType(Context.getFunctionType(ReturnType, &ArgType,
4346 ExpectedParams, EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004347 }
4348
Richard Smith3003e1d2012-05-15 04:39:51 +00004349 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004350 if (First) {
4351 MD->setDeletedAsWritten();
4352 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004353 // C++11 [dcl.fct.def.default]p4:
4354 // [For a] user-provided explicitly-defaulted function [...] if such a
4355 // function is implicitly defined as deleted, the program is ill-formed.
4356 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4357 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004358 }
4359 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004360
Richard Smith3003e1d2012-05-15 04:39:51 +00004361 if (HadError)
4362 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004363}
4364
Richard Smith1d28caf2012-12-11 01:14:52 +00004365/// Check whether the exception specification provided for an
4366/// explicitly-defaulted special member matches the exception specification
4367/// that would have been generated for an implicit special member, per
4368/// C++11 [dcl.fct.def.default]p2.
4369void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4370 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4371 // Compute the implicit exception specification.
4372 FunctionProtoType::ExtProtoInfo EPI;
4373 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4374 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4375 Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4376
4377 // Ensure that it matches.
4378 CheckEquivalentExceptionSpec(
4379 PDiag(diag::err_incorrect_defaulted_exception_spec)
4380 << getSpecialMember(MD), PDiag(),
4381 ImplicitType, SourceLocation(),
4382 SpecifiedType, MD->getLocation());
4383}
4384
4385void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4386 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4387 I != N; ++I)
4388 CheckExplicitlyDefaultedMemberExceptionSpec(
4389 DelayedDefaultedMemberExceptionSpecs[I].first,
4390 DelayedDefaultedMemberExceptionSpecs[I].second);
4391
4392 DelayedDefaultedMemberExceptionSpecs.clear();
4393}
4394
Richard Smith7d5088a2012-02-18 02:02:13 +00004395namespace {
4396struct SpecialMemberDeletionInfo {
4397 Sema &S;
4398 CXXMethodDecl *MD;
4399 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004400 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004401
4402 // Properties of the special member, computed for convenience.
4403 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4404 SourceLocation Loc;
4405
4406 bool AllFieldsAreConst;
4407
4408 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004409 Sema::CXXSpecialMember CSM, bool Diagnose)
4410 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004411 IsConstructor(false), IsAssignment(false), IsMove(false),
4412 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4413 AllFieldsAreConst(true) {
4414 switch (CSM) {
4415 case Sema::CXXDefaultConstructor:
4416 case Sema::CXXCopyConstructor:
4417 IsConstructor = true;
4418 break;
4419 case Sema::CXXMoveConstructor:
4420 IsConstructor = true;
4421 IsMove = true;
4422 break;
4423 case Sema::CXXCopyAssignment:
4424 IsAssignment = true;
4425 break;
4426 case Sema::CXXMoveAssignment:
4427 IsAssignment = true;
4428 IsMove = true;
4429 break;
4430 case Sema::CXXDestructor:
4431 break;
4432 case Sema::CXXInvalid:
4433 llvm_unreachable("invalid special member kind");
4434 }
4435
4436 if (MD->getNumParams()) {
4437 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4438 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4439 }
4440 }
4441
4442 bool inUnion() const { return MD->getParent()->isUnion(); }
4443
4444 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004445 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4446 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004447 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004448 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4449 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4450 Quals = 0;
4451 return S.LookupSpecialMember(Class, CSM,
4452 ConstArg || (Quals & Qualifiers::Const),
4453 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004454 MD->getRefQualifier() == RQ_RValue,
4455 TQ & Qualifiers::Const,
4456 TQ & Qualifiers::Volatile);
4457 }
4458
Richard Smith6c4c36c2012-03-30 20:53:28 +00004459 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004460
Richard Smith6c4c36c2012-03-30 20:53:28 +00004461 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004462 bool shouldDeleteForField(FieldDecl *FD);
4463 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004464
Richard Smith517bb842012-07-18 03:51:16 +00004465 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4466 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004467 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4468 Sema::SpecialMemberOverloadResult *SMOR,
4469 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004470
4471 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004472};
4473}
4474
John McCall12d8d802012-04-09 20:53:23 +00004475/// Is the given special member inaccessible when used on the given
4476/// sub-object.
4477bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4478 CXXMethodDecl *target) {
4479 /// If we're operating on a base class, the object type is the
4480 /// type of this special member.
4481 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004482 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004483 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4484 objectTy = S.Context.getTypeDeclType(MD->getParent());
4485 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4486
4487 // If we're operating on a field, the object type is the type of the field.
4488 } else {
4489 objectTy = S.Context.getTypeDeclType(target->getParent());
4490 }
4491
4492 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4493}
4494
Richard Smith6c4c36c2012-03-30 20:53:28 +00004495/// Check whether we should delete a special member due to the implicit
4496/// definition containing a call to a special member of a subobject.
4497bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4498 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4499 bool IsDtorCallInCtor) {
4500 CXXMethodDecl *Decl = SMOR->getMethod();
4501 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4502
4503 int DiagKind = -1;
4504
4505 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4506 DiagKind = !Decl ? 0 : 1;
4507 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4508 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004509 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004510 DiagKind = 3;
4511 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4512 !Decl->isTrivial()) {
4513 // A member of a union must have a trivial corresponding special member.
4514 // As a weird special case, a destructor call from a union's constructor
4515 // must be accessible and non-deleted, but need not be trivial. Such a
4516 // destructor is never actually called, but is semantically checked as
4517 // if it were.
4518 DiagKind = 4;
4519 }
4520
4521 if (DiagKind == -1)
4522 return false;
4523
4524 if (Diagnose) {
4525 if (Field) {
4526 S.Diag(Field->getLocation(),
4527 diag::note_deleted_special_member_class_subobject)
4528 << CSM << MD->getParent() << /*IsField*/true
4529 << Field << DiagKind << IsDtorCallInCtor;
4530 } else {
4531 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4532 S.Diag(Base->getLocStart(),
4533 diag::note_deleted_special_member_class_subobject)
4534 << CSM << MD->getParent() << /*IsField*/false
4535 << Base->getType() << DiagKind << IsDtorCallInCtor;
4536 }
4537
4538 if (DiagKind == 1)
4539 S.NoteDeletedFunction(Decl);
4540 // FIXME: Explain inaccessibility if DiagKind == 3.
4541 }
4542
4543 return true;
4544}
4545
Richard Smith9a561d52012-02-26 09:11:52 +00004546/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004547/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004548bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004549 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004550 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004551
4552 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004553 // -- any direct or virtual base class, or non-static data member with no
4554 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004555 // either M has no default constructor or overload resolution as applied
4556 // to M's default constructor results in an ambiguity or in a function
4557 // that is deleted or inaccessible
4558 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4559 // -- a direct or virtual base class B that cannot be copied/moved because
4560 // overload resolution, as applied to B's corresponding special member,
4561 // results in an ambiguity or a function that is deleted or inaccessible
4562 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004563 // C++11 [class.dtor]p5:
4564 // -- any direct or virtual base class [...] has a type with a destructor
4565 // that is deleted or inaccessible
4566 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004567 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004568 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004569 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004570
Richard Smith6c4c36c2012-03-30 20:53:28 +00004571 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4572 // -- any direct or virtual base class or non-static data member has a
4573 // type with a destructor that is deleted or inaccessible
4574 if (IsConstructor) {
4575 Sema::SpecialMemberOverloadResult *SMOR =
4576 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4577 false, false, false, false, false);
4578 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4579 return true;
4580 }
4581
Richard Smith9a561d52012-02-26 09:11:52 +00004582 return false;
4583}
4584
4585/// Check whether we should delete a special member function due to the class
4586/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004587bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004588 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004589 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004590}
4591
4592/// Check whether we should delete a special member function due to the class
4593/// having a particular non-static data member.
4594bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4595 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4596 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4597
4598 if (CSM == Sema::CXXDefaultConstructor) {
4599 // For a default constructor, all references must be initialized in-class
4600 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004601 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4602 if (Diagnose)
4603 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4604 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004605 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004606 }
Richard Smith79363f52012-02-27 06:07:25 +00004607 // C++11 [class.ctor]p5: any non-variant non-static data member of
4608 // const-qualified type (or array thereof) with no
4609 // brace-or-equal-initializer does not have a user-provided default
4610 // constructor.
4611 if (!inUnion() && FieldType.isConstQualified() &&
4612 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004613 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4614 if (Diagnose)
4615 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004616 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004617 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004618 }
4619
4620 if (inUnion() && !FieldType.isConstQualified())
4621 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004622 } else if (CSM == Sema::CXXCopyConstructor) {
4623 // For a copy constructor, data members must not be of rvalue reference
4624 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004625 if (FieldType->isRValueReferenceType()) {
4626 if (Diagnose)
4627 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4628 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004629 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004630 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004631 } else if (IsAssignment) {
4632 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004633 if (FieldType->isReferenceType()) {
4634 if (Diagnose)
4635 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4636 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004637 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004638 }
4639 if (!FieldRecord && FieldType.isConstQualified()) {
4640 // C++11 [class.copy]p23:
4641 // -- a non-static data member of const non-class type (or array thereof)
4642 if (Diagnose)
4643 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004644 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004645 return true;
4646 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004647 }
4648
4649 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004650 // Some additional restrictions exist on the variant members.
4651 if (!inUnion() && FieldRecord->isUnion() &&
4652 FieldRecord->isAnonymousStructOrUnion()) {
4653 bool AllVariantFieldsAreConst = true;
4654
Richard Smithdf8dc862012-03-29 19:00:10 +00004655 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004656 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4657 UE = FieldRecord->field_end();
4658 UI != UE; ++UI) {
4659 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004660
4661 if (!UnionFieldType.isConstQualified())
4662 AllVariantFieldsAreConst = false;
4663
Richard Smith9a561d52012-02-26 09:11:52 +00004664 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4665 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004666 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4667 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004668 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004669 }
4670
4671 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004672 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004673 FieldRecord->field_begin() != FieldRecord->field_end()) {
4674 if (Diagnose)
4675 S.Diag(FieldRecord->getLocation(),
4676 diag::note_deleted_default_ctor_all_const)
4677 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004678 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004679 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004680
Richard Smithdf8dc862012-03-29 19:00:10 +00004681 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004682 // This is technically non-conformant, but sanity demands it.
4683 return false;
4684 }
4685
Richard Smith517bb842012-07-18 03:51:16 +00004686 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4687 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004688 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004689 }
4690
4691 return false;
4692}
4693
4694/// C++11 [class.ctor] p5:
4695/// A defaulted default constructor for a class X is defined as deleted if
4696/// X is a union and all of its variant members are of const-qualified type.
4697bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004698 // This is a silly definition, because it gives an empty union a deleted
4699 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004700 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4701 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4702 if (Diagnose)
4703 S.Diag(MD->getParent()->getLocation(),
4704 diag::note_deleted_default_ctor_all_const)
4705 << MD->getParent() << /*not anonymous union*/0;
4706 return true;
4707 }
4708 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004709}
4710
4711/// Determine whether a defaulted special member function should be defined as
4712/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4713/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004714bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4715 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004716 if (MD->isInvalidDecl())
4717 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004718 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004719 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004720 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004721 return false;
4722
Richard Smith7d5088a2012-02-18 02:02:13 +00004723 // C++11 [expr.lambda.prim]p19:
4724 // The closure type associated with a lambda-expression has a
4725 // deleted (8.4.3) default constructor and a deleted copy
4726 // assignment operator.
4727 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004728 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4729 if (Diagnose)
4730 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004731 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004732 }
4733
Richard Smith5bdaac52012-04-02 20:59:25 +00004734 // For an anonymous struct or union, the copy and assignment special members
4735 // will never be used, so skip the check. For an anonymous union declared at
4736 // namespace scope, the constructor and destructor are used.
4737 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4738 RD->isAnonymousStructOrUnion())
4739 return false;
4740
Richard Smith6c4c36c2012-03-30 20:53:28 +00004741 // C++11 [class.copy]p7, p18:
4742 // If the class definition declares a move constructor or move assignment
4743 // operator, an implicitly declared copy constructor or copy assignment
4744 // operator is defined as deleted.
4745 if (MD->isImplicit() &&
4746 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4747 CXXMethodDecl *UserDeclaredMove = 0;
4748
4749 // In Microsoft mode, a user-declared move only causes the deletion of the
4750 // corresponding copy operation, not both copy operations.
4751 if (RD->hasUserDeclaredMoveConstructor() &&
4752 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4753 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004754
4755 // Find any user-declared move constructor.
4756 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4757 E = RD->ctor_end(); I != E; ++I) {
4758 if (I->isMoveConstructor()) {
4759 UserDeclaredMove = *I;
4760 break;
4761 }
4762 }
Richard Smith1c931be2012-04-02 18:40:40 +00004763 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004764 } else if (RD->hasUserDeclaredMoveAssignment() &&
4765 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4766 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004767
4768 // Find any user-declared move assignment operator.
4769 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4770 E = RD->method_end(); I != E; ++I) {
4771 if (I->isMoveAssignmentOperator()) {
4772 UserDeclaredMove = *I;
4773 break;
4774 }
4775 }
Richard Smith1c931be2012-04-02 18:40:40 +00004776 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004777 }
4778
4779 if (UserDeclaredMove) {
4780 Diag(UserDeclaredMove->getLocation(),
4781 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004782 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004783 << UserDeclaredMove->isMoveAssignmentOperator();
4784 return true;
4785 }
4786 }
Sean Hunte16da072011-10-10 06:18:57 +00004787
Richard Smith5bdaac52012-04-02 20:59:25 +00004788 // Do access control from the special member function
4789 ContextRAII MethodContext(*this, MD);
4790
Richard Smith9a561d52012-02-26 09:11:52 +00004791 // C++11 [class.dtor]p5:
4792 // -- for a virtual destructor, lookup of the non-array deallocation function
4793 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004794 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004795 FunctionDecl *OperatorDelete = 0;
4796 DeclarationName Name =
4797 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4798 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004799 OperatorDelete, false)) {
4800 if (Diagnose)
4801 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004802 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004803 }
Richard Smith9a561d52012-02-26 09:11:52 +00004804 }
4805
Richard Smith6c4c36c2012-03-30 20:53:28 +00004806 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004807
Sean Huntcdee3fe2011-05-11 22:34:38 +00004808 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004809 BE = RD->bases_end(); BI != BE; ++BI)
4810 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004811 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004812 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004813
4814 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004815 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004816 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004817 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004818
4819 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004820 FE = RD->field_end(); FI != FE; ++FI)
4821 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004822 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004823 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004824
Richard Smith7d5088a2012-02-18 02:02:13 +00004825 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004826 return true;
4827
4828 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004829}
4830
Richard Smithac713512012-12-08 02:53:02 +00004831/// Perform lookup for a special member of the specified kind, and determine
4832/// whether it is trivial. If the triviality can be determined without the
4833/// lookup, skip it. This is intended for use when determining whether a
4834/// special member of a containing object is trivial, and thus does not ever
4835/// perform overload resolution for default constructors.
4836///
4837/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4838/// member that was most likely to be intended to be trivial, if any.
4839static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4840 Sema::CXXSpecialMember CSM, unsigned Quals,
4841 CXXMethodDecl **Selected) {
4842 if (Selected)
4843 *Selected = 0;
4844
4845 switch (CSM) {
4846 case Sema::CXXInvalid:
4847 llvm_unreachable("not a special member");
4848
4849 case Sema::CXXDefaultConstructor:
4850 // C++11 [class.ctor]p5:
4851 // A default constructor is trivial if:
4852 // - all the [direct subobjects] have trivial default constructors
4853 //
4854 // Note, no overload resolution is performed in this case.
4855 if (RD->hasTrivialDefaultConstructor())
4856 return true;
4857
4858 if (Selected) {
4859 // If there's a default constructor which could have been trivial, dig it
4860 // out. Otherwise, if there's any user-provided default constructor, point
4861 // to that as an example of why there's not a trivial one.
4862 CXXConstructorDecl *DefCtor = 0;
4863 if (RD->needsImplicitDefaultConstructor())
4864 S.DeclareImplicitDefaultConstructor(RD);
4865 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4866 CE = RD->ctor_end(); CI != CE; ++CI) {
4867 if (!CI->isDefaultConstructor())
4868 continue;
4869 DefCtor = *CI;
4870 if (!DefCtor->isUserProvided())
4871 break;
4872 }
4873
4874 *Selected = DefCtor;
4875 }
4876
4877 return false;
4878
4879 case Sema::CXXDestructor:
4880 // C++11 [class.dtor]p5:
4881 // A destructor is trivial if:
4882 // - all the direct [subobjects] have trivial destructors
4883 if (RD->hasTrivialDestructor())
4884 return true;
4885
4886 if (Selected) {
4887 if (RD->needsImplicitDestructor())
4888 S.DeclareImplicitDestructor(RD);
4889 *Selected = RD->getDestructor();
4890 }
4891
4892 return false;
4893
4894 case Sema::CXXCopyConstructor:
4895 // C++11 [class.copy]p12:
4896 // A copy constructor is trivial if:
4897 // - the constructor selected to copy each direct [subobject] is trivial
4898 if (RD->hasTrivialCopyConstructor()) {
4899 if (Quals == Qualifiers::Const)
4900 // We must either select the trivial copy constructor or reach an
4901 // ambiguity; no need to actually perform overload resolution.
4902 return true;
4903 } else if (!Selected) {
4904 return false;
4905 }
4906 // In C++98, we are not supposed to perform overload resolution here, but we
4907 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4908 // cases like B as having a non-trivial copy constructor:
4909 // struct A { template<typename T> A(T&); };
4910 // struct B { mutable A a; };
4911 goto NeedOverloadResolution;
4912
4913 case Sema::CXXCopyAssignment:
4914 // C++11 [class.copy]p25:
4915 // A copy assignment operator is trivial if:
4916 // - the assignment operator selected to copy each direct [subobject] is
4917 // trivial
4918 if (RD->hasTrivialCopyAssignment()) {
4919 if (Quals == Qualifiers::Const)
4920 return true;
4921 } else if (!Selected) {
4922 return false;
4923 }
4924 // In C++98, we are not supposed to perform overload resolution here, but we
4925 // treat that as a language defect.
4926 goto NeedOverloadResolution;
4927
4928 case Sema::CXXMoveConstructor:
4929 case Sema::CXXMoveAssignment:
4930 NeedOverloadResolution:
4931 Sema::SpecialMemberOverloadResult *SMOR =
4932 S.LookupSpecialMember(RD, CSM,
4933 Quals & Qualifiers::Const,
4934 Quals & Qualifiers::Volatile,
4935 /*RValueThis*/false, /*ConstThis*/false,
4936 /*VolatileThis*/false);
4937
4938 // The standard doesn't describe how to behave if the lookup is ambiguous.
4939 // We treat it as not making the member non-trivial, just like the standard
4940 // mandates for the default constructor. This should rarely matter, because
4941 // the member will also be deleted.
4942 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4943 return true;
4944
4945 if (!SMOR->getMethod()) {
4946 assert(SMOR->getKind() ==
4947 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4948 return false;
4949 }
4950
4951 // We deliberately don't check if we found a deleted special member. We're
4952 // not supposed to!
4953 if (Selected)
4954 *Selected = SMOR->getMethod();
4955 return SMOR->getMethod()->isTrivial();
4956 }
4957
4958 llvm_unreachable("unknown special method kind");
4959}
4960
4961CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
4962 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
4963 CI != CE; ++CI)
4964 if (!CI->isImplicit())
4965 return *CI;
4966
4967 // Look for constructor templates.
4968 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
4969 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
4970 if (CXXConstructorDecl *CD =
4971 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
4972 return CD;
4973 }
4974
4975 return 0;
4976}
4977
4978/// The kind of subobject we are checking for triviality. The values of this
4979/// enumeration are used in diagnostics.
4980enum TrivialSubobjectKind {
4981 /// The subobject is a base class.
4982 TSK_BaseClass,
4983 /// The subobject is a non-static data member.
4984 TSK_Field,
4985 /// The object is actually the complete object.
4986 TSK_CompleteObject
4987};
4988
4989/// Check whether the special member selected for a given type would be trivial.
4990static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
4991 QualType SubType,
4992 Sema::CXXSpecialMember CSM,
4993 TrivialSubobjectKind Kind,
4994 bool Diagnose) {
4995 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
4996 if (!SubRD)
4997 return true;
4998
4999 CXXMethodDecl *Selected;
5000 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5001 Diagnose ? &Selected : 0))
5002 return true;
5003
5004 if (Diagnose) {
5005 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5006 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5007 << Kind << SubType.getUnqualifiedType();
5008 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5009 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5010 } else if (!Selected)
5011 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5012 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5013 else if (Selected->isUserProvided()) {
5014 if (Kind == TSK_CompleteObject)
5015 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5016 << Kind << SubType.getUnqualifiedType() << CSM;
5017 else {
5018 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5019 << Kind << SubType.getUnqualifiedType() << CSM;
5020 S.Diag(Selected->getLocation(), diag::note_declared_at);
5021 }
5022 } else {
5023 if (Kind != TSK_CompleteObject)
5024 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5025 << Kind << SubType.getUnqualifiedType() << CSM;
5026
5027 // Explain why the defaulted or deleted special member isn't trivial.
5028 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5029 }
5030 }
5031
5032 return false;
5033}
5034
5035/// Check whether the members of a class type allow a special member to be
5036/// trivial.
5037static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5038 Sema::CXXSpecialMember CSM,
5039 bool ConstArg, bool Diagnose) {
5040 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5041 FE = RD->field_end(); FI != FE; ++FI) {
5042 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5043 continue;
5044
5045 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5046
5047 // Pretend anonymous struct or union members are members of this class.
5048 if (FI->isAnonymousStructOrUnion()) {
5049 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5050 CSM, ConstArg, Diagnose))
5051 return false;
5052 continue;
5053 }
5054
5055 // C++11 [class.ctor]p5:
5056 // A default constructor is trivial if [...]
5057 // -- no non-static data member of its class has a
5058 // brace-or-equal-initializer
5059 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5060 if (Diagnose)
5061 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5062 return false;
5063 }
5064
5065 // Objective C ARC 4.3.5:
5066 // [...] nontrivally ownership-qualified types are [...] not trivially
5067 // default constructible, copy constructible, move constructible, copy
5068 // assignable, move assignable, or destructible [...]
5069 if (S.getLangOpts().ObjCAutoRefCount &&
5070 FieldType.hasNonTrivialObjCLifetime()) {
5071 if (Diagnose)
5072 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5073 << RD << FieldType.getObjCLifetime();
5074 return false;
5075 }
5076
5077 if (ConstArg && !FI->isMutable())
5078 FieldType.addConst();
5079 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5080 TSK_Field, Diagnose))
5081 return false;
5082 }
5083
5084 return true;
5085}
5086
5087/// Diagnose why the specified class does not have a trivial special member of
5088/// the given kind.
5089void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5090 QualType Ty = Context.getRecordType(RD);
5091 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5092 Ty.addConst();
5093
5094 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5095 TSK_CompleteObject, /*Diagnose*/true);
5096}
5097
5098/// Determine whether a defaulted or deleted special member function is trivial,
5099/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5100/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5101bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5102 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005103 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5104
5105 CXXRecordDecl *RD = MD->getParent();
5106
5107 bool ConstArg = false;
5108 ParmVarDecl *Param0 = MD->getNumParams() ? MD->getParamDecl(0) : 0;
5109
5110 // C++11 [class.copy]p12, p25:
5111 // A [special member] is trivial if its declared parameter type is the same
5112 // as if it had been implicitly declared [...]
5113 switch (CSM) {
5114 case CXXDefaultConstructor:
5115 case CXXDestructor:
5116 // Trivial default constructors and destructors cannot have parameters.
5117 break;
5118
5119 case CXXCopyConstructor:
5120 case CXXCopyAssignment: {
5121 // Trivial copy operations always have const, non-volatile parameter types.
5122 ConstArg = true;
5123 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5124 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5125 if (Diagnose)
5126 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5127 << Param0->getSourceRange() << Param0->getType()
5128 << Context.getLValueReferenceType(
5129 Context.getRecordType(RD).withConst());
5130 return false;
5131 }
5132 break;
5133 }
5134
5135 case CXXMoveConstructor:
5136 case CXXMoveAssignment: {
5137 // Trivial move operations always have non-cv-qualified parameters.
5138 const RValueReferenceType *RT =
5139 Param0->getType()->getAs<RValueReferenceType>();
5140 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5141 if (Diagnose)
5142 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5143 << Param0->getSourceRange() << Param0->getType()
5144 << Context.getRValueReferenceType(Context.getRecordType(RD));
5145 return false;
5146 }
5147 break;
5148 }
5149
5150 case CXXInvalid:
5151 llvm_unreachable("not a special member");
5152 }
5153
5154 // FIXME: We require that the parameter-declaration-clause is equivalent to
5155 // that of an implicit declaration, not just that the declared parameter type
5156 // matches, in order to prevent absuridities like a function simultaneously
5157 // being a trivial copy constructor and a non-trivial default constructor.
5158 // This issue has not yet been assigned a core issue number.
5159 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5160 if (Diagnose)
5161 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5162 diag::note_nontrivial_default_arg)
5163 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5164 return false;
5165 }
5166 if (MD->isVariadic()) {
5167 if (Diagnose)
5168 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5169 return false;
5170 }
5171
5172 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5173 // A copy/move [constructor or assignment operator] is trivial if
5174 // -- the [member] selected to copy/move each direct base class subobject
5175 // is trivial
5176 //
5177 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5178 // A [default constructor or destructor] is trivial if
5179 // -- all the direct base classes have trivial [default constructors or
5180 // destructors]
5181 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5182 BE = RD->bases_end(); BI != BE; ++BI)
5183 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5184 ConstArg ? BI->getType().withConst()
5185 : BI->getType(),
5186 CSM, TSK_BaseClass, Diagnose))
5187 return false;
5188
5189 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5190 // A copy/move [constructor or assignment operator] for a class X is
5191 // trivial if
5192 // -- for each non-static data member of X that is of class type (or array
5193 // thereof), the constructor selected to copy/move that member is
5194 // trivial
5195 //
5196 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5197 // A [default constructor or destructor] is trivial if
5198 // -- for all of the non-static data members of its class that are of class
5199 // type (or array thereof), each such class has a trivial [default
5200 // constructor or destructor]
5201 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5202 return false;
5203
5204 // C++11 [class.dtor]p5:
5205 // A destructor is trivial if [...]
5206 // -- the destructor is not virtual
5207 if (CSM == CXXDestructor && MD->isVirtual()) {
5208 if (Diagnose)
5209 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5210 return false;
5211 }
5212
5213 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5214 // A [special member] for class X is trivial if [...]
5215 // -- class X has no virtual functions and no virtual base classes
5216 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5217 if (!Diagnose)
5218 return false;
5219
5220 if (RD->getNumVBases()) {
5221 // Check for virtual bases. We already know that the corresponding
5222 // member in all bases is trivial, so vbases must all be direct.
5223 CXXBaseSpecifier &BS = *RD->vbases_begin();
5224 assert(BS.isVirtual());
5225 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5226 return false;
5227 }
5228
5229 // Must have a virtual method.
5230 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5231 ME = RD->method_end(); MI != ME; ++MI) {
5232 if (MI->isVirtual()) {
5233 SourceLocation MLoc = MI->getLocStart();
5234 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5235 return false;
5236 }
5237 }
5238
5239 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5240 }
5241
5242 // Looks like it's trivial!
5243 return true;
5244}
5245
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005246/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005247namespace {
5248 struct FindHiddenVirtualMethodData {
5249 Sema *S;
5250 CXXMethodDecl *Method;
5251 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005252 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005253 };
5254}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005255
David Blaikie5f750682012-10-19 00:53:08 +00005256/// \brief Check whether any most overriden method from MD in Methods
5257static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5258 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5259 if (MD->size_overridden_methods() == 0)
5260 return Methods.count(MD->getCanonicalDecl());
5261 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5262 E = MD->end_overridden_methods();
5263 I != E; ++I)
5264 if (CheckMostOverridenMethods(*I, Methods))
5265 return true;
5266 return false;
5267}
5268
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005269/// \brief Member lookup function that determines whether a given C++
5270/// method overloads virtual methods in a base class without overriding any,
5271/// to be used with CXXRecordDecl::lookupInBases().
5272static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5273 CXXBasePath &Path,
5274 void *UserData) {
5275 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5276
5277 FindHiddenVirtualMethodData &Data
5278 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5279
5280 DeclarationName Name = Data.Method->getDeclName();
5281 assert(Name.getNameKind() == DeclarationName::Identifier);
5282
5283 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005284 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005285 for (Path.Decls = BaseRecord->lookup(Name);
5286 Path.Decls.first != Path.Decls.second;
5287 ++Path.Decls.first) {
5288 NamedDecl *D = *Path.Decls.first;
5289 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005290 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005291 foundSameNameMethod = true;
5292 // Interested only in hidden virtual methods.
5293 if (!MD->isVirtual())
5294 continue;
5295 // If the method we are checking overrides a method from its base
5296 // don't warn about the other overloaded methods.
5297 if (!Data.S->IsOverload(Data.Method, MD, false))
5298 return true;
5299 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005300 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005301 overloadedMethods.push_back(MD);
5302 }
5303 }
5304
5305 if (foundSameNameMethod)
5306 Data.OverloadedMethods.append(overloadedMethods.begin(),
5307 overloadedMethods.end());
5308 return foundSameNameMethod;
5309}
5310
David Blaikie5f750682012-10-19 00:53:08 +00005311/// \brief Add the most overriden methods from MD to Methods
5312static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5313 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5314 if (MD->size_overridden_methods() == 0)
5315 Methods.insert(MD->getCanonicalDecl());
5316 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5317 E = MD->end_overridden_methods();
5318 I != E; ++I)
5319 AddMostOverridenMethods(*I, Methods);
5320}
5321
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005322/// \brief See if a method overloads virtual methods in a base class without
5323/// overriding any.
5324void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5325 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005326 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005327 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005328 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005329 return;
5330
5331 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5332 /*bool RecordPaths=*/false,
5333 /*bool DetectVirtual=*/false);
5334 FindHiddenVirtualMethodData Data;
5335 Data.Method = MD;
5336 Data.S = this;
5337
5338 // Keep the base methods that were overriden or introduced in the subclass
5339 // by 'using' in a set. A base method not in this set is hidden.
5340 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5341 res.first != res.second; ++res.first) {
David Blaikie5f750682012-10-19 00:53:08 +00005342 NamedDecl *ND = *res.first;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005343 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
David Blaikie5f750682012-10-19 00:53:08 +00005344 ND = shad->getTargetDecl();
5345 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5346 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005347 }
5348
5349 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5350 !Data.OverloadedMethods.empty()) {
5351 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5352 << MD << (Data.OverloadedMethods.size() > 1);
5353
5354 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5355 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5356 Diag(overloadedMD->getLocation(),
5357 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5358 }
5359 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005360}
5361
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005362void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005363 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005364 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005365 SourceLocation RBrac,
5366 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005367 if (!TagDecl)
5368 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005369
Douglas Gregor42af25f2009-05-11 19:58:34 +00005370 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005371
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005372 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5373 if (l->getKind() != AttributeList::AT_Visibility)
5374 continue;
5375 l->setInvalid();
5376 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5377 l->getName();
5378 }
5379
David Blaikie77b6de02011-09-22 02:58:26 +00005380 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005381 // strict aliasing violation!
5382 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005383 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005384
Douglas Gregor23c94db2010-07-02 17:43:08 +00005385 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005386 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005387}
5388
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005389/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5390/// special functions, such as the default constructor, copy
5391/// constructor, or destructor, to the given C++ class (C++
5392/// [special]p1). This routine can only be executed just before the
5393/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005394void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005395 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005396 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005397
Richard Smithbc2a35d2012-12-08 08:32:28 +00005398 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005399 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005400
Richard Smithbc2a35d2012-12-08 08:32:28 +00005401 // If the properties or semantics of the copy constructor couldn't be
5402 // determined while the class was being declared, force a declaration
5403 // of it now.
5404 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5405 DeclareImplicitCopyConstructor(ClassDecl);
5406 }
5407
5408 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005409 ++ASTContext::NumImplicitMoveConstructors;
5410
Richard Smithbc2a35d2012-12-08 08:32:28 +00005411 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5412 DeclareImplicitMoveConstructor(ClassDecl);
5413 }
5414
Douglas Gregora376d102010-07-02 21:50:04 +00005415 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5416 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005417
5418 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005419 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005420 // it shows up in the right place in the vtable and that we diagnose
5421 // problems with the implicit exception specification.
5422 if (ClassDecl->isDynamicClass() ||
5423 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005424 DeclareImplicitCopyAssignment(ClassDecl);
5425 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005426
Richard Smith1c931be2012-04-02 18:40:40 +00005427 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005428 ++ASTContext::NumImplicitMoveAssignmentOperators;
5429
5430 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005431 if (ClassDecl->isDynamicClass() ||
5432 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005433 DeclareImplicitMoveAssignment(ClassDecl);
5434 }
5435
Douglas Gregor4923aa22010-07-02 20:37:36 +00005436 if (!ClassDecl->hasUserDeclaredDestructor()) {
5437 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005438
5439 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005440 // have to declare the destructor immediately. This ensures that, e.g., it
5441 // shows up in the right place in the vtable and that we diagnose problems
5442 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005443 if (ClassDecl->isDynamicClass() ||
5444 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005445 DeclareImplicitDestructor(ClassDecl);
5446 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005447}
5448
Francois Pichet8387e2a2011-04-22 22:18:13 +00005449void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5450 if (!D)
5451 return;
5452
5453 int NumParamList = D->getNumTemplateParameterLists();
5454 for (int i = 0; i < NumParamList; i++) {
5455 TemplateParameterList* Params = D->getTemplateParameterList(i);
5456 for (TemplateParameterList::iterator Param = Params->begin(),
5457 ParamEnd = Params->end();
5458 Param != ParamEnd; ++Param) {
5459 NamedDecl *Named = cast<NamedDecl>(*Param);
5460 if (Named->getDeclName()) {
5461 S->AddDecl(Named);
5462 IdResolver.AddDecl(Named);
5463 }
5464 }
5465 }
5466}
5467
John McCalld226f652010-08-21 09:40:31 +00005468void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005469 if (!D)
5470 return;
5471
5472 TemplateParameterList *Params = 0;
5473 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5474 Params = Template->getTemplateParameters();
5475 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5476 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5477 Params = PartialSpec->getTemplateParameters();
5478 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005479 return;
5480
Douglas Gregor6569d682009-05-27 23:11:45 +00005481 for (TemplateParameterList::iterator Param = Params->begin(),
5482 ParamEnd = Params->end();
5483 Param != ParamEnd; ++Param) {
5484 NamedDecl *Named = cast<NamedDecl>(*Param);
5485 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005486 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005487 IdResolver.AddDecl(Named);
5488 }
5489 }
5490}
5491
John McCalld226f652010-08-21 09:40:31 +00005492void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005493 if (!RecordD) return;
5494 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005495 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005496 PushDeclContext(S, Record);
5497}
5498
John McCalld226f652010-08-21 09:40:31 +00005499void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005500 if (!RecordD) return;
5501 PopDeclContext();
5502}
5503
Douglas Gregor72b505b2008-12-16 21:30:33 +00005504/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5505/// parsing a top-level (non-nested) C++ class, and we are now
5506/// parsing those parts of the given Method declaration that could
5507/// not be parsed earlier (C++ [class.mem]p2), such as default
5508/// arguments. This action should enter the scope of the given
5509/// Method declaration as if we had just parsed the qualified method
5510/// name. However, it should not bring the parameters into scope;
5511/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005512void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005513}
5514
5515/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5516/// C++ method declaration. We're (re-)introducing the given
5517/// function parameter into scope for use in parsing later parts of
5518/// the method declaration. For example, we could see an
5519/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005520void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005521 if (!ParamD)
5522 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005523
John McCalld226f652010-08-21 09:40:31 +00005524 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005525
5526 // If this parameter has an unparsed default argument, clear it out
5527 // to make way for the parsed default argument.
5528 if (Param->hasUnparsedDefaultArg())
5529 Param->setDefaultArg(0);
5530
John McCalld226f652010-08-21 09:40:31 +00005531 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005532 if (Param->getDeclName())
5533 IdResolver.AddDecl(Param);
5534}
5535
5536/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5537/// processing the delayed method declaration for Method. The method
5538/// declaration is now considered finished. There may be a separate
5539/// ActOnStartOfFunctionDef action later (not necessarily
5540/// immediately!) for this method, if it was also defined inside the
5541/// class body.
John McCalld226f652010-08-21 09:40:31 +00005542void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005543 if (!MethodD)
5544 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005545
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005546 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005547
John McCalld226f652010-08-21 09:40:31 +00005548 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005549
5550 // Now that we have our default arguments, check the constructor
5551 // again. It could produce additional diagnostics or affect whether
5552 // the class has implicitly-declared destructors, among other
5553 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005554 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5555 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005556
5557 // Check the default arguments, which we may have added.
5558 if (!Method->isInvalidDecl())
5559 CheckCXXDefaultArguments(Method);
5560}
5561
Douglas Gregor42a552f2008-11-05 20:51:48 +00005562/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005563/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005564/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005565/// emit diagnostics and set the invalid bit to true. In any case, the type
5566/// will be updated to reflect a well-formed type for the constructor and
5567/// returned.
5568QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005569 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005570 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005571
5572 // C++ [class.ctor]p3:
5573 // A constructor shall not be virtual (10.3) or static (9.4). A
5574 // constructor can be invoked for a const, volatile or const
5575 // volatile object. A constructor shall not be declared const,
5576 // volatile, or const volatile (9.3.2).
5577 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005578 if (!D.isInvalidType())
5579 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5580 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5581 << SourceRange(D.getIdentifierLoc());
5582 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005583 }
John McCalld931b082010-08-26 03:08:43 +00005584 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005585 if (!D.isInvalidType())
5586 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5587 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5588 << SourceRange(D.getIdentifierLoc());
5589 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005590 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005591 }
Mike Stump1eb44332009-09-09 15:08:12 +00005592
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005593 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005594 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005595 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005596 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5597 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005598 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005599 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5600 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005601 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005602 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5603 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005604 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005605 }
Mike Stump1eb44332009-09-09 15:08:12 +00005606
Douglas Gregorc938c162011-01-26 05:01:58 +00005607 // C++0x [class.ctor]p4:
5608 // A constructor shall not be declared with a ref-qualifier.
5609 if (FTI.hasRefQualifier()) {
5610 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5611 << FTI.RefQualifierIsLValueRef
5612 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5613 D.setInvalidType();
5614 }
5615
Douglas Gregor42a552f2008-11-05 20:51:48 +00005616 // Rebuild the function type "R" without any type qualifiers (in
5617 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005618 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005619 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005620 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5621 return R;
5622
5623 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5624 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005625 EPI.RefQualifier = RQ_None;
5626
Chris Lattner65401802009-04-25 08:28:21 +00005627 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005628 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005629}
5630
Douglas Gregor72b505b2008-12-16 21:30:33 +00005631/// CheckConstructor - Checks a fully-formed constructor for
5632/// well-formedness, issuing any diagnostics required. Returns true if
5633/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005634void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005635 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005636 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5637 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005638 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005639
5640 // C++ [class.copy]p3:
5641 // A declaration of a constructor for a class X is ill-formed if
5642 // its first parameter is of type (optionally cv-qualified) X and
5643 // either there are no other parameters or else all other
5644 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005645 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005646 ((Constructor->getNumParams() == 1) ||
5647 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005648 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5649 Constructor->getTemplateSpecializationKind()
5650 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005651 QualType ParamType = Constructor->getParamDecl(0)->getType();
5652 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5653 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005654 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005655 const char *ConstRef
5656 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5657 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005658 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005659 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005660
5661 // FIXME: Rather that making the constructor invalid, we should endeavor
5662 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005663 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005664 }
5665 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005666}
5667
John McCall15442822010-08-04 01:04:25 +00005668/// CheckDestructor - Checks a fully-formed destructor definition for
5669/// well-formedness, issuing any diagnostics required. Returns true
5670/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005671bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005672 CXXRecordDecl *RD = Destructor->getParent();
5673
5674 if (Destructor->isVirtual()) {
5675 SourceLocation Loc;
5676
5677 if (!Destructor->isImplicit())
5678 Loc = Destructor->getLocation();
5679 else
5680 Loc = RD->getLocation();
5681
5682 // If we have a virtual destructor, look up the deallocation function
5683 FunctionDecl *OperatorDelete = 0;
5684 DeclarationName Name =
5685 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005686 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005687 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005688
Eli Friedman5f2987c2012-02-02 03:46:19 +00005689 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005690
5691 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005692 }
Anders Carlsson37909802009-11-30 21:24:50 +00005693
5694 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005695}
5696
Mike Stump1eb44332009-09-09 15:08:12 +00005697static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005698FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5699 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5700 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005701 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005702}
5703
Douglas Gregor42a552f2008-11-05 20:51:48 +00005704/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5705/// the well-formednes of the destructor declarator @p D with type @p
5706/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005707/// emit diagnostics and set the declarator to invalid. Even if this happens,
5708/// will be updated to reflect a well-formed type for the destructor and
5709/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005710QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005711 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005712 // C++ [class.dtor]p1:
5713 // [...] A typedef-name that names a class is a class-name
5714 // (7.1.3); however, a typedef-name that names a class shall not
5715 // be used as the identifier in the declarator for a destructor
5716 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005717 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005718 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005719 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005720 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005721 else if (const TemplateSpecializationType *TST =
5722 DeclaratorType->getAs<TemplateSpecializationType>())
5723 if (TST->isTypeAlias())
5724 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5725 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005726
5727 // C++ [class.dtor]p2:
5728 // A destructor is used to destroy objects of its class type. A
5729 // destructor takes no parameters, and no return type can be
5730 // specified for it (not even void). The address of a destructor
5731 // shall not be taken. A destructor shall not be static. A
5732 // destructor can be invoked for a const, volatile or const
5733 // volatile object. A destructor shall not be declared const,
5734 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005735 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005736 if (!D.isInvalidType())
5737 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5738 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005739 << SourceRange(D.getIdentifierLoc())
5740 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5741
John McCalld931b082010-08-26 03:08:43 +00005742 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005743 }
Chris Lattner65401802009-04-25 08:28:21 +00005744 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005745 // Destructors don't have return types, but the parser will
5746 // happily parse something like:
5747 //
5748 // class X {
5749 // float ~X();
5750 // };
5751 //
5752 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005753 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5754 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5755 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005756 }
Mike Stump1eb44332009-09-09 15:08:12 +00005757
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005758 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005759 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005760 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005761 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5762 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005763 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005764 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5765 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005766 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005767 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5768 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005769 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005770 }
5771
Douglas Gregorc938c162011-01-26 05:01:58 +00005772 // C++0x [class.dtor]p2:
5773 // A destructor shall not be declared with a ref-qualifier.
5774 if (FTI.hasRefQualifier()) {
5775 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5776 << FTI.RefQualifierIsLValueRef
5777 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5778 D.setInvalidType();
5779 }
5780
Douglas Gregor42a552f2008-11-05 20:51:48 +00005781 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005782 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005783 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5784
5785 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005786 FTI.freeArgs();
5787 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005788 }
5789
Mike Stump1eb44332009-09-09 15:08:12 +00005790 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005791 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005792 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005793 D.setInvalidType();
5794 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005795
5796 // Rebuild the function type "R" without any type qualifiers or
5797 // parameters (in case any of the errors above fired) and with
5798 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005799 // types.
John McCalle23cf432010-12-14 08:05:40 +00005800 if (!D.isInvalidType())
5801 return R;
5802
Douglas Gregord92ec472010-07-01 05:10:53 +00005803 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005804 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5805 EPI.Variadic = false;
5806 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005807 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005808 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005809}
5810
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005811/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5812/// well-formednes of the conversion function declarator @p D with
5813/// type @p R. If there are any errors in the declarator, this routine
5814/// will emit diagnostics and return true. Otherwise, it will return
5815/// false. Either way, the type @p R will be updated to reflect a
5816/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005817void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005818 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005819 // C++ [class.conv.fct]p1:
5820 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005821 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005822 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005823 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005824 if (!D.isInvalidType())
5825 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5826 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5827 << SourceRange(D.getIdentifierLoc());
5828 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005829 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005830 }
John McCalla3f81372010-04-13 00:04:31 +00005831
5832 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5833
Chris Lattner6e475012009-04-25 08:35:12 +00005834 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005835 // Conversion functions don't have return types, but the parser will
5836 // happily parse something like:
5837 //
5838 // class X {
5839 // float operator bool();
5840 // };
5841 //
5842 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005843 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5844 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5845 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005846 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005847 }
5848
John McCalla3f81372010-04-13 00:04:31 +00005849 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5850
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005851 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005852 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005853 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5854
5855 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005856 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005857 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005858 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005859 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005860 D.setInvalidType();
5861 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005862
John McCalla3f81372010-04-13 00:04:31 +00005863 // Diagnose "&operator bool()" and other such nonsense. This
5864 // is actually a gcc extension which we don't support.
5865 if (Proto->getResultType() != ConvType) {
5866 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5867 << Proto->getResultType();
5868 D.setInvalidType();
5869 ConvType = Proto->getResultType();
5870 }
5871
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005872 // C++ [class.conv.fct]p4:
5873 // The conversion-type-id shall not represent a function type nor
5874 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005875 if (ConvType->isArrayType()) {
5876 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5877 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005878 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005879 } else if (ConvType->isFunctionType()) {
5880 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5881 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005882 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005883 }
5884
5885 // Rebuild the function type "R" without any parameters (in case any
5886 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005887 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005888 if (D.isInvalidType())
5889 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005890
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005891 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005892 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005893 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005894 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005895 diag::warn_cxx98_compat_explicit_conversion_functions :
5896 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005897 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005898}
5899
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005900/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5901/// the declaration of the given C++ conversion function. This routine
5902/// is responsible for recording the conversion function in the C++
5903/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005904Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005905 assert(Conversion && "Expected to receive a conversion function declaration");
5906
Douglas Gregor9d350972008-12-12 08:25:50 +00005907 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005908
5909 // Make sure we aren't redeclaring the conversion function.
5910 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005911
5912 // C++ [class.conv.fct]p1:
5913 // [...] A conversion function is never used to convert a
5914 // (possibly cv-qualified) object to the (possibly cv-qualified)
5915 // same object type (or a reference to it), to a (possibly
5916 // cv-qualified) base class of that type (or a reference to it),
5917 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005918 // FIXME: Suppress this warning if the conversion function ends up being a
5919 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005920 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005921 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005922 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005923 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005924 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5925 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005926 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005927 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005928 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5929 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005930 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005931 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005932 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005933 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005934 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005935 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005936 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005937 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005938 }
5939
Douglas Gregore80622f2010-09-29 04:25:11 +00005940 if (FunctionTemplateDecl *ConversionTemplate
5941 = Conversion->getDescribedFunctionTemplate())
5942 return ConversionTemplate;
5943
John McCalld226f652010-08-21 09:40:31 +00005944 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005945}
5946
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005947//===----------------------------------------------------------------------===//
5948// Namespace Handling
5949//===----------------------------------------------------------------------===//
5950
Richard Smithd1a55a62012-10-04 22:13:39 +00005951/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5952/// reopened.
5953static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5954 SourceLocation Loc,
5955 IdentifierInfo *II, bool *IsInline,
5956 NamespaceDecl *PrevNS) {
5957 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00005958
Richard Smithc969e6a2012-10-05 01:46:25 +00005959 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5960 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5961 // inline namespaces, with the intention of bringing names into namespace std.
5962 //
5963 // We support this just well enough to get that case working; this is not
5964 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00005965 if (*IsInline && II && II->getName().startswith("__atomic") &&
5966 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00005967 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00005968 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5969 NS = NS->getPreviousDecl())
5970 NS->setInline(*IsInline);
5971 // Patch up the lookup table for the containing namespace. This isn't really
5972 // correct, but it's good enough for this particular case.
5973 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5974 E = PrevNS->decls_end(); I != E; ++I)
5975 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5976 PrevNS->getParent()->makeDeclVisibleInContext(ND);
5977 return;
5978 }
5979
5980 if (PrevNS->isInline())
5981 // The user probably just forgot the 'inline', so suggest that it
5982 // be added back.
5983 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5984 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
5985 else
5986 S.Diag(Loc, diag::err_inline_namespace_mismatch)
5987 << IsInline;
5988
5989 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
5990 *IsInline = PrevNS->isInline();
5991}
John McCallea318642010-08-26 09:15:37 +00005992
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005993/// ActOnStartNamespaceDef - This is called at the start of a namespace
5994/// definition.
John McCalld226f652010-08-21 09:40:31 +00005995Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005996 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005997 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005998 SourceLocation IdentLoc,
5999 IdentifierInfo *II,
6000 SourceLocation LBrace,
6001 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006002 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6003 // For anonymous namespace, take the location of the left brace.
6004 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006005 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006006 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006007 bool IsStd = false;
6008 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006009 Scope *DeclRegionScope = NamespcScope->getParent();
6010
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006011 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006012 if (II) {
6013 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006014 // The identifier in an original-namespace-definition shall not
6015 // have been previously defined in the declarative region in
6016 // which the original-namespace-definition appears. The
6017 // identifier in an original-namespace-definition is the name of
6018 // the namespace. Subsequently in that declarative region, it is
6019 // treated as an original-namespace-name.
6020 //
6021 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006022 // look through using directives, just look for any ordinary names.
6023
6024 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006025 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6026 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006027 NamedDecl *PrevDecl = 0;
6028 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006029 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00006030 R.first != R.second; ++R.first) {
6031 if ((*R.first)->getIdentifierNamespace() & IDNS) {
6032 PrevDecl = *R.first;
6033 break;
6034 }
6035 }
6036
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006037 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6038
6039 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006040 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006041 if (IsInline != PrevNS->isInline())
6042 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6043 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006044 } else if (PrevDecl) {
6045 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006046 Diag(Loc, diag::err_redefinition_different_kind)
6047 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006048 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006049 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006050 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006051 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006052 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006053 // This is the first "real" definition of the namespace "std", so update
6054 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006055 PrevNS = getStdNamespace();
6056 IsStd = true;
6057 AddToKnown = !IsInline;
6058 } else {
6059 // We've seen this namespace for the first time.
6060 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006061 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006062 } else {
John McCall9aeed322009-10-01 00:25:31 +00006063 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006064
6065 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006066 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006067 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006068 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006069 } else {
6070 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006071 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006072 }
6073
Richard Smithd1a55a62012-10-04 22:13:39 +00006074 if (PrevNS && IsInline != PrevNS->isInline())
6075 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6076 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006077 }
6078
6079 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6080 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006081 if (IsInvalid)
6082 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006083
6084 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006085
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006086 // FIXME: Should we be merging attributes?
6087 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006088 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006089
6090 if (IsStd)
6091 StdNamespace = Namespc;
6092 if (AddToKnown)
6093 KnownNamespaces[Namespc] = false;
6094
6095 if (II) {
6096 PushOnScopeChains(Namespc, DeclRegionScope);
6097 } else {
6098 // Link the anonymous namespace into its parent.
6099 DeclContext *Parent = CurContext->getRedeclContext();
6100 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6101 TU->setAnonymousNamespace(Namespc);
6102 } else {
6103 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006104 }
John McCall9aeed322009-10-01 00:25:31 +00006105
Douglas Gregora4181472010-03-24 00:46:35 +00006106 CurContext->addDecl(Namespc);
6107
John McCall9aeed322009-10-01 00:25:31 +00006108 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6109 // behaves as if it were replaced by
6110 // namespace unique { /* empty body */ }
6111 // using namespace unique;
6112 // namespace unique { namespace-body }
6113 // where all occurrences of 'unique' in a translation unit are
6114 // replaced by the same identifier and this identifier differs
6115 // from all other identifiers in the entire program.
6116
6117 // We just create the namespace with an empty name and then add an
6118 // implicit using declaration, just like the standard suggests.
6119 //
6120 // CodeGen enforces the "universally unique" aspect by giving all
6121 // declarations semantically contained within an anonymous
6122 // namespace internal linkage.
6123
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006124 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006125 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006126 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006127 /* 'using' */ LBrace,
6128 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006129 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006130 /* identifier */ SourceLocation(),
6131 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006132 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006133 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006134 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006135 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006136 }
6137
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006138 ActOnDocumentableDecl(Namespc);
6139
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006140 // Although we could have an invalid decl (i.e. the namespace name is a
6141 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006142 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6143 // for the namespace has the declarations that showed up in that particular
6144 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006145 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006146 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006147}
6148
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006149/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6150/// is a namespace alias, returns the namespace it points to.
6151static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6152 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6153 return AD->getNamespace();
6154 return dyn_cast_or_null<NamespaceDecl>(D);
6155}
6156
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006157/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6158/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006159void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006160 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6161 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006162 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006163 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006164 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006165 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006166}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006167
John McCall384aff82010-08-25 07:42:41 +00006168CXXRecordDecl *Sema::getStdBadAlloc() const {
6169 return cast_or_null<CXXRecordDecl>(
6170 StdBadAlloc.get(Context.getExternalSource()));
6171}
6172
6173NamespaceDecl *Sema::getStdNamespace() const {
6174 return cast_or_null<NamespaceDecl>(
6175 StdNamespace.get(Context.getExternalSource()));
6176}
6177
Douglas Gregor66992202010-06-29 17:53:46 +00006178/// \brief Retrieve the special "std" namespace, which may require us to
6179/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006180NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006181 if (!StdNamespace) {
6182 // The "std" namespace has not yet been defined, so build one implicitly.
6183 StdNamespace = NamespaceDecl::Create(Context,
6184 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006185 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006186 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006187 &PP.getIdentifierTable().get("std"),
6188 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006189 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006190 }
6191
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006192 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006193}
6194
Sebastian Redl395e04d2012-01-17 22:49:33 +00006195bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006196 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006197 "Looking for std::initializer_list outside of C++.");
6198
6199 // We're looking for implicit instantiations of
6200 // template <typename E> class std::initializer_list.
6201
6202 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6203 return false;
6204
Sebastian Redl84760e32012-01-17 22:49:58 +00006205 ClassTemplateDecl *Template = 0;
6206 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006207
Sebastian Redl84760e32012-01-17 22:49:58 +00006208 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006209
Sebastian Redl84760e32012-01-17 22:49:58 +00006210 ClassTemplateSpecializationDecl *Specialization =
6211 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6212 if (!Specialization)
6213 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006214
Sebastian Redl84760e32012-01-17 22:49:58 +00006215 Template = Specialization->getSpecializedTemplate();
6216 Arguments = Specialization->getTemplateArgs().data();
6217 } else if (const TemplateSpecializationType *TST =
6218 Ty->getAs<TemplateSpecializationType>()) {
6219 Template = dyn_cast_or_null<ClassTemplateDecl>(
6220 TST->getTemplateName().getAsTemplateDecl());
6221 Arguments = TST->getArgs();
6222 }
6223 if (!Template)
6224 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006225
6226 if (!StdInitializerList) {
6227 // Haven't recognized std::initializer_list yet, maybe this is it.
6228 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6229 if (TemplateClass->getIdentifier() !=
6230 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006231 !getStdNamespace()->InEnclosingNamespaceSetOf(
6232 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006233 return false;
6234 // This is a template called std::initializer_list, but is it the right
6235 // template?
6236 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006237 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006238 return false;
6239 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6240 return false;
6241
6242 // It's the right template.
6243 StdInitializerList = Template;
6244 }
6245
6246 if (Template != StdInitializerList)
6247 return false;
6248
6249 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006250 if (Element)
6251 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006252 return true;
6253}
6254
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006255static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6256 NamespaceDecl *Std = S.getStdNamespace();
6257 if (!Std) {
6258 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6259 return 0;
6260 }
6261
6262 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6263 Loc, Sema::LookupOrdinaryName);
6264 if (!S.LookupQualifiedName(Result, Std)) {
6265 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6266 return 0;
6267 }
6268 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6269 if (!Template) {
6270 Result.suppressDiagnostics();
6271 // We found something weird. Complain about the first thing we found.
6272 NamedDecl *Found = *Result.begin();
6273 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6274 return 0;
6275 }
6276
6277 // We found some template called std::initializer_list. Now verify that it's
6278 // correct.
6279 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006280 if (Params->getMinRequiredArguments() != 1 ||
6281 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006282 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6283 return 0;
6284 }
6285
6286 return Template;
6287}
6288
6289QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6290 if (!StdInitializerList) {
6291 StdInitializerList = LookupStdInitializerList(*this, Loc);
6292 if (!StdInitializerList)
6293 return QualType();
6294 }
6295
6296 TemplateArgumentListInfo Args(Loc, Loc);
6297 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6298 Context.getTrivialTypeSourceInfo(Element,
6299 Loc)));
6300 return Context.getCanonicalType(
6301 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6302}
6303
Sebastian Redl98d36062012-01-17 22:50:14 +00006304bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6305 // C++ [dcl.init.list]p2:
6306 // A constructor is an initializer-list constructor if its first parameter
6307 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6308 // std::initializer_list<E> for some type E, and either there are no other
6309 // parameters or else all other parameters have default arguments.
6310 if (Ctor->getNumParams() < 1 ||
6311 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6312 return false;
6313
6314 QualType ArgType = Ctor->getParamDecl(0)->getType();
6315 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6316 ArgType = RT->getPointeeType().getUnqualifiedType();
6317
6318 return isStdInitializerList(ArgType, 0);
6319}
6320
Douglas Gregor9172aa62011-03-26 22:25:30 +00006321/// \brief Determine whether a using statement is in a context where it will be
6322/// apply in all contexts.
6323static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6324 switch (CurContext->getDeclKind()) {
6325 case Decl::TranslationUnit:
6326 return true;
6327 case Decl::LinkageSpec:
6328 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6329 default:
6330 return false;
6331 }
6332}
6333
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006334namespace {
6335
6336// Callback to only accept typo corrections that are namespaces.
6337class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6338 public:
6339 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6340 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6341 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6342 }
6343 return false;
6344 }
6345};
6346
6347}
6348
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006349static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6350 CXXScopeSpec &SS,
6351 SourceLocation IdentLoc,
6352 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006353 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006354 R.clear();
6355 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006356 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006357 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006358 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6359 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006360 if (DeclContext *DC = S.computeDeclContext(SS, false))
6361 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6362 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006363 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6364 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006365 else
6366 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6367 << Ident << CorrectedQuotedStr
6368 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006369
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006370 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6371 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006372
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006373 R.addDecl(Corrected.getCorrectionDecl());
6374 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006375 }
6376 return false;
6377}
6378
John McCalld226f652010-08-21 09:40:31 +00006379Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006380 SourceLocation UsingLoc,
6381 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006382 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006383 SourceLocation IdentLoc,
6384 IdentifierInfo *NamespcName,
6385 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006386 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6387 assert(NamespcName && "Invalid NamespcName.");
6388 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006389
6390 // This can only happen along a recovery path.
6391 while (S->getFlags() & Scope::TemplateParamScope)
6392 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006393 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006394
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006395 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006396 NestedNameSpecifier *Qualifier = 0;
6397 if (SS.isSet())
6398 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6399
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006400 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006401 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6402 LookupParsedName(R, S, &SS);
6403 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006404 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006405
Douglas Gregor66992202010-06-29 17:53:46 +00006406 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006407 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006408 // Allow "using namespace std;" or "using namespace ::std;" even if
6409 // "std" hasn't been defined yet, for GCC compatibility.
6410 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6411 NamespcName->isStr("std")) {
6412 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006413 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006414 R.resolveKind();
6415 }
6416 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006417 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006418 }
6419
John McCallf36e02d2009-10-09 21:13:30 +00006420 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006421 NamedDecl *Named = R.getFoundDecl();
6422 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6423 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006424 // C++ [namespace.udir]p1:
6425 // A using-directive specifies that the names in the nominated
6426 // namespace can be used in the scope in which the
6427 // using-directive appears after the using-directive. During
6428 // unqualified name lookup (3.4.1), the names appear as if they
6429 // were declared in the nearest enclosing namespace which
6430 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006431 // namespace. [Note: in this context, "contains" means "contains
6432 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006433
6434 // Find enclosing context containing both using-directive and
6435 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006436 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006437 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6438 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6439 CommonAncestor = CommonAncestor->getParent();
6440
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006441 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006442 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006443 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006444
Douglas Gregor9172aa62011-03-26 22:25:30 +00006445 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006446 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006447 Diag(IdentLoc, diag::warn_using_directive_in_header);
6448 }
6449
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006450 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006451 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006452 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006453 }
6454
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006455 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006456 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006457}
6458
6459void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006460 // If the scope has an associated entity and the using directive is at
6461 // namespace or translation unit scope, add the UsingDirectiveDecl into
6462 // its lookup structure so qualified name lookup can find it.
6463 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6464 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006465 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006466 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006467 // Otherwise, it is at block sope. The using-directives will affect lookup
6468 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006469 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006470}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006471
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006472
John McCalld226f652010-08-21 09:40:31 +00006473Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006474 AccessSpecifier AS,
6475 bool HasUsingKeyword,
6476 SourceLocation UsingLoc,
6477 CXXScopeSpec &SS,
6478 UnqualifiedId &Name,
6479 AttributeList *AttrList,
6480 bool IsTypeName,
6481 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006482 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006483
Douglas Gregor12c118a2009-11-04 16:30:06 +00006484 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006485 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006486 case UnqualifiedId::IK_Identifier:
6487 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006488 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006489 case UnqualifiedId::IK_ConversionFunctionId:
6490 break;
6491
6492 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006493 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006494 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006495 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006496 getLangOpts().CPlusPlus0x ?
Richard Smitha1366cb2012-04-27 19:33:05 +00006497 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6498 // instead once inheriting constructors work.
6499 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00006500 diag::err_using_decl_constructor)
6501 << SS.getRange();
6502
David Blaikie4e4d0842012-03-11 07:00:24 +00006503 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00006504
John McCalld226f652010-08-21 09:40:31 +00006505 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006506
6507 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006508 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006509 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006510 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006511
6512 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006513 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006514 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006515 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006516 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006517
6518 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6519 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006520 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006521 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006522
John McCall60fa3cf2009-12-11 02:10:03 +00006523 // Warn about using declarations.
6524 // TODO: store that the declaration was written without 'using' and
6525 // talk about access decls instead of using decls in the
6526 // diagnostics.
6527 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006528 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006529
6530 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006531 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006532 }
6533
Douglas Gregor56c04582010-12-16 00:46:58 +00006534 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6535 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6536 return 0;
6537
John McCall9488ea12009-11-17 05:59:44 +00006538 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006539 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006540 /* IsInstantiation */ false,
6541 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006542 if (UD)
6543 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006544
John McCalld226f652010-08-21 09:40:31 +00006545 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006546}
6547
Douglas Gregor09acc982010-07-07 23:08:52 +00006548/// \brief Determine whether a using declaration considers the given
6549/// declarations as "equivalent", e.g., if they are redeclarations of
6550/// the same entity or are both typedefs of the same type.
6551static bool
6552IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6553 bool &SuppressRedeclaration) {
6554 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6555 SuppressRedeclaration = false;
6556 return true;
6557 }
6558
Richard Smith162e1c12011-04-15 14:24:37 +00006559 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6560 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006561 SuppressRedeclaration = true;
6562 return Context.hasSameType(TD1->getUnderlyingType(),
6563 TD2->getUnderlyingType());
6564 }
6565
6566 return false;
6567}
6568
6569
John McCall9f54ad42009-12-10 09:41:52 +00006570/// Determines whether to create a using shadow decl for a particular
6571/// decl, given the set of decls existing prior to this using lookup.
6572bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6573 const LookupResult &Previous) {
6574 // Diagnose finding a decl which is not from a base class of the
6575 // current class. We do this now because there are cases where this
6576 // function will silently decide not to build a shadow decl, which
6577 // will pre-empt further diagnostics.
6578 //
6579 // We don't need to do this in C++0x because we do the check once on
6580 // the qualifier.
6581 //
6582 // FIXME: diagnose the following if we care enough:
6583 // struct A { int foo; };
6584 // struct B : A { using A::foo; };
6585 // template <class T> struct C : A {};
6586 // template <class T> struct D : C<T> { using B::foo; } // <---
6587 // This is invalid (during instantiation) in C++03 because B::foo
6588 // resolves to the using decl in B, which is not a base class of D<T>.
6589 // We can't diagnose it immediately because C<T> is an unknown
6590 // specialization. The UsingShadowDecl in D<T> then points directly
6591 // to A::foo, which will look well-formed when we instantiate.
6592 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00006593 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006594 DeclContext *OrigDC = Orig->getDeclContext();
6595
6596 // Handle enums and anonymous structs.
6597 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6598 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6599 while (OrigRec->isAnonymousStructOrUnion())
6600 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6601
6602 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6603 if (OrigDC == CurContext) {
6604 Diag(Using->getLocation(),
6605 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006606 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006607 Diag(Orig->getLocation(), diag::note_using_decl_target);
6608 return true;
6609 }
6610
Douglas Gregordc355712011-02-25 00:36:19 +00006611 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006612 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006613 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006614 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006615 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006616 Diag(Orig->getLocation(), diag::note_using_decl_target);
6617 return true;
6618 }
6619 }
6620
6621 if (Previous.empty()) return false;
6622
6623 NamedDecl *Target = Orig;
6624 if (isa<UsingShadowDecl>(Target))
6625 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6626
John McCalld7533ec2009-12-11 02:33:26 +00006627 // If the target happens to be one of the previous declarations, we
6628 // don't have a conflict.
6629 //
6630 // FIXME: but we might be increasing its access, in which case we
6631 // should redeclare it.
6632 NamedDecl *NonTag = 0, *Tag = 0;
6633 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6634 I != E; ++I) {
6635 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006636 bool Result;
6637 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6638 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006639
6640 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6641 }
6642
John McCall9f54ad42009-12-10 09:41:52 +00006643 if (Target->isFunctionOrFunctionTemplate()) {
6644 FunctionDecl *FD;
6645 if (isa<FunctionTemplateDecl>(Target))
6646 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6647 else
6648 FD = cast<FunctionDecl>(Target);
6649
6650 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006651 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006652 case Ovl_Overload:
6653 return false;
6654
6655 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006656 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006657 break;
6658
6659 // We found a decl with the exact signature.
6660 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006661 // If we're in a record, we want to hide the target, so we
6662 // return true (without a diagnostic) to tell the caller not to
6663 // build a shadow decl.
6664 if (CurContext->isRecord())
6665 return true;
6666
6667 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006668 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006669 break;
6670 }
6671
6672 Diag(Target->getLocation(), diag::note_using_decl_target);
6673 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6674 return true;
6675 }
6676
6677 // Target is not a function.
6678
John McCall9f54ad42009-12-10 09:41:52 +00006679 if (isa<TagDecl>(Target)) {
6680 // No conflict between a tag and a non-tag.
6681 if (!Tag) return false;
6682
John McCall41ce66f2009-12-10 19:51:03 +00006683 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006684 Diag(Target->getLocation(), diag::note_using_decl_target);
6685 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6686 return true;
6687 }
6688
6689 // No conflict between a tag and a non-tag.
6690 if (!NonTag) return false;
6691
John McCall41ce66f2009-12-10 19:51:03 +00006692 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006693 Diag(Target->getLocation(), diag::note_using_decl_target);
6694 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6695 return true;
6696}
6697
John McCall9488ea12009-11-17 05:59:44 +00006698/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006699UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006700 UsingDecl *UD,
6701 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006702
6703 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006704 NamedDecl *Target = Orig;
6705 if (isa<UsingShadowDecl>(Target)) {
6706 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6707 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006708 }
6709
6710 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006711 = UsingShadowDecl::Create(Context, CurContext,
6712 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006713 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006714
6715 Shadow->setAccess(UD->getAccess());
6716 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6717 Shadow->setInvalidDecl();
6718
John McCall9488ea12009-11-17 05:59:44 +00006719 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006720 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006721 else
John McCall604e7f12009-12-08 07:46:18 +00006722 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006723
John McCall604e7f12009-12-08 07:46:18 +00006724
John McCall9f54ad42009-12-10 09:41:52 +00006725 return Shadow;
6726}
John McCall604e7f12009-12-08 07:46:18 +00006727
John McCall9f54ad42009-12-10 09:41:52 +00006728/// Hides a using shadow declaration. This is required by the current
6729/// using-decl implementation when a resolvable using declaration in a
6730/// class is followed by a declaration which would hide or override
6731/// one or more of the using decl's targets; for example:
6732///
6733/// struct Base { void foo(int); };
6734/// struct Derived : Base {
6735/// using Base::foo;
6736/// void foo(int);
6737/// };
6738///
6739/// The governing language is C++03 [namespace.udecl]p12:
6740///
6741/// When a using-declaration brings names from a base class into a
6742/// derived class scope, member functions in the derived class
6743/// override and/or hide member functions with the same name and
6744/// parameter types in a base class (rather than conflicting).
6745///
6746/// There are two ways to implement this:
6747/// (1) optimistically create shadow decls when they're not hidden
6748/// by existing declarations, or
6749/// (2) don't create any shadow decls (or at least don't make them
6750/// visible) until we've fully parsed/instantiated the class.
6751/// The problem with (1) is that we might have to retroactively remove
6752/// a shadow decl, which requires several O(n) operations because the
6753/// decl structures are (very reasonably) not designed for removal.
6754/// (2) avoids this but is very fiddly and phase-dependent.
6755void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006756 if (Shadow->getDeclName().getNameKind() ==
6757 DeclarationName::CXXConversionFunctionName)
6758 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6759
John McCall9f54ad42009-12-10 09:41:52 +00006760 // Remove it from the DeclContext...
6761 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006762
John McCall9f54ad42009-12-10 09:41:52 +00006763 // ...and the scope, if applicable...
6764 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006765 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006766 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006767 }
6768
John McCall9f54ad42009-12-10 09:41:52 +00006769 // ...and the using decl.
6770 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6771
6772 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006773 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006774}
6775
John McCall7ba107a2009-11-18 02:36:19 +00006776/// Builds a using declaration.
6777///
6778/// \param IsInstantiation - Whether this call arises from an
6779/// instantiation of an unresolved using declaration. We treat
6780/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006781NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6782 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006783 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006784 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006785 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006786 bool IsInstantiation,
6787 bool IsTypeName,
6788 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006789 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006790 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006791 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006792
Anders Carlsson550b14b2009-08-28 05:49:21 +00006793 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006794
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006795 if (SS.isEmpty()) {
6796 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006797 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006798 }
Mike Stump1eb44332009-09-09 15:08:12 +00006799
John McCall9f54ad42009-12-10 09:41:52 +00006800 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006801 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006802 ForRedeclaration);
6803 Previous.setHideTags(false);
6804 if (S) {
6805 LookupName(Previous, S);
6806
6807 // It is really dumb that we have to do this.
6808 LookupResult::Filter F = Previous.makeFilter();
6809 while (F.hasNext()) {
6810 NamedDecl *D = F.next();
6811 if (!isDeclInScope(D, CurContext, S))
6812 F.erase();
6813 }
6814 F.done();
6815 } else {
6816 assert(IsInstantiation && "no scope in non-instantiation");
6817 assert(CurContext->isRecord() && "scope not record in instantiation");
6818 LookupQualifiedName(Previous, CurContext);
6819 }
6820
John McCall9f54ad42009-12-10 09:41:52 +00006821 // Check for invalid redeclarations.
6822 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6823 return 0;
6824
6825 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006826 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6827 return 0;
6828
John McCallaf8e6ed2009-11-12 03:15:40 +00006829 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006830 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006831 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006832 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006833 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006834 // FIXME: not all declaration name kinds are legal here
6835 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6836 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006837 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006838 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006839 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006840 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6841 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006842 }
John McCalled976492009-12-04 22:46:56 +00006843 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006844 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6845 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006846 }
John McCalled976492009-12-04 22:46:56 +00006847 D->setAccess(AS);
6848 CurContext->addDecl(D);
6849
6850 if (!LookupContext) return D;
6851 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006852
John McCall77bb1aa2010-05-01 00:40:08 +00006853 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006854 UD->setInvalidDecl();
6855 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006856 }
6857
Richard Smithc5a89a12012-04-02 01:30:27 +00006858 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006859 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006860 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006861 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006862 return UD;
6863 }
6864
6865 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006866
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006867 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006868
John McCall604e7f12009-12-08 07:46:18 +00006869 // Unlike most lookups, we don't always want to hide tag
6870 // declarations: tag names are visible through the using declaration
6871 // even if hidden by ordinary names, *except* in a dependent context
6872 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006873 if (!IsInstantiation)
6874 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006875
John McCallb9abd8722012-04-07 03:04:20 +00006876 // For the purposes of this lookup, we have a base object type
6877 // equal to that of the current context.
6878 if (CurContext->isRecord()) {
6879 R.setBaseObjectType(
6880 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6881 }
6882
John McCalla24dc2e2009-11-17 02:14:36 +00006883 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006884
John McCallf36e02d2009-10-09 21:13:30 +00006885 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006886 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006887 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006888 UD->setInvalidDecl();
6889 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006890 }
6891
John McCalled976492009-12-04 22:46:56 +00006892 if (R.isAmbiguous()) {
6893 UD->setInvalidDecl();
6894 return UD;
6895 }
Mike Stump1eb44332009-09-09 15:08:12 +00006896
John McCall7ba107a2009-11-18 02:36:19 +00006897 if (IsTypeName) {
6898 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006899 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006900 Diag(IdentLoc, diag::err_using_typename_non_type);
6901 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6902 Diag((*I)->getUnderlyingDecl()->getLocation(),
6903 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006904 UD->setInvalidDecl();
6905 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006906 }
6907 } else {
6908 // If we asked for a non-typename and we got a type, error out,
6909 // but only if this is an instantiation of an unresolved using
6910 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006911 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006912 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6913 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006914 UD->setInvalidDecl();
6915 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006916 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006917 }
6918
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006919 // C++0x N2914 [namespace.udecl]p6:
6920 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006921 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006922 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6923 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006924 UD->setInvalidDecl();
6925 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006926 }
Mike Stump1eb44332009-09-09 15:08:12 +00006927
John McCall9f54ad42009-12-10 09:41:52 +00006928 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6929 if (!CheckUsingShadowDecl(UD, *I, Previous))
6930 BuildUsingShadowDecl(S, UD, *I);
6931 }
John McCall9488ea12009-11-17 05:59:44 +00006932
6933 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006934}
6935
Sebastian Redlf677ea32011-02-05 19:23:19 +00006936/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006937bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6938 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006939
Douglas Gregordc355712011-02-25 00:36:19 +00006940 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006941 assert(SourceType &&
6942 "Using decl naming constructor doesn't have type in scope spec.");
6943 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6944
6945 // Check whether the named type is a direct base class.
6946 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6947 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6948 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6949 BaseIt != BaseE; ++BaseIt) {
6950 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6951 if (CanonicalSourceType == BaseType)
6952 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006953 if (BaseIt->getType()->isDependentType())
6954 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006955 }
6956
6957 if (BaseIt == BaseE) {
6958 // Did not find SourceType in the bases.
6959 Diag(UD->getUsingLocation(),
6960 diag::err_using_decl_constructor_not_in_direct_base)
6961 << UD->getNameInfo().getSourceRange()
6962 << QualType(SourceType, 0) << TargetClass;
6963 return true;
6964 }
6965
Richard Smithc5a89a12012-04-02 01:30:27 +00006966 if (!CurContext->isDependentContext())
6967 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006968
6969 return false;
6970}
6971
John McCall9f54ad42009-12-10 09:41:52 +00006972/// Checks that the given using declaration is not an invalid
6973/// redeclaration. Note that this is checking only for the using decl
6974/// itself, not for any ill-formedness among the UsingShadowDecls.
6975bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6976 bool isTypeName,
6977 const CXXScopeSpec &SS,
6978 SourceLocation NameLoc,
6979 const LookupResult &Prev) {
6980 // C++03 [namespace.udecl]p8:
6981 // C++0x [namespace.udecl]p10:
6982 // A using-declaration is a declaration and can therefore be used
6983 // repeatedly where (and only where) multiple declarations are
6984 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006985 //
John McCall8a726212010-11-29 18:01:58 +00006986 // That's in non-member contexts.
6987 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006988 return false;
6989
6990 NestedNameSpecifier *Qual
6991 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6992
6993 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6994 NamedDecl *D = *I;
6995
6996 bool DTypename;
6997 NestedNameSpecifier *DQual;
6998 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6999 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007000 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007001 } else if (UnresolvedUsingValueDecl *UD
7002 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7003 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007004 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007005 } else if (UnresolvedUsingTypenameDecl *UD
7006 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7007 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007008 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007009 } else continue;
7010
7011 // using decls differ if one says 'typename' and the other doesn't.
7012 // FIXME: non-dependent using decls?
7013 if (isTypeName != DTypename) continue;
7014
7015 // using decls differ if they name different scopes (but note that
7016 // template instantiation can cause this check to trigger when it
7017 // didn't before instantiation).
7018 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7019 Context.getCanonicalNestedNameSpecifier(DQual))
7020 continue;
7021
7022 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007023 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007024 return true;
7025 }
7026
7027 return false;
7028}
7029
John McCall604e7f12009-12-08 07:46:18 +00007030
John McCalled976492009-12-04 22:46:56 +00007031/// Checks that the given nested-name qualifier used in a using decl
7032/// in the current context is appropriately related to the current
7033/// scope. If an error is found, diagnoses it and returns true.
7034bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7035 const CXXScopeSpec &SS,
7036 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007037 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007038
John McCall604e7f12009-12-08 07:46:18 +00007039 if (!CurContext->isRecord()) {
7040 // C++03 [namespace.udecl]p3:
7041 // C++0x [namespace.udecl]p8:
7042 // A using-declaration for a class member shall be a member-declaration.
7043
7044 // If we weren't able to compute a valid scope, it must be a
7045 // dependent class scope.
7046 if (!NamedContext || NamedContext->isRecord()) {
7047 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7048 << SS.getRange();
7049 return true;
7050 }
7051
7052 // Otherwise, everything is known to be fine.
7053 return false;
7054 }
7055
7056 // The current scope is a record.
7057
7058 // If the named context is dependent, we can't decide much.
7059 if (!NamedContext) {
7060 // FIXME: in C++0x, we can diagnose if we can prove that the
7061 // nested-name-specifier does not refer to a base class, which is
7062 // still possible in some cases.
7063
7064 // Otherwise we have to conservatively report that things might be
7065 // okay.
7066 return false;
7067 }
7068
7069 if (!NamedContext->isRecord()) {
7070 // Ideally this would point at the last name in the specifier,
7071 // but we don't have that level of source info.
7072 Diag(SS.getRange().getBegin(),
7073 diag::err_using_decl_nested_name_specifier_is_not_class)
7074 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7075 return true;
7076 }
7077
Douglas Gregor6fb07292010-12-21 07:41:49 +00007078 if (!NamedContext->isDependentContext() &&
7079 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7080 return true;
7081
David Blaikie4e4d0842012-03-11 07:00:24 +00007082 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00007083 // C++0x [namespace.udecl]p3:
7084 // In a using-declaration used as a member-declaration, the
7085 // nested-name-specifier shall name a base class of the class
7086 // being defined.
7087
7088 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7089 cast<CXXRecordDecl>(NamedContext))) {
7090 if (CurContext == NamedContext) {
7091 Diag(NameLoc,
7092 diag::err_using_decl_nested_name_specifier_is_current_class)
7093 << SS.getRange();
7094 return true;
7095 }
7096
7097 Diag(SS.getRange().getBegin(),
7098 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7099 << (NestedNameSpecifier*) SS.getScopeRep()
7100 << cast<CXXRecordDecl>(CurContext)
7101 << SS.getRange();
7102 return true;
7103 }
7104
7105 return false;
7106 }
7107
7108 // C++03 [namespace.udecl]p4:
7109 // A using-declaration used as a member-declaration shall refer
7110 // to a member of a base class of the class being defined [etc.].
7111
7112 // Salient point: SS doesn't have to name a base class as long as
7113 // lookup only finds members from base classes. Therefore we can
7114 // diagnose here only if we can prove that that can't happen,
7115 // i.e. if the class hierarchies provably don't intersect.
7116
7117 // TODO: it would be nice if "definitely valid" results were cached
7118 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7119 // need to be repeated.
7120
7121 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007122 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007123
7124 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7125 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7126 Data->Bases.insert(Base);
7127 return true;
7128 }
7129
7130 bool hasDependentBases(const CXXRecordDecl *Class) {
7131 return !Class->forallBases(collect, this);
7132 }
7133
7134 /// Returns true if the base is dependent or is one of the
7135 /// accumulated base classes.
7136 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7137 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7138 return !Data->Bases.count(Base);
7139 }
7140
7141 bool mightShareBases(const CXXRecordDecl *Class) {
7142 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7143 }
7144 };
7145
7146 UserData Data;
7147
7148 // Returns false if we find a dependent base.
7149 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7150 return false;
7151
7152 // Returns false if the class has a dependent base or if it or one
7153 // of its bases is present in the base set of the current context.
7154 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7155 return false;
7156
7157 Diag(SS.getRange().getBegin(),
7158 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7159 << (NestedNameSpecifier*) SS.getScopeRep()
7160 << cast<CXXRecordDecl>(CurContext)
7161 << SS.getRange();
7162
7163 return true;
John McCalled976492009-12-04 22:46:56 +00007164}
7165
Richard Smith162e1c12011-04-15 14:24:37 +00007166Decl *Sema::ActOnAliasDeclaration(Scope *S,
7167 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007168 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007169 SourceLocation UsingLoc,
7170 UnqualifiedId &Name,
7171 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007172 // Skip up to the relevant declaration scope.
7173 while (S->getFlags() & Scope::TemplateParamScope)
7174 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007175 assert((S->getFlags() & Scope::DeclScope) &&
7176 "got alias-declaration outside of declaration scope");
7177
7178 if (Type.isInvalid())
7179 return 0;
7180
7181 bool Invalid = false;
7182 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7183 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007184 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007185
7186 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7187 return 0;
7188
7189 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007190 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007191 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007192 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7193 TInfo->getTypeLoc().getBeginLoc());
7194 }
Richard Smith162e1c12011-04-15 14:24:37 +00007195
7196 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7197 LookupName(Previous, S);
7198
7199 // Warn about shadowing the name of a template parameter.
7200 if (Previous.isSingleResult() &&
7201 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007202 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007203 Previous.clear();
7204 }
7205
7206 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7207 "name in alias declaration must be an identifier");
7208 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7209 Name.StartLocation,
7210 Name.Identifier, TInfo);
7211
7212 NewTD->setAccess(AS);
7213
7214 if (Invalid)
7215 NewTD->setInvalidDecl();
7216
Richard Smith3e4c6c42011-05-05 21:57:07 +00007217 CheckTypedefForVariablyModifiedType(S, NewTD);
7218 Invalid |= NewTD->isInvalidDecl();
7219
Richard Smith162e1c12011-04-15 14:24:37 +00007220 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007221
7222 NamedDecl *NewND;
7223 if (TemplateParamLists.size()) {
7224 TypeAliasTemplateDecl *OldDecl = 0;
7225 TemplateParameterList *OldTemplateParams = 0;
7226
7227 if (TemplateParamLists.size() != 1) {
7228 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007229 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7230 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007231 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007232 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007233
7234 // Only consider previous declarations in the same scope.
7235 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7236 /*ExplicitInstantiationOrSpecialization*/false);
7237 if (!Previous.empty()) {
7238 Redeclaration = true;
7239
7240 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7241 if (!OldDecl && !Invalid) {
7242 Diag(UsingLoc, diag::err_redefinition_different_kind)
7243 << Name.Identifier;
7244
7245 NamedDecl *OldD = Previous.getRepresentativeDecl();
7246 if (OldD->getLocation().isValid())
7247 Diag(OldD->getLocation(), diag::note_previous_definition);
7248
7249 Invalid = true;
7250 }
7251
7252 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7253 if (TemplateParameterListsAreEqual(TemplateParams,
7254 OldDecl->getTemplateParameters(),
7255 /*Complain=*/true,
7256 TPL_TemplateMatch))
7257 OldTemplateParams = OldDecl->getTemplateParameters();
7258 else
7259 Invalid = true;
7260
7261 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7262 if (!Invalid &&
7263 !Context.hasSameType(OldTD->getUnderlyingType(),
7264 NewTD->getUnderlyingType())) {
7265 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7266 // but we can't reasonably accept it.
7267 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7268 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7269 if (OldTD->getLocation().isValid())
7270 Diag(OldTD->getLocation(), diag::note_previous_definition);
7271 Invalid = true;
7272 }
7273 }
7274 }
7275
7276 // Merge any previous default template arguments into our parameters,
7277 // and check the parameter list.
7278 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7279 TPC_TypeAliasTemplate))
7280 return 0;
7281
7282 TypeAliasTemplateDecl *NewDecl =
7283 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7284 Name.Identifier, TemplateParams,
7285 NewTD);
7286
7287 NewDecl->setAccess(AS);
7288
7289 if (Invalid)
7290 NewDecl->setInvalidDecl();
7291 else if (OldDecl)
7292 NewDecl->setPreviousDeclaration(OldDecl);
7293
7294 NewND = NewDecl;
7295 } else {
7296 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7297 NewND = NewTD;
7298 }
Richard Smith162e1c12011-04-15 14:24:37 +00007299
7300 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007301 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007302
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007303 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007304 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007305}
7306
John McCalld226f652010-08-21 09:40:31 +00007307Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007308 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007309 SourceLocation AliasLoc,
7310 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007311 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007312 SourceLocation IdentLoc,
7313 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007314
Anders Carlsson81c85c42009-03-28 23:53:49 +00007315 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007316 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7317 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007318
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007319 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007320 NamedDecl *PrevDecl
7321 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7322 ForRedeclaration);
7323 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7324 PrevDecl = 0;
7325
7326 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007327 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007328 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007329 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007330 // FIXME: At some point, we'll want to create the (redundant)
7331 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007332 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007333 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007334 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007335 }
Mike Stump1eb44332009-09-09 15:08:12 +00007336
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007337 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7338 diag::err_redefinition_different_kind;
7339 Diag(AliasLoc, DiagID) << Alias;
7340 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007341 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007342 }
7343
John McCalla24dc2e2009-11-17 02:14:36 +00007344 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007345 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007346
John McCallf36e02d2009-10-09 21:13:30 +00007347 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007348 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007349 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007350 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007351 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007352 }
Mike Stump1eb44332009-09-09 15:08:12 +00007353
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007354 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007355 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007356 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007357 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007358
John McCall3dbd3d52010-02-16 06:53:13 +00007359 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007360 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007361}
7362
Sean Hunt001cad92011-05-10 00:49:42 +00007363Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007364Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7365 CXXMethodDecl *MD) {
7366 CXXRecordDecl *ClassDecl = MD->getParent();
7367
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007368 // C++ [except.spec]p14:
7369 // An implicitly declared special member function (Clause 12) shall have an
7370 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007371 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007372 if (ClassDecl->isInvalidDecl())
7373 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007374
Sebastian Redl60618fa2011-03-12 11:50:43 +00007375 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007376 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7377 BEnd = ClassDecl->bases_end();
7378 B != BEnd; ++B) {
7379 if (B->isVirtual()) // Handled below.
7380 continue;
7381
Douglas Gregor18274032010-07-03 00:47:00 +00007382 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7383 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007384 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7385 // If this is a deleted function, add it anyway. This might be conformant
7386 // with the standard. This might not. I'm not sure. It might not matter.
7387 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007388 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007389 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007390 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007391
7392 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007393 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7394 BEnd = ClassDecl->vbases_end();
7395 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007396 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7397 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007398 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7399 // If this is a deleted function, add it anyway. This might be conformant
7400 // with the standard. This might not. I'm not sure. It might not matter.
7401 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007402 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007403 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007404 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007405
7406 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007407 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7408 FEnd = ClassDecl->field_end();
7409 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007410 if (F->hasInClassInitializer()) {
7411 if (Expr *E = F->getInClassInitializer())
7412 ExceptSpec.CalledExpr(E);
7413 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007414 // DR1351:
7415 // If the brace-or-equal-initializer of a non-static data member
7416 // invokes a defaulted default constructor of its class or of an
7417 // enclosing class in a potentially evaluated subexpression, the
7418 // program is ill-formed.
7419 //
7420 // This resolution is unworkable: the exception specification of the
7421 // default constructor can be needed in an unevaluated context, in
7422 // particular, in the operand of a noexcept-expression, and we can be
7423 // unable to compute an exception specification for an enclosed class.
7424 //
7425 // We do not allow an in-class initializer to require the evaluation
7426 // of the exception specification for any in-class initializer whose
7427 // definition is not lexically complete.
7428 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007429 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007430 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007431 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7432 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7433 // If this is a deleted function, add it anyway. This might be conformant
7434 // with the standard. This might not. I'm not sure. It might not matter.
7435 // In particular, the problem is that this function never gets called. It
7436 // might just be ill-formed because this function attempts to refer to
7437 // a deleted function here.
7438 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007439 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007440 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007441 }
John McCalle23cf432010-12-14 08:05:40 +00007442
Sean Hunt001cad92011-05-10 00:49:42 +00007443 return ExceptSpec;
7444}
7445
Richard Smithafb49182012-11-29 01:34:07 +00007446namespace {
7447/// RAII object to register a special member as being currently declared.
7448struct DeclaringSpecialMember {
7449 Sema &S;
7450 Sema::SpecialMemberDecl D;
7451 bool WasAlreadyBeingDeclared;
7452
7453 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7454 : S(S), D(RD, CSM) {
7455 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7456 if (WasAlreadyBeingDeclared)
7457 // This almost never happens, but if it does, ensure that our cache
7458 // doesn't contain a stale result.
7459 S.SpecialMemberCache.clear();
7460
7461 // FIXME: Register a note to be produced if we encounter an error while
7462 // declaring the special member.
7463 }
7464 ~DeclaringSpecialMember() {
7465 if (!WasAlreadyBeingDeclared)
7466 S.SpecialMembersBeingDeclared.erase(D);
7467 }
7468
7469 /// \brief Are we already trying to declare this special member?
7470 bool isAlreadyBeingDeclared() const {
7471 return WasAlreadyBeingDeclared;
7472 }
7473};
7474}
7475
Sean Hunt001cad92011-05-10 00:49:42 +00007476CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7477 CXXRecordDecl *ClassDecl) {
7478 // C++ [class.ctor]p5:
7479 // A default constructor for a class X is a constructor of class X
7480 // that can be called without an argument. If there is no
7481 // user-declared constructor for class X, a default constructor is
7482 // implicitly declared. An implicitly-declared default constructor
7483 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007484 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007485 "Should not build implicit default constructor!");
7486
Richard Smithafb49182012-11-29 01:34:07 +00007487 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7488 if (DSM.isAlreadyBeingDeclared())
7489 return 0;
7490
Richard Smith7756afa2012-06-10 05:43:50 +00007491 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7492 CXXDefaultConstructor,
7493 false);
7494
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007495 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007496 CanQualType ClassType
7497 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007498 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007499 DeclarationName Name
7500 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007501 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007502 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007503 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007504 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007505 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007506 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007507 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007508 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007509
7510 // Build an exception specification pointing back at this constructor.
7511 FunctionProtoType::ExtProtoInfo EPI;
7512 EPI.ExceptionSpecType = EST_Unevaluated;
7513 EPI.ExceptionSpecDecl = DefaultCon;
7514 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7515
Richard Smithbc2a35d2012-12-08 08:32:28 +00007516 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7517 // constructors is easy to compute.
7518 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7519
7520 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7521 DefaultCon->setDeletedAsWritten();
7522
Douglas Gregor18274032010-07-03 00:47:00 +00007523 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007524 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007525
Douglas Gregor23c94db2010-07-02 17:43:08 +00007526 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007527 PushOnScopeChains(DefaultCon, S, false);
7528 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007529
Douglas Gregor32df23e2010-07-01 22:02:46 +00007530 return DefaultCon;
7531}
7532
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007533void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7534 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007535 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007536 !Constructor->doesThisDeclarationHaveABody() &&
7537 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007538 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007539
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007540 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007541 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007542
Eli Friedman9a14db32012-10-18 20:14:08 +00007543 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007544 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007545 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007546 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007547 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007548 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007549 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007550 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007551 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007552
7553 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007554 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007555
7556 Constructor->setUsed();
7557 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007558
7559 if (ASTMutationListener *L = getASTMutationListener()) {
7560 L->CompletedImplicitDefinition(Constructor);
7561 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007562}
7563
Richard Smith7a614d82011-06-11 17:19:42 +00007564void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007565 // Check that any explicitly-defaulted methods have exception specifications
7566 // compatible with their implicit exception specifications.
7567 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007568}
7569
Sebastian Redlf677ea32011-02-05 19:23:19 +00007570void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7571 // We start with an initial pass over the base classes to collect those that
7572 // inherit constructors from. If there are none, we can forgo all further
7573 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007574 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007575 BasesVector BasesToInheritFrom;
7576 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7577 BaseE = ClassDecl->bases_end();
7578 BaseIt != BaseE; ++BaseIt) {
7579 if (BaseIt->getInheritConstructors()) {
7580 QualType Base = BaseIt->getType();
7581 if (Base->isDependentType()) {
7582 // If we inherit constructors from anything that is dependent, just
7583 // abort processing altogether. We'll get another chance for the
7584 // instantiations.
7585 return;
7586 }
7587 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7588 }
7589 }
7590 if (BasesToInheritFrom.empty())
7591 return;
7592
7593 // Now collect the constructors that we already have in the current class.
7594 // Those take precedence over inherited constructors.
7595 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7596 // unless there is a user-declared constructor with the same signature in
7597 // the class where the using-declaration appears.
7598 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7599 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7600 CtorE = ClassDecl->ctor_end();
7601 CtorIt != CtorE; ++CtorIt) {
7602 ExistingConstructors.insert(
7603 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7604 }
7605
Sebastian Redlf677ea32011-02-05 19:23:19 +00007606 DeclarationName CreatedCtorName =
7607 Context.DeclarationNames.getCXXConstructorName(
7608 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7609
7610 // Now comes the true work.
7611 // First, we keep a map from constructor types to the base that introduced
7612 // them. Needed for finding conflicting constructors. We also keep the
7613 // actually inserted declarations in there, for pretty diagnostics.
7614 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7615 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7616 ConstructorToSourceMap InheritedConstructors;
7617 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7618 BaseE = BasesToInheritFrom.end();
7619 BaseIt != BaseE; ++BaseIt) {
7620 const RecordType *Base = *BaseIt;
7621 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7622 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7623 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7624 CtorE = BaseDecl->ctor_end();
7625 CtorIt != CtorE; ++CtorIt) {
7626 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007627 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007628 DeclarationName Name =
7629 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007630 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7631 LookupQualifiedName(Result, CurContext);
7632 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007633 SourceLocation UsingLoc = UD ? UD->getLocation() :
7634 ClassDecl->getLocation();
7635
7636 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7637 // from the class X named in the using-declaration consists of actual
7638 // constructors and notional constructors that result from the
7639 // transformation of defaulted parameters as follows:
7640 // - all non-template default constructors of X, and
7641 // - for each non-template constructor of X that has at least one
7642 // parameter with a default argument, the set of constructors that
7643 // results from omitting any ellipsis parameter specification and
7644 // successively omitting parameters with a default argument from the
7645 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00007646 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007647 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7648 const FunctionProtoType *BaseCtorType =
7649 BaseCtor->getType()->getAs<FunctionProtoType>();
7650
7651 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7652 maxParams = BaseCtor->getNumParams();
7653 params <= maxParams; ++params) {
7654 // Skip default constructors. They're never inherited.
7655 if (params == 0)
7656 continue;
7657 // Skip copy and move constructors for the same reason.
7658 if (CanBeCopyOrMove && params == 1)
7659 continue;
7660
7661 // Build up a function type for this particular constructor.
7662 // FIXME: The working paper does not consider that the exception spec
7663 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007664 // source. This code doesn't yet, either. When it does, this code will
7665 // need to be delayed until after exception specifications and in-class
7666 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007667 const Type *NewCtorType;
7668 if (params == maxParams)
7669 NewCtorType = BaseCtorType;
7670 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007671 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007672 for (unsigned i = 0; i < params; ++i) {
7673 Args.push_back(BaseCtorType->getArgType(i));
7674 }
7675 FunctionProtoType::ExtProtoInfo ExtInfo =
7676 BaseCtorType->getExtProtoInfo();
7677 ExtInfo.Variadic = false;
7678 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7679 Args.data(), params, ExtInfo)
7680 .getTypePtr();
7681 }
7682 const Type *CanonicalNewCtorType =
7683 Context.getCanonicalType(NewCtorType);
7684
7685 // Now that we have the type, first check if the class already has a
7686 // constructor with this signature.
7687 if (ExistingConstructors.count(CanonicalNewCtorType))
7688 continue;
7689
7690 // Then we check if we have already declared an inherited constructor
7691 // with this signature.
7692 std::pair<ConstructorToSourceMap::iterator, bool> result =
7693 InheritedConstructors.insert(std::make_pair(
7694 CanonicalNewCtorType,
7695 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7696 if (!result.second) {
7697 // Already in the map. If it came from a different class, that's an
7698 // error. Not if it's from the same.
7699 CanQualType PreviousBase = result.first->second.first;
7700 if (CanonicalBase != PreviousBase) {
7701 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7702 const CXXConstructorDecl *PrevBaseCtor =
7703 PrevCtor->getInheritedConstructor();
7704 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7705
7706 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7707 Diag(BaseCtor->getLocation(),
7708 diag::note_using_decl_constructor_conflict_current_ctor);
7709 Diag(PrevBaseCtor->getLocation(),
7710 diag::note_using_decl_constructor_conflict_previous_ctor);
7711 Diag(PrevCtor->getLocation(),
7712 diag::note_using_decl_constructor_conflict_previous_using);
7713 }
7714 continue;
7715 }
7716
7717 // OK, we're there, now add the constructor.
7718 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007719 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007720 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7721 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007722 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7723 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007724 /*ImplicitlyDeclared=*/true,
7725 // FIXME: Due to a defect in the standard, we treat inherited
7726 // constructors as constexpr even if that makes them ill-formed.
7727 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007728 NewCtor->setAccess(BaseCtor->getAccess());
7729
7730 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007731 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007732 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007733 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7734 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007735 /*IdentifierInfo=*/0,
7736 BaseCtorType->getArgType(i),
7737 /*TInfo=*/0, SC_None,
7738 SC_None, /*DefaultArg=*/0));
7739 }
David Blaikie4278c652011-09-21 18:16:56 +00007740 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007741 NewCtor->setInheritedConstructor(BaseCtor);
7742
Sebastian Redlf677ea32011-02-05 19:23:19 +00007743 ClassDecl->addDecl(NewCtor);
7744 result.first->second.second = NewCtor;
7745 }
7746 }
7747 }
7748}
7749
Sean Huntcb45a0f2011-05-12 22:46:25 +00007750Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007751Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7752 CXXRecordDecl *ClassDecl = MD->getParent();
7753
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007754 // C++ [except.spec]p14:
7755 // An implicitly declared special member function (Clause 12) shall have
7756 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007757 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007758 if (ClassDecl->isInvalidDecl())
7759 return ExceptSpec;
7760
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007761 // Direct base-class destructors.
7762 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7763 BEnd = ClassDecl->bases_end();
7764 B != BEnd; ++B) {
7765 if (B->isVirtual()) // Handled below.
7766 continue;
7767
7768 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007769 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007770 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007771 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007772
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007773 // Virtual base-class destructors.
7774 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7775 BEnd = ClassDecl->vbases_end();
7776 B != BEnd; ++B) {
7777 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007778 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007779 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007780 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007781
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007782 // Field destructors.
7783 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7784 FEnd = ClassDecl->field_end();
7785 F != FEnd; ++F) {
7786 if (const RecordType *RecordTy
7787 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007788 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007789 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007790 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007791
Sean Huntcb45a0f2011-05-12 22:46:25 +00007792 return ExceptSpec;
7793}
7794
7795CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7796 // C++ [class.dtor]p2:
7797 // If a class has no user-declared destructor, a destructor is
7798 // declared implicitly. An implicitly-declared destructor is an
7799 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007800 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007801
Richard Smithafb49182012-11-29 01:34:07 +00007802 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7803 if (DSM.isAlreadyBeingDeclared())
7804 return 0;
7805
Douglas Gregor4923aa22010-07-02 20:37:36 +00007806 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007807 CanQualType ClassType
7808 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007809 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007810 DeclarationName Name
7811 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007812 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007813 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007814 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7815 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007816 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007817 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007818 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007819 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007820
7821 // Build an exception specification pointing back at this destructor.
7822 FunctionProtoType::ExtProtoInfo EPI;
7823 EPI.ExceptionSpecType = EST_Unevaluated;
7824 EPI.ExceptionSpecDecl = Destructor;
7825 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7826
Richard Smithbc2a35d2012-12-08 08:32:28 +00007827 AddOverriddenMethods(ClassDecl, Destructor);
7828
7829 // We don't need to use SpecialMemberIsTrivial here; triviality for
7830 // destructors is easy to compute.
7831 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7832
7833 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7834 Destructor->setDeletedAsWritten();
7835
Douglas Gregor4923aa22010-07-02 20:37:36 +00007836 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007837 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007838
Douglas Gregor4923aa22010-07-02 20:37:36 +00007839 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007840 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007841 PushOnScopeChains(Destructor, S, false);
7842 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007843
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007844 return Destructor;
7845}
7846
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007847void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007848 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007849 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007850 !Destructor->doesThisDeclarationHaveABody() &&
7851 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007852 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007853 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007854 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007855
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007856 if (Destructor->isInvalidDecl())
7857 return;
7858
Eli Friedman9a14db32012-10-18 20:14:08 +00007859 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007860
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007861 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007862 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7863 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007864
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007865 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007866 Diag(CurrentLocation, diag::note_member_synthesized_at)
7867 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7868
7869 Destructor->setInvalidDecl();
7870 return;
7871 }
7872
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007873 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007874 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007875 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007876 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007877 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007878
7879 if (ASTMutationListener *L = getASTMutationListener()) {
7880 L->CompletedImplicitDefinition(Destructor);
7881 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007882}
7883
Richard Smitha4156b82012-04-21 18:42:51 +00007884/// \brief Perform any semantic analysis which needs to be delayed until all
7885/// pending class member declarations have been parsed.
7886void Sema::ActOnFinishCXXMemberDecls() {
Richard Smitha4156b82012-04-21 18:42:51 +00007887 // Perform any deferred checking of exception specifications for virtual
7888 // destructors.
7889 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7890 i != e; ++i) {
7891 const CXXDestructorDecl *Dtor =
7892 DelayedDestructorExceptionSpecChecks[i].first;
7893 assert(!Dtor->getParent()->isDependentType() &&
7894 "Should not ever add destructors of templates into the list.");
7895 CheckOverridingFunctionExceptionSpec(Dtor,
7896 DelayedDestructorExceptionSpecChecks[i].second);
7897 }
7898 DelayedDestructorExceptionSpecChecks.clear();
7899}
7900
Richard Smithb9d0b762012-07-27 04:22:15 +00007901void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7902 CXXDestructorDecl *Destructor) {
7903 assert(getLangOpts().CPlusPlus0x &&
7904 "adjusting dtor exception specs was introduced in c++11");
7905
Sebastian Redl0ee33912011-05-19 05:13:44 +00007906 // C++11 [class.dtor]p3:
7907 // A declaration of a destructor that does not have an exception-
7908 // specification is implicitly considered to have the same exception-
7909 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007910 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007911 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007912 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007913 return;
7914
Chandler Carruth3f224b22011-09-20 04:55:26 +00007915 // Replace the destructor's type, building off the existing one. Fortunately,
7916 // the only thing of interest in the destructor type is its extended info.
7917 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007918 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7919 EPI.ExceptionSpecType = EST_Unevaluated;
7920 EPI.ExceptionSpecDecl = Destructor;
7921 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007922
Sebastian Redl0ee33912011-05-19 05:13:44 +00007923 // FIXME: If the destructor has a body that could throw, and the newly created
7924 // spec doesn't allow exceptions, we should emit a warning, because this
7925 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007926 // However, we don't have a body or an exception specification yet, so it
7927 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007928}
7929
Richard Smith8c889532012-11-14 00:50:40 +00007930/// When generating a defaulted copy or move assignment operator, if a field
7931/// should be copied with __builtin_memcpy rather than via explicit assignments,
7932/// do so. This optimization only applies for arrays of scalars, and for arrays
7933/// of class type where the selected copy/move-assignment operator is trivial.
7934static StmtResult
7935buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7936 Expr *To, Expr *From) {
7937 // Compute the size of the memory buffer to be copied.
7938 QualType SizeType = S.Context.getSizeType();
7939 llvm::APInt Size(S.Context.getTypeSize(SizeType),
7940 S.Context.getTypeSizeInChars(T).getQuantity());
7941
7942 // Take the address of the field references for "from" and "to". We
7943 // directly construct UnaryOperators here because semantic analysis
7944 // does not permit us to take the address of an xvalue.
7945 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7946 S.Context.getPointerType(From->getType()),
7947 VK_RValue, OK_Ordinary, Loc);
7948 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7949 S.Context.getPointerType(To->getType()),
7950 VK_RValue, OK_Ordinary, Loc);
7951
7952 const Type *E = T->getBaseElementTypeUnsafe();
7953 bool NeedsCollectableMemCpy =
7954 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7955
7956 // Create a reference to the __builtin_objc_memmove_collectable function
7957 StringRef MemCpyName = NeedsCollectableMemCpy ?
7958 "__builtin_objc_memmove_collectable" :
7959 "__builtin_memcpy";
7960 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
7961 Sema::LookupOrdinaryName);
7962 S.LookupName(R, S.TUScope, true);
7963
7964 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
7965 if (!MemCpy)
7966 // Something went horribly wrong earlier, and we will have complained
7967 // about it.
7968 return StmtError();
7969
7970 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
7971 VK_RValue, Loc, 0);
7972 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
7973
7974 Expr *CallArgs[] = {
7975 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
7976 };
7977 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
7978 Loc, CallArgs, Loc);
7979
7980 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7981 return S.Owned(Call.takeAs<Stmt>());
7982}
7983
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007984/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007985/// \c To.
7986///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007987/// This routine is used to copy/move the members of a class with an
7988/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007989/// copied are arrays, this routine builds for loops to copy them.
7990///
7991/// \param S The Sema object used for type-checking.
7992///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007993/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007994///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007995/// \param T The type of the expressions being copied/moved. Both expressions
7996/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007997///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007998/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007999///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008000/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008001///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008002/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008003/// Otherwise, it's a non-static member subobject.
8004///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008005/// \param Copying Whether we're copying or moving.
8006///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008007/// \param Depth Internal parameter recording the depth of the recursion.
8008///
Richard Smith8c889532012-11-14 00:50:40 +00008009/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8010/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008011static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008012buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8013 Expr *To, Expr *From,
8014 bool CopyingBaseSubobject, bool Copying,
8015 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008016 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008017 // Each subobject is assigned in the manner appropriate to its type:
8018 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008019 // - if the subobject is of class type, as if by a call to operator= with
8020 // the subobject as the object expression and the corresponding
8021 // subobject of x as a single function argument (as if by explicit
8022 // qualification; that is, ignoring any possible virtual overriding
8023 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008024 //
8025 // C++03 [class.copy]p13:
8026 // - if the subobject is of class type, the copy assignment operator for
8027 // the class is used (as if by explicit qualification; that is,
8028 // ignoring any possible virtual overriding functions in more derived
8029 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008030 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8031 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008032
Douglas Gregor06a9f362010-05-01 20:49:11 +00008033 // Look for operator=.
8034 DeclarationName Name
8035 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8036 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8037 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008038
Richard Smith044c8aa2012-11-13 00:54:12 +00008039 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8040 // operator.
8041 if (!S.getLangOpts().CPlusPlus0x) {
8042 LookupResult::Filter F = OpLookup.makeFilter();
8043 while (F.hasNext()) {
8044 NamedDecl *D = F.next();
8045 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8046 if (Method->isCopyAssignmentOperator() ||
8047 (!Copying && Method->isMoveAssignmentOperator()))
8048 continue;
8049
8050 F.erase();
8051 }
8052 F.done();
John McCallb0207482010-03-16 06:11:48 +00008053 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008054
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008055 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008056 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008057 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008058 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008059 // ambiguities), we need to cast "this" to that subobject type; to
8060 // ensure that we don't go through the virtual call mechanism, we need
8061 // to qualify the operator= name with the base class (see below). However,
8062 // this means that if the base class has a protected copy assignment
8063 // operator, the protected member access check will fail. So, we
8064 // rewrite "protected" access to "public" access in this case, since we
8065 // know by construction that we're calling from a derived class.
8066 if (CopyingBaseSubobject) {
8067 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8068 L != LEnd; ++L) {
8069 if (L.getAccess() == AS_protected)
8070 L.setAccess(AS_public);
8071 }
8072 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008073
Douglas Gregor06a9f362010-05-01 20:49:11 +00008074 // Create the nested-name-specifier that will be used to qualify the
8075 // reference to operator=; this is required to suppress the virtual
8076 // call mechanism.
8077 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008078 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008079 SS.MakeTrivial(S.Context,
8080 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008081 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008082 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008083
Douglas Gregor06a9f362010-05-01 20:49:11 +00008084 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008085 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008086 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008087 /*TemplateKWLoc=*/SourceLocation(),
8088 /*FirstQualifierInScope=*/0,
8089 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008090 /*TemplateArgs=*/0,
8091 /*SuppressQualifierCheck=*/true);
8092 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008093 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008094
Douglas Gregor06a9f362010-05-01 20:49:11 +00008095 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008096
Richard Smith044c8aa2012-11-13 00:54:12 +00008097 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008098 OpEqualRef.takeAs<Expr>(),
8099 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008100 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008101 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008102
Richard Smith8c889532012-11-14 00:50:40 +00008103 // If we built a call to a trivial 'operator=' while copying an array,
8104 // bail out. We'll replace the whole shebang with a memcpy.
8105 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8106 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8107 return StmtResult((Stmt*)0);
8108
Richard Smith044c8aa2012-11-13 00:54:12 +00008109 // Convert to an expression-statement, and clean up any produced
8110 // temporaries.
8111 return S.ActOnExprStmt(S.MakeFullExpr(Call.take(), Loc));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008112 }
John McCallb0207482010-03-16 06:11:48 +00008113
Richard Smith044c8aa2012-11-13 00:54:12 +00008114 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008115 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008116 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008117 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008118 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008119 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008120 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008121 return S.ActOnExprStmt(S.MakeFullExpr(Assignment.take(), Loc));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008122 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008123
8124 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008125 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008126
Douglas Gregor06a9f362010-05-01 20:49:11 +00008127 // Construct a loop over the array bounds, e.g.,
8128 //
8129 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8130 //
8131 // that will copy each of the array elements.
8132 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008133
Douglas Gregor06a9f362010-05-01 20:49:11 +00008134 // Create the iteration variable.
8135 IdentifierInfo *IterationVarName = 0;
8136 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008137 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008138 llvm::raw_svector_ostream OS(Str);
8139 OS << "__i" << Depth;
8140 IterationVarName = &S.Context.Idents.get(OS.str());
8141 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008142 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008143 IterationVarName, SizeType,
8144 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00008145 SC_None, SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008146
Douglas Gregor06a9f362010-05-01 20:49:11 +00008147 // Initialize the iteration variable to zero.
8148 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008149 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008150
8151 // Create a reference to the iteration variable; we'll use this several
8152 // times throughout.
8153 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008154 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008155 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008156 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8157 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8158
Douglas Gregor06a9f362010-05-01 20:49:11 +00008159 // Create the DeclStmt that holds the iteration variable.
8160 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008161
Douglas Gregor06a9f362010-05-01 20:49:11 +00008162 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008163 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008164 IterationVarRefRVal,
8165 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008166 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008167 IterationVarRefRVal,
8168 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008169 if (!Copying) // Cast to rvalue
8170 From = CastForMoving(S, From);
8171
8172 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008173 StmtResult Copy =
8174 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8175 To, From, CopyingBaseSubobject,
8176 Copying, Depth + 1);
8177 // Bail out if copying fails or if we determined that we should use memcpy.
8178 if (Copy.isInvalid() || !Copy.get())
8179 return Copy;
8180
8181 // Create the comparison against the array bound.
8182 llvm::APInt Upper
8183 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8184 Expr *Comparison
8185 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8186 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8187 BO_NE, S.Context.BoolTy,
8188 VK_RValue, OK_Ordinary, Loc, false);
8189
8190 // Create the pre-increment of the iteration variable.
8191 Expr *Increment
8192 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8193 VK_LValue, OK_Ordinary, Loc);
8194
Douglas Gregor06a9f362010-05-01 20:49:11 +00008195 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008196 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008197 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00008198 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008199 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008200}
8201
Richard Smith8c889532012-11-14 00:50:40 +00008202static StmtResult
8203buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8204 Expr *To, Expr *From,
8205 bool CopyingBaseSubobject, bool Copying) {
8206 // Maybe we should use a memcpy?
8207 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8208 T.isTriviallyCopyableType(S.Context))
8209 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8210
8211 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8212 CopyingBaseSubobject,
8213 Copying, 0));
8214
8215 // If we ended up picking a trivial assignment operator for an array of a
8216 // non-trivially-copyable class type, just emit a memcpy.
8217 if (!Result.isInvalid() && !Result.get())
8218 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8219
8220 return Result;
8221}
8222
Richard Smithb9d0b762012-07-27 04:22:15 +00008223Sema::ImplicitExceptionSpecification
8224Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8225 CXXRecordDecl *ClassDecl = MD->getParent();
8226
8227 ImplicitExceptionSpecification ExceptSpec(*this);
8228 if (ClassDecl->isInvalidDecl())
8229 return ExceptSpec;
8230
8231 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8232 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8233 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8234
Douglas Gregorb87786f2010-07-01 17:48:08 +00008235 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008236 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008237 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008238
8239 // It is unspecified whether or not an implicit copy assignment operator
8240 // attempts to deduplicate calls to assignment operators of virtual bases are
8241 // made. As such, this exception specification is effectively unspecified.
8242 // Based on a similar decision made for constness in C++0x, we're erring on
8243 // the side of assuming such calls to be made regardless of whether they
8244 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008245 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8246 BaseEnd = ClassDecl->bases_end();
8247 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008248 if (Base->isVirtual())
8249 continue;
8250
Douglas Gregora376d102010-07-02 21:50:04 +00008251 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008252 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008253 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8254 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008255 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008256 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008257
8258 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8259 BaseEnd = ClassDecl->vbases_end();
8260 Base != BaseEnd; ++Base) {
8261 CXXRecordDecl *BaseClassDecl
8262 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8263 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8264 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008265 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008266 }
8267
Douglas Gregorb87786f2010-07-01 17:48:08 +00008268 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8269 FieldEnd = ClassDecl->field_end();
8270 Field != FieldEnd;
8271 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008272 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008273 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8274 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008275 LookupCopyingAssignment(FieldClassDecl,
8276 ArgQuals | FieldType.getCVRQualifiers(),
8277 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008278 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008279 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008280 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008281
Richard Smithb9d0b762012-07-27 04:22:15 +00008282 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008283}
8284
8285CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8286 // Note: The following rules are largely analoguous to the copy
8287 // constructor rules. Note that virtual bases are not taken into account
8288 // for determining the argument type of the operator. Note also that
8289 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008290 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008291
Richard Smithafb49182012-11-29 01:34:07 +00008292 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8293 if (DSM.isAlreadyBeingDeclared())
8294 return 0;
8295
Sean Hunt30de05c2011-05-14 05:23:20 +00008296 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8297 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008298 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008299 ArgType = ArgType.withConst();
8300 ArgType = Context.getLValueReferenceType(ArgType);
8301
Douglas Gregord3c35902010-07-01 16:36:15 +00008302 // An implicitly-declared copy assignment operator is an inline public
8303 // member of its class.
8304 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008305 SourceLocation ClassLoc = ClassDecl->getLocation();
8306 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008307 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008308 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00008309 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00008310 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008311 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008312 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008313 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008314 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008315 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008316
8317 // Build an exception specification pointing back at this member.
8318 FunctionProtoType::ExtProtoInfo EPI;
8319 EPI.ExceptionSpecType = EST_Unevaluated;
8320 EPI.ExceptionSpecDecl = CopyAssignment;
8321 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8322
Douglas Gregord3c35902010-07-01 16:36:15 +00008323 // Add the parameter to the operator.
8324 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008325 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008326 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008327 SC_None,
8328 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008329 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008330
Richard Smithbc2a35d2012-12-08 08:32:28 +00008331 AddOverriddenMethods(ClassDecl, CopyAssignment);
8332
8333 CopyAssignment->setTrivial(
8334 ClassDecl->needsOverloadResolutionForCopyAssignment()
8335 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8336 : ClassDecl->hasTrivialCopyAssignment());
8337
Nico Weberafcc96a2012-01-23 03:19:29 +00008338 // C++0x [class.copy]p19:
8339 // .... If the class definition does not explicitly declare a copy
8340 // assignment operator, there is no user-declared move constructor, and
8341 // there is no user-declared move assignment operator, a copy assignment
8342 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008343 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00008344 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008345
Richard Smithbc2a35d2012-12-08 08:32:28 +00008346 // Note that we have added this copy-assignment operator.
8347 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8348
8349 if (Scope *S = getScopeForContext(ClassDecl))
8350 PushOnScopeChains(CopyAssignment, S, false);
8351 ClassDecl->addDecl(CopyAssignment);
8352
Douglas Gregord3c35902010-07-01 16:36:15 +00008353 return CopyAssignment;
8354}
8355
Douglas Gregor06a9f362010-05-01 20:49:11 +00008356void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8357 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008358 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008359 CopyAssignOperator->isOverloadedOperator() &&
8360 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008361 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8362 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008363 "DefineImplicitCopyAssignment called for wrong function");
8364
8365 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8366
8367 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8368 CopyAssignOperator->setInvalidDecl();
8369 return;
8370 }
8371
8372 CopyAssignOperator->setUsed();
8373
Eli Friedman9a14db32012-10-18 20:14:08 +00008374 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008375 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008376
8377 // C++0x [class.copy]p30:
8378 // The implicitly-defined or explicitly-defaulted copy assignment operator
8379 // for a non-union class X performs memberwise copy assignment of its
8380 // subobjects. The direct base classes of X are assigned first, in the
8381 // order of their declaration in the base-specifier-list, and then the
8382 // immediate non-static data members of X are assigned, in the order in
8383 // which they were declared in the class definition.
8384
8385 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008386 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008387
8388 // The parameter for the "other" object, which we are copying from.
8389 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8390 Qualifiers OtherQuals = Other->getType().getQualifiers();
8391 QualType OtherRefType = Other->getType();
8392 if (const LValueReferenceType *OtherRef
8393 = OtherRefType->getAs<LValueReferenceType>()) {
8394 OtherRefType = OtherRef->getPointeeType();
8395 OtherQuals = OtherRefType.getQualifiers();
8396 }
8397
8398 // Our location for everything implicitly-generated.
8399 SourceLocation Loc = CopyAssignOperator->getLocation();
8400
8401 // Construct a reference to the "other" object. We'll be using this
8402 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008403 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008404 assert(OtherRef && "Reference to parameter cannot fail!");
8405
8406 // Construct the "this" pointer. We'll be using this throughout the generated
8407 // ASTs.
8408 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8409 assert(This && "Reference to this cannot fail!");
8410
8411 // Assign base classes.
8412 bool Invalid = false;
8413 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8414 E = ClassDecl->bases_end(); Base != E; ++Base) {
8415 // Form the assignment:
8416 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8417 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008418 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008419 Invalid = true;
8420 continue;
8421 }
8422
John McCallf871d0c2010-08-07 06:22:56 +00008423 CXXCastPath BasePath;
8424 BasePath.push_back(Base);
8425
Douglas Gregor06a9f362010-05-01 20:49:11 +00008426 // Construct the "from" expression, which is an implicit cast to the
8427 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008428 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008429 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8430 CK_UncheckedDerivedToBase,
8431 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008432
8433 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008434 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008435
8436 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008437 To = ImpCastExprToType(To.take(),
8438 Context.getCVRQualifiedType(BaseType,
8439 CopyAssignOperator->getTypeQualifiers()),
8440 CK_UncheckedDerivedToBase,
8441 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008442
8443 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008444 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008445 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008446 /*CopyingBaseSubobject=*/true,
8447 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008448 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008449 Diag(CurrentLocation, diag::note_member_synthesized_at)
8450 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8451 CopyAssignOperator->setInvalidDecl();
8452 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008453 }
8454
8455 // Success! Record the copy.
8456 Statements.push_back(Copy.takeAs<Expr>());
8457 }
8458
Douglas Gregor06a9f362010-05-01 20:49:11 +00008459 // Assign non-static members.
8460 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8461 FieldEnd = ClassDecl->field_end();
8462 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008463 if (Field->isUnnamedBitfield())
8464 continue;
8465
Douglas Gregor06a9f362010-05-01 20:49:11 +00008466 // Check for members of reference type; we can't copy those.
8467 if (Field->getType()->isReferenceType()) {
8468 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8469 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8470 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008471 Diag(CurrentLocation, diag::note_member_synthesized_at)
8472 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008473 Invalid = true;
8474 continue;
8475 }
8476
8477 // Check for members of const-qualified, non-class type.
8478 QualType BaseType = Context.getBaseElementType(Field->getType());
8479 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8480 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8481 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8482 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008483 Diag(CurrentLocation, diag::note_member_synthesized_at)
8484 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008485 Invalid = true;
8486 continue;
8487 }
John McCallb77115d2011-06-17 00:18:42 +00008488
8489 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008490 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8491 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008492
8493 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008494 if (FieldType->isIncompleteArrayType()) {
8495 assert(ClassDecl->hasFlexibleArrayMember() &&
8496 "Incomplete array type is not valid");
8497 continue;
8498 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008499
8500 // Build references to the field in the object we're copying from and to.
8501 CXXScopeSpec SS; // Intentionally empty
8502 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8503 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008504 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008505 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008506 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008507 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008508 SS, SourceLocation(), 0,
8509 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008510 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008511 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008512 SS, SourceLocation(), 0,
8513 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008514 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8515 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008516
Douglas Gregor06a9f362010-05-01 20:49:11 +00008517 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008518 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008519 To.get(), From.get(),
8520 /*CopyingBaseSubobject=*/false,
8521 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008522 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008523 Diag(CurrentLocation, diag::note_member_synthesized_at)
8524 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8525 CopyAssignOperator->setInvalidDecl();
8526 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008527 }
8528
8529 // Success! Record the copy.
8530 Statements.push_back(Copy.takeAs<Stmt>());
8531 }
8532
8533 if (!Invalid) {
8534 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008535 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008536
John McCall60d7b3a2010-08-24 06:29:42 +00008537 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008538 if (Return.isInvalid())
8539 Invalid = true;
8540 else {
8541 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008542
8543 if (Trap.hasErrorOccurred()) {
8544 Diag(CurrentLocation, diag::note_member_synthesized_at)
8545 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8546 Invalid = true;
8547 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008548 }
8549 }
8550
8551 if (Invalid) {
8552 CopyAssignOperator->setInvalidDecl();
8553 return;
8554 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008555
8556 StmtResult Body;
8557 {
8558 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008559 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008560 /*isStmtExpr=*/false);
8561 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8562 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008563 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008564
8565 if (ASTMutationListener *L = getASTMutationListener()) {
8566 L->CompletedImplicitDefinition(CopyAssignOperator);
8567 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008568}
8569
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008570Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008571Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8572 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008573
Richard Smithb9d0b762012-07-27 04:22:15 +00008574 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008575 if (ClassDecl->isInvalidDecl())
8576 return ExceptSpec;
8577
8578 // C++0x [except.spec]p14:
8579 // An implicitly declared special member function (Clause 12) shall have an
8580 // exception-specification. [...]
8581
8582 // It is unspecified whether or not an implicit move assignment operator
8583 // attempts to deduplicate calls to assignment operators of virtual bases are
8584 // made. As such, this exception specification is effectively unspecified.
8585 // Based on a similar decision made for constness in C++0x, we're erring on
8586 // the side of assuming such calls to be made regardless of whether they
8587 // actually happen.
8588 // Note that a move constructor is not implicitly declared when there are
8589 // virtual bases, but it can still be user-declared and explicitly defaulted.
8590 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8591 BaseEnd = ClassDecl->bases_end();
8592 Base != BaseEnd; ++Base) {
8593 if (Base->isVirtual())
8594 continue;
8595
8596 CXXRecordDecl *BaseClassDecl
8597 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8598 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008599 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008600 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008601 }
8602
8603 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8604 BaseEnd = ClassDecl->vbases_end();
8605 Base != BaseEnd; ++Base) {
8606 CXXRecordDecl *BaseClassDecl
8607 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8608 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008609 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008610 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008611 }
8612
8613 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8614 FieldEnd = ClassDecl->field_end();
8615 Field != FieldEnd;
8616 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008617 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008618 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008619 if (CXXMethodDecl *MoveAssign =
8620 LookupMovingAssignment(FieldClassDecl,
8621 FieldType.getCVRQualifiers(),
8622 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008623 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008624 }
8625 }
8626
8627 return ExceptSpec;
8628}
8629
Richard Smith1c931be2012-04-02 18:40:40 +00008630/// Determine whether the class type has any direct or indirect virtual base
8631/// classes which have a non-trivial move assignment operator.
8632static bool
8633hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8634 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8635 BaseEnd = ClassDecl->vbases_end();
8636 Base != BaseEnd; ++Base) {
8637 CXXRecordDecl *BaseClass =
8638 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8639
8640 // Try to declare the move assignment. If it would be deleted, then the
8641 // class does not have a non-trivial move assignment.
8642 if (BaseClass->needsImplicitMoveAssignment())
8643 S.DeclareImplicitMoveAssignment(BaseClass);
8644
Richard Smith426391c2012-11-16 00:53:38 +00008645 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008646 return true;
8647 }
8648
8649 return false;
8650}
8651
8652/// Determine whether the given type either has a move constructor or is
8653/// trivially copyable.
8654static bool
8655hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8656 Type = S.Context.getBaseElementType(Type);
8657
8658 // FIXME: Technically, non-trivially-copyable non-class types, such as
8659 // reference types, are supposed to return false here, but that appears
8660 // to be a standard defect.
8661 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008662 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008663 return true;
8664
8665 if (Type.isTriviallyCopyableType(S.Context))
8666 return true;
8667
8668 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008669 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8670 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008671 if (ClassDecl->needsImplicitMoveConstructor())
8672 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008673 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008674 }
8675
Richard Smithe5411b72012-12-01 02:35:44 +00008676 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8677 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008678 if (ClassDecl->needsImplicitMoveAssignment())
8679 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008680 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008681}
8682
8683/// Determine whether all non-static data members and direct or virtual bases
8684/// of class \p ClassDecl have either a move operation, or are trivially
8685/// copyable.
8686static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8687 bool IsConstructor) {
8688 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8689 BaseEnd = ClassDecl->bases_end();
8690 Base != BaseEnd; ++Base) {
8691 if (Base->isVirtual())
8692 continue;
8693
8694 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8695 return false;
8696 }
8697
8698 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8699 BaseEnd = ClassDecl->vbases_end();
8700 Base != BaseEnd; ++Base) {
8701 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8702 return false;
8703 }
8704
8705 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8706 FieldEnd = ClassDecl->field_end();
8707 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008708 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008709 return false;
8710 }
8711
8712 return true;
8713}
8714
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008715CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008716 // C++11 [class.copy]p20:
8717 // If the definition of a class X does not explicitly declare a move
8718 // assignment operator, one will be implicitly declared as defaulted
8719 // if and only if:
8720 //
8721 // - [first 4 bullets]
8722 assert(ClassDecl->needsImplicitMoveAssignment());
8723
Richard Smithafb49182012-11-29 01:34:07 +00008724 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8725 if (DSM.isAlreadyBeingDeclared())
8726 return 0;
8727
Richard Smith1c931be2012-04-02 18:40:40 +00008728 // [Checked after we build the declaration]
8729 // - the move assignment operator would not be implicitly defined as
8730 // deleted,
8731
8732 // [DR1402]:
8733 // - X has no direct or indirect virtual base class with a non-trivial
8734 // move assignment operator, and
8735 // - each of X's non-static data members and direct or virtual base classes
8736 // has a type that either has a move assignment operator or is trivially
8737 // copyable.
8738 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8739 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8740 ClassDecl->setFailedImplicitMoveAssignment();
8741 return 0;
8742 }
8743
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008744 // Note: The following rules are largely analoguous to the move
8745 // constructor rules.
8746
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008747 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8748 QualType RetType = Context.getLValueReferenceType(ArgType);
8749 ArgType = Context.getRValueReferenceType(ArgType);
8750
8751 // An implicitly-declared move assignment operator is an inline public
8752 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008753 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8754 SourceLocation ClassLoc = ClassDecl->getLocation();
8755 DeclarationNameInfo NameInfo(Name, ClassLoc);
8756 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008757 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008758 /*TInfo=*/0, /*isStatic=*/false,
8759 /*StorageClassAsWritten=*/SC_None,
8760 /*isInline=*/true,
8761 /*isConstexpr=*/false,
8762 SourceLocation());
8763 MoveAssignment->setAccess(AS_public);
8764 MoveAssignment->setDefaulted();
8765 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008766
Richard Smithb9d0b762012-07-27 04:22:15 +00008767 // Build an exception specification pointing back at this member.
8768 FunctionProtoType::ExtProtoInfo EPI;
8769 EPI.ExceptionSpecType = EST_Unevaluated;
8770 EPI.ExceptionSpecDecl = MoveAssignment;
8771 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8772
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008773 // Add the parameter to the operator.
8774 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8775 ClassLoc, ClassLoc, /*Id=*/0,
8776 ArgType, /*TInfo=*/0,
8777 SC_None,
8778 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008779 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008780
Richard Smithbc2a35d2012-12-08 08:32:28 +00008781 AddOverriddenMethods(ClassDecl, MoveAssignment);
8782
8783 MoveAssignment->setTrivial(
8784 ClassDecl->needsOverloadResolutionForMoveAssignment()
8785 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8786 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008787
8788 // C++0x [class.copy]p9:
8789 // If the definition of a class X does not explicitly declare a move
8790 // assignment operator, one will be implicitly declared as defaulted if and
8791 // only if:
8792 // [...]
8793 // - the move assignment operator would not be implicitly defined as
8794 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008795 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008796 // Cache this result so that we don't try to generate this over and over
8797 // on every lookup, leaking memory and wasting time.
8798 ClassDecl->setFailedImplicitMoveAssignment();
8799 return 0;
8800 }
8801
Richard Smithbc2a35d2012-12-08 08:32:28 +00008802 // Note that we have added this copy-assignment operator.
8803 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8804
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008805 if (Scope *S = getScopeForContext(ClassDecl))
8806 PushOnScopeChains(MoveAssignment, S, false);
8807 ClassDecl->addDecl(MoveAssignment);
8808
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008809 return MoveAssignment;
8810}
8811
8812void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8813 CXXMethodDecl *MoveAssignOperator) {
8814 assert((MoveAssignOperator->isDefaulted() &&
8815 MoveAssignOperator->isOverloadedOperator() &&
8816 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008817 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8818 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008819 "DefineImplicitMoveAssignment called for wrong function");
8820
8821 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8822
8823 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8824 MoveAssignOperator->setInvalidDecl();
8825 return;
8826 }
8827
8828 MoveAssignOperator->setUsed();
8829
Eli Friedman9a14db32012-10-18 20:14:08 +00008830 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008831 DiagnosticErrorTrap Trap(Diags);
8832
8833 // C++0x [class.copy]p28:
8834 // The implicitly-defined or move assignment operator for a non-union class
8835 // X performs memberwise move assignment of its subobjects. The direct base
8836 // classes of X are assigned first, in the order of their declaration in the
8837 // base-specifier-list, and then the immediate non-static data members of X
8838 // are assigned, in the order in which they were declared in the class
8839 // definition.
8840
8841 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008842 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008843
8844 // The parameter for the "other" object, which we are move from.
8845 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8846 QualType OtherRefType = Other->getType()->
8847 getAs<RValueReferenceType>()->getPointeeType();
8848 assert(OtherRefType.getQualifiers() == 0 &&
8849 "Bad argument type of defaulted move assignment");
8850
8851 // Our location for everything implicitly-generated.
8852 SourceLocation Loc = MoveAssignOperator->getLocation();
8853
8854 // Construct a reference to the "other" object. We'll be using this
8855 // throughout the generated ASTs.
8856 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8857 assert(OtherRef && "Reference to parameter cannot fail!");
8858 // Cast to rvalue.
8859 OtherRef = CastForMoving(*this, OtherRef);
8860
8861 // Construct the "this" pointer. We'll be using this throughout the generated
8862 // ASTs.
8863 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8864 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008865
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008866 // Assign base classes.
8867 bool Invalid = false;
8868 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8869 E = ClassDecl->bases_end(); Base != E; ++Base) {
8870 // Form the assignment:
8871 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8872 QualType BaseType = Base->getType().getUnqualifiedType();
8873 if (!BaseType->isRecordType()) {
8874 Invalid = true;
8875 continue;
8876 }
8877
8878 CXXCastPath BasePath;
8879 BasePath.push_back(Base);
8880
8881 // Construct the "from" expression, which is an implicit cast to the
8882 // appropriately-qualified base type.
8883 Expr *From = OtherRef;
8884 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008885 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008886
8887 // Dereference "this".
8888 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8889
8890 // Implicitly cast "this" to the appropriately-qualified base type.
8891 To = ImpCastExprToType(To.take(),
8892 Context.getCVRQualifiedType(BaseType,
8893 MoveAssignOperator->getTypeQualifiers()),
8894 CK_UncheckedDerivedToBase,
8895 VK_LValue, &BasePath);
8896
8897 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00008898 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008899 To.get(), From,
8900 /*CopyingBaseSubobject=*/true,
8901 /*Copying=*/false);
8902 if (Move.isInvalid()) {
8903 Diag(CurrentLocation, diag::note_member_synthesized_at)
8904 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8905 MoveAssignOperator->setInvalidDecl();
8906 return;
8907 }
8908
8909 // Success! Record the move.
8910 Statements.push_back(Move.takeAs<Expr>());
8911 }
8912
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008913 // Assign non-static members.
8914 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8915 FieldEnd = ClassDecl->field_end();
8916 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008917 if (Field->isUnnamedBitfield())
8918 continue;
8919
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008920 // Check for members of reference type; we can't move those.
8921 if (Field->getType()->isReferenceType()) {
8922 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8923 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8924 Diag(Field->getLocation(), diag::note_declared_at);
8925 Diag(CurrentLocation, diag::note_member_synthesized_at)
8926 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8927 Invalid = true;
8928 continue;
8929 }
8930
8931 // Check for members of const-qualified, non-class type.
8932 QualType BaseType = Context.getBaseElementType(Field->getType());
8933 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8934 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8935 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8936 Diag(Field->getLocation(), diag::note_declared_at);
8937 Diag(CurrentLocation, diag::note_member_synthesized_at)
8938 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8939 Invalid = true;
8940 continue;
8941 }
8942
8943 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008944 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8945 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008946
8947 QualType FieldType = Field->getType().getNonReferenceType();
8948 if (FieldType->isIncompleteArrayType()) {
8949 assert(ClassDecl->hasFlexibleArrayMember() &&
8950 "Incomplete array type is not valid");
8951 continue;
8952 }
8953
8954 // Build references to the field in the object we're copying from and to.
8955 CXXScopeSpec SS; // Intentionally empty
8956 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8957 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008958 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008959 MemberLookup.resolveKind();
8960 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8961 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008962 SS, SourceLocation(), 0,
8963 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008964 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8965 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008966 SS, SourceLocation(), 0,
8967 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008968 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8969 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8970
8971 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8972 "Member reference with rvalue base must be rvalue except for reference "
8973 "members, which aren't allowed for move assignment.");
8974
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008975 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008976 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008977 To.get(), From.get(),
8978 /*CopyingBaseSubobject=*/false,
8979 /*Copying=*/false);
8980 if (Move.isInvalid()) {
8981 Diag(CurrentLocation, diag::note_member_synthesized_at)
8982 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8983 MoveAssignOperator->setInvalidDecl();
8984 return;
8985 }
Richard Smithe7ce7092012-11-12 23:33:00 +00008986
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008987 // Success! Record the copy.
8988 Statements.push_back(Move.takeAs<Stmt>());
8989 }
8990
8991 if (!Invalid) {
8992 // Add a "return *this;"
8993 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8994
8995 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8996 if (Return.isInvalid())
8997 Invalid = true;
8998 else {
8999 Statements.push_back(Return.takeAs<Stmt>());
9000
9001 if (Trap.hasErrorOccurred()) {
9002 Diag(CurrentLocation, diag::note_member_synthesized_at)
9003 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9004 Invalid = true;
9005 }
9006 }
9007 }
9008
9009 if (Invalid) {
9010 MoveAssignOperator->setInvalidDecl();
9011 return;
9012 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009013
9014 StmtResult Body;
9015 {
9016 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009017 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009018 /*isStmtExpr=*/false);
9019 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9020 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009021 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9022
9023 if (ASTMutationListener *L = getASTMutationListener()) {
9024 L->CompletedImplicitDefinition(MoveAssignOperator);
9025 }
9026}
9027
Richard Smithb9d0b762012-07-27 04:22:15 +00009028Sema::ImplicitExceptionSpecification
9029Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9030 CXXRecordDecl *ClassDecl = MD->getParent();
9031
9032 ImplicitExceptionSpecification ExceptSpec(*this);
9033 if (ClassDecl->isInvalidDecl())
9034 return ExceptSpec;
9035
9036 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9037 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9038 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9039
Douglas Gregor0d405db2010-07-01 20:59:04 +00009040 // C++ [except.spec]p14:
9041 // An implicitly declared special member function (Clause 12) shall have an
9042 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009043 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9044 BaseEnd = ClassDecl->bases_end();
9045 Base != BaseEnd;
9046 ++Base) {
9047 // Virtual bases are handled below.
9048 if (Base->isVirtual())
9049 continue;
9050
Douglas Gregor22584312010-07-02 23:41:54 +00009051 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009052 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009053 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009054 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009055 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009056 }
9057 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9058 BaseEnd = ClassDecl->vbases_end();
9059 Base != BaseEnd;
9060 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009061 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009062 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009063 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009064 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009065 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009066 }
9067 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9068 FieldEnd = ClassDecl->field_end();
9069 Field != FieldEnd;
9070 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009071 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009072 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9073 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009074 LookupCopyingConstructor(FieldClassDecl,
9075 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009076 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009077 }
9078 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009079
Richard Smithb9d0b762012-07-27 04:22:15 +00009080 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009081}
9082
9083CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9084 CXXRecordDecl *ClassDecl) {
9085 // C++ [class.copy]p4:
9086 // If the class definition does not explicitly declare a copy
9087 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009088 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009089
Richard Smithafb49182012-11-29 01:34:07 +00009090 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9091 if (DSM.isAlreadyBeingDeclared())
9092 return 0;
9093
Sean Hunt49634cf2011-05-13 06:10:58 +00009094 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9095 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009096 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009097 if (Const)
9098 ArgType = ArgType.withConst();
9099 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009100
Richard Smith7756afa2012-06-10 05:43:50 +00009101 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9102 CXXCopyConstructor,
9103 Const);
9104
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009105 DeclarationName Name
9106 = Context.DeclarationNames.getCXXConstructorName(
9107 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009108 SourceLocation ClassLoc = ClassDecl->getLocation();
9109 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009110
9111 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009112 // member of its class.
9113 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009114 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009115 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009116 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009117 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009118 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009119
Richard Smithb9d0b762012-07-27 04:22:15 +00009120 // Build an exception specification pointing back at this member.
9121 FunctionProtoType::ExtProtoInfo EPI;
9122 EPI.ExceptionSpecType = EST_Unevaluated;
9123 EPI.ExceptionSpecDecl = CopyConstructor;
9124 CopyConstructor->setType(
9125 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9126
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009127 // Add the parameter to the constructor.
9128 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009129 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009130 /*IdentifierInfo=*/0,
9131 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009132 SC_None,
9133 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009134 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009135
Richard Smithbc2a35d2012-12-08 08:32:28 +00009136 CopyConstructor->setTrivial(
9137 ClassDecl->needsOverloadResolutionForCopyConstructor()
9138 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9139 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009140
Nico Weberafcc96a2012-01-23 03:19:29 +00009141 // C++11 [class.copy]p8:
9142 // ... If the class definition does not explicitly declare a copy
9143 // constructor, there is no user-declared move constructor, and there is no
9144 // user-declared move assignment operator, a copy constructor is implicitly
9145 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009146 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00009147 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00009148
Richard Smithbc2a35d2012-12-08 08:32:28 +00009149 // Note that we have declared this constructor.
9150 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9151
9152 if (Scope *S = getScopeForContext(ClassDecl))
9153 PushOnScopeChains(CopyConstructor, S, false);
9154 ClassDecl->addDecl(CopyConstructor);
9155
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009156 return CopyConstructor;
9157}
9158
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009159void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009160 CXXConstructorDecl *CopyConstructor) {
9161 assert((CopyConstructor->isDefaulted() &&
9162 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009163 !CopyConstructor->doesThisDeclarationHaveABody() &&
9164 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009165 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009166
Anders Carlsson63010a72010-04-23 16:24:12 +00009167 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009168 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009169
Eli Friedman9a14db32012-10-18 20:14:08 +00009170 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009171 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009172
Sean Huntcbb67482011-01-08 20:30:50 +00009173 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009174 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009175 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009176 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009177 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009178 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009179 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009180 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9181 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009182 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009183 /*isStmtExpr=*/false)
9184 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009185 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009186 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009187
9188 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009189 if (ASTMutationListener *L = getASTMutationListener()) {
9190 L->CompletedImplicitDefinition(CopyConstructor);
9191 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009192}
9193
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009194Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009195Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9196 CXXRecordDecl *ClassDecl = MD->getParent();
9197
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009198 // C++ [except.spec]p14:
9199 // An implicitly declared special member function (Clause 12) shall have an
9200 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009201 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009202 if (ClassDecl->isInvalidDecl())
9203 return ExceptSpec;
9204
9205 // Direct base-class constructors.
9206 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9207 BEnd = ClassDecl->bases_end();
9208 B != BEnd; ++B) {
9209 if (B->isVirtual()) // Handled below.
9210 continue;
9211
9212 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9213 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009214 CXXConstructorDecl *Constructor =
9215 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009216 // If this is a deleted function, add it anyway. This might be conformant
9217 // with the standard. This might not. I'm not sure. It might not matter.
9218 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009219 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009220 }
9221 }
9222
9223 // Virtual base-class constructors.
9224 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9225 BEnd = ClassDecl->vbases_end();
9226 B != BEnd; ++B) {
9227 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9228 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009229 CXXConstructorDecl *Constructor =
9230 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009231 // If this is a deleted function, add it anyway. This might be conformant
9232 // with the standard. This might not. I'm not sure. It might not matter.
9233 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009234 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009235 }
9236 }
9237
9238 // Field constructors.
9239 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9240 FEnd = ClassDecl->field_end();
9241 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009242 QualType FieldType = Context.getBaseElementType(F->getType());
9243 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9244 CXXConstructorDecl *Constructor =
9245 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009246 // If this is a deleted function, add it anyway. This might be conformant
9247 // with the standard. This might not. I'm not sure. It might not matter.
9248 // In particular, the problem is that this function never gets called. It
9249 // might just be ill-formed because this function attempts to refer to
9250 // a deleted function here.
9251 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009252 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009253 }
9254 }
9255
9256 return ExceptSpec;
9257}
9258
9259CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9260 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009261 // C++11 [class.copy]p9:
9262 // If the definition of a class X does not explicitly declare a move
9263 // constructor, one will be implicitly declared as defaulted if and only if:
9264 //
9265 // - [first 4 bullets]
9266 assert(ClassDecl->needsImplicitMoveConstructor());
9267
Richard Smithafb49182012-11-29 01:34:07 +00009268 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9269 if (DSM.isAlreadyBeingDeclared())
9270 return 0;
9271
Richard Smith1c931be2012-04-02 18:40:40 +00009272 // [Checked after we build the declaration]
9273 // - the move assignment operator would not be implicitly defined as
9274 // deleted,
9275
9276 // [DR1402]:
9277 // - each of X's non-static data members and direct or virtual base classes
9278 // has a type that either has a move constructor or is trivially copyable.
9279 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9280 ClassDecl->setFailedImplicitMoveConstructor();
9281 return 0;
9282 }
9283
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009284 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9285 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009286
Richard Smith7756afa2012-06-10 05:43:50 +00009287 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9288 CXXMoveConstructor,
9289 false);
9290
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009291 DeclarationName Name
9292 = Context.DeclarationNames.getCXXConstructorName(
9293 Context.getCanonicalType(ClassType));
9294 SourceLocation ClassLoc = ClassDecl->getLocation();
9295 DeclarationNameInfo NameInfo(Name, ClassLoc);
9296
9297 // C++0x [class.copy]p11:
9298 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009299 // member of its class.
9300 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009301 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009302 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009303 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009304 MoveConstructor->setAccess(AS_public);
9305 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009306
Richard Smithb9d0b762012-07-27 04:22:15 +00009307 // Build an exception specification pointing back at this member.
9308 FunctionProtoType::ExtProtoInfo EPI;
9309 EPI.ExceptionSpecType = EST_Unevaluated;
9310 EPI.ExceptionSpecDecl = MoveConstructor;
9311 MoveConstructor->setType(
9312 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9313
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009314 // Add the parameter to the constructor.
9315 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9316 ClassLoc, ClassLoc,
9317 /*IdentifierInfo=*/0,
9318 ArgType, /*TInfo=*/0,
9319 SC_None,
9320 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009321 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009322
Richard Smithbc2a35d2012-12-08 08:32:28 +00009323 MoveConstructor->setTrivial(
9324 ClassDecl->needsOverloadResolutionForMoveConstructor()
9325 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9326 : ClassDecl->hasTrivialMoveConstructor());
9327
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009328 // C++0x [class.copy]p9:
9329 // If the definition of a class X does not explicitly declare a move
9330 // constructor, one will be implicitly declared as defaulted if and only if:
9331 // [...]
9332 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009333 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009334 // Cache this result so that we don't try to generate this over and over
9335 // on every lookup, leaking memory and wasting time.
9336 ClassDecl->setFailedImplicitMoveConstructor();
9337 return 0;
9338 }
9339
9340 // Note that we have declared this constructor.
9341 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9342
9343 if (Scope *S = getScopeForContext(ClassDecl))
9344 PushOnScopeChains(MoveConstructor, S, false);
9345 ClassDecl->addDecl(MoveConstructor);
9346
9347 return MoveConstructor;
9348}
9349
9350void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9351 CXXConstructorDecl *MoveConstructor) {
9352 assert((MoveConstructor->isDefaulted() &&
9353 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009354 !MoveConstructor->doesThisDeclarationHaveABody() &&
9355 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009356 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9357
9358 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9359 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9360
Eli Friedman9a14db32012-10-18 20:14:08 +00009361 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009362 DiagnosticErrorTrap Trap(Diags);
9363
9364 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
9365 Trap.hasErrorOccurred()) {
9366 Diag(CurrentLocation, diag::note_member_synthesized_at)
9367 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9368 MoveConstructor->setInvalidDecl();
9369 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009370 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009371 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9372 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009373 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009374 /*isStmtExpr=*/false)
9375 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009376 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009377 }
9378
9379 MoveConstructor->setUsed();
9380
9381 if (ASTMutationListener *L = getASTMutationListener()) {
9382 L->CompletedImplicitDefinition(MoveConstructor);
9383 }
9384}
9385
Douglas Gregore4e68d42012-02-15 19:33:52 +00009386bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9387 return FD->isDeleted() &&
9388 (FD->isDefaulted() || FD->isImplicit()) &&
9389 isa<CXXMethodDecl>(FD);
9390}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009391
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009392/// \brief Mark the call operator of the given lambda closure type as "used".
9393static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9394 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009395 = cast<CXXMethodDecl>(
9396 *Lambda->lookup(
9397 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009398 CallOperator->setReferenced();
9399 CallOperator->setUsed();
9400}
9401
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009402void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9403 SourceLocation CurrentLocation,
9404 CXXConversionDecl *Conv)
9405{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009406 CXXRecordDecl *Lambda = Conv->getParent();
9407
9408 // Make sure that the lambda call operator is marked used.
9409 markLambdaCallOperatorUsed(*this, Lambda);
9410
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009411 Conv->setUsed();
9412
Eli Friedman9a14db32012-10-18 20:14:08 +00009413 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009414 DiagnosticErrorTrap Trap(Diags);
9415
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009416 // Return the address of the __invoke function.
9417 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9418 CXXMethodDecl *Invoke
9419 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
9420 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9421 VK_LValue, Conv->getLocation()).take();
9422 assert(FunctionRef && "Can't refer to __invoke function?");
9423 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9424 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
9425 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009426 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009427
9428 // Fill in the __invoke function with a dummy implementation. IR generation
9429 // will fill in the actual details.
9430 Invoke->setUsed();
9431 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009432 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009433
9434 if (ASTMutationListener *L = getASTMutationListener()) {
9435 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009436 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009437 }
9438}
9439
9440void Sema::DefineImplicitLambdaToBlockPointerConversion(
9441 SourceLocation CurrentLocation,
9442 CXXConversionDecl *Conv)
9443{
9444 Conv->setUsed();
9445
Eli Friedman9a14db32012-10-18 20:14:08 +00009446 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009447 DiagnosticErrorTrap Trap(Diags);
9448
Douglas Gregorac1303e2012-02-22 05:02:47 +00009449 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009450 Expr *This = ActOnCXXThis(CurrentLocation).take();
9451 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009452
Eli Friedman23f02672012-03-01 04:01:32 +00009453 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9454 Conv->getLocation(),
9455 Conv, DerefThis);
9456
9457 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9458 // behavior. Note that only the general conversion function does this
9459 // (since it's unusable otherwise); in the case where we inline the
9460 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009461 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009462 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9463 CK_CopyAndAutoreleaseBlockObject,
9464 BuildBlock.get(), 0, VK_RValue);
9465
9466 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009467 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009468 Conv->setInvalidDecl();
9469 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009470 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009471
Douglas Gregorac1303e2012-02-22 05:02:47 +00009472 // Create the return statement that returns the block from the conversion
9473 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009474 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009475 if (Return.isInvalid()) {
9476 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9477 Conv->setInvalidDecl();
9478 return;
9479 }
9480
9481 // Set the body of the conversion function.
9482 Stmt *ReturnS = Return.take();
9483 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9484 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009485 Conv->getLocation()));
9486
Douglas Gregorac1303e2012-02-22 05:02:47 +00009487 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009488 if (ASTMutationListener *L = getASTMutationListener()) {
9489 L->CompletedImplicitDefinition(Conv);
9490 }
9491}
9492
Douglas Gregorf52757d2012-03-10 06:53:13 +00009493/// \brief Determine whether the given list arguments contains exactly one
9494/// "real" (non-default) argument.
9495static bool hasOneRealArgument(MultiExprArg Args) {
9496 switch (Args.size()) {
9497 case 0:
9498 return false;
9499
9500 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009501 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009502 return false;
9503
9504 // fall through
9505 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009506 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009507 }
9508
9509 return false;
9510}
9511
John McCall60d7b3a2010-08-24 06:29:42 +00009512ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009513Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009514 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009515 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009516 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009517 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009518 unsigned ConstructKind,
9519 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009520 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009521
Douglas Gregor2f599792010-04-02 18:24:57 +00009522 // C++0x [class.copy]p34:
9523 // When certain criteria are met, an implementation is allowed to
9524 // omit the copy/move construction of a class object, even if the
9525 // copy/move constructor and/or destructor for the object have
9526 // side effects. [...]
9527 // - when a temporary class object that has not been bound to a
9528 // reference (12.2) would be copied/moved to a class object
9529 // with the same cv-unqualified type, the copy/move operation
9530 // can be omitted by constructing the temporary object
9531 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009532 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009533 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009534 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009535 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009536 }
Mike Stump1eb44332009-09-09 15:08:12 +00009537
9538 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009539 Elidable, ExprArgs, HadMultipleCandidates,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009540 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009541}
9542
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009543/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9544/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009545ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009546Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9547 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009548 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009549 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009550 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009551 unsigned ConstructKind,
9552 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009553 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009554 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009555 Constructor, Elidable, ExprArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009556 HadMultipleCandidates, /*FIXME*/false,
9557 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009558 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9559 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009560}
9561
Mike Stump1eb44332009-09-09 15:08:12 +00009562bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009563 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009564 MultiExprArg Exprs,
9565 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009566 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009567 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009568 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009569 Exprs, HadMultipleCandidates, false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009570 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009571 if (TempResult.isInvalid())
9572 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009573
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009574 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009575 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009576 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009577 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009578 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009579
Anders Carlssonfe2de492009-08-25 05:18:00 +00009580 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009581}
9582
John McCall68c6c9a2010-02-02 09:10:11 +00009583void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009584 if (VD->isInvalidDecl()) return;
9585
John McCall68c6c9a2010-02-02 09:10:11 +00009586 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009587 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009588 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009589 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009590
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009591 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009592 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009593 CheckDestructorAccess(VD->getLocation(), Destructor,
9594 PDiag(diag::err_access_dtor_var)
9595 << VD->getDeclName()
9596 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009597 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009598
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009599 if (!VD->hasGlobalStorage()) return;
9600
9601 // Emit warning for non-trivial dtor in global scope (a real global,
9602 // class-static, function-static).
9603 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9604
9605 // TODO: this should be re-enabled for static locals by !CXAAtExit
9606 if (!VD->isStaticLocal())
9607 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009608}
9609
Douglas Gregor39da0b82009-09-09 23:08:42 +00009610/// \brief Given a constructor and the set of arguments provided for the
9611/// constructor, convert the arguments and add any required default arguments
9612/// to form a proper call to this constructor.
9613///
9614/// \returns true if an error occurred, false otherwise.
9615bool
9616Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9617 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009618 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009619 SmallVectorImpl<Expr*> &ConvertedArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009620 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009621 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9622 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009623 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009624
9625 const FunctionProtoType *Proto
9626 = Constructor->getType()->getAs<FunctionProtoType>();
9627 assert(Proto && "Constructor without a prototype?");
9628 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009629
9630 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009631 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009632 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009633 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009634 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009635
9636 VariadicCallType CallType =
9637 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009638 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009639 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9640 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009641 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009642 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009643
9644 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9645
Richard Smith831421f2012-06-25 20:30:08 +00009646 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9647 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009648
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009649 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009650}
9651
Anders Carlsson20d45d22009-12-12 00:32:00 +00009652static inline bool
9653CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9654 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009655 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009656 if (isa<NamespaceDecl>(DC)) {
9657 return SemaRef.Diag(FnDecl->getLocation(),
9658 diag::err_operator_new_delete_declared_in_namespace)
9659 << FnDecl->getDeclName();
9660 }
9661
9662 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009663 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009664 return SemaRef.Diag(FnDecl->getLocation(),
9665 diag::err_operator_new_delete_declared_static)
9666 << FnDecl->getDeclName();
9667 }
9668
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009669 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009670}
9671
Anders Carlsson156c78e2009-12-13 17:53:43 +00009672static inline bool
9673CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9674 CanQualType ExpectedResultType,
9675 CanQualType ExpectedFirstParamType,
9676 unsigned DependentParamTypeDiag,
9677 unsigned InvalidParamTypeDiag) {
9678 QualType ResultType =
9679 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9680
9681 // Check that the result type is not dependent.
9682 if (ResultType->isDependentType())
9683 return SemaRef.Diag(FnDecl->getLocation(),
9684 diag::err_operator_new_delete_dependent_result_type)
9685 << FnDecl->getDeclName() << ExpectedResultType;
9686
9687 // Check that the result type is what we expect.
9688 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9689 return SemaRef.Diag(FnDecl->getLocation(),
9690 diag::err_operator_new_delete_invalid_result_type)
9691 << FnDecl->getDeclName() << ExpectedResultType;
9692
9693 // A function template must have at least 2 parameters.
9694 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9695 return SemaRef.Diag(FnDecl->getLocation(),
9696 diag::err_operator_new_delete_template_too_few_parameters)
9697 << FnDecl->getDeclName();
9698
9699 // The function decl must have at least 1 parameter.
9700 if (FnDecl->getNumParams() == 0)
9701 return SemaRef.Diag(FnDecl->getLocation(),
9702 diag::err_operator_new_delete_too_few_parameters)
9703 << FnDecl->getDeclName();
9704
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009705 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009706 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9707 if (FirstParamType->isDependentType())
9708 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9709 << FnDecl->getDeclName() << ExpectedFirstParamType;
9710
9711 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009712 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009713 ExpectedFirstParamType)
9714 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9715 << FnDecl->getDeclName() << ExpectedFirstParamType;
9716
9717 return false;
9718}
9719
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009720static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009721CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009722 // C++ [basic.stc.dynamic.allocation]p1:
9723 // A program is ill-formed if an allocation function is declared in a
9724 // namespace scope other than global scope or declared static in global
9725 // scope.
9726 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9727 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009728
9729 CanQualType SizeTy =
9730 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9731
9732 // C++ [basic.stc.dynamic.allocation]p1:
9733 // The return type shall be void*. The first parameter shall have type
9734 // std::size_t.
9735 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9736 SizeTy,
9737 diag::err_operator_new_dependent_param_type,
9738 diag::err_operator_new_param_type))
9739 return true;
9740
9741 // C++ [basic.stc.dynamic.allocation]p1:
9742 // The first parameter shall not have an associated default argument.
9743 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009744 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009745 diag::err_operator_new_default_arg)
9746 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9747
9748 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009749}
9750
9751static bool
Richard Smith444d3842012-10-20 08:26:51 +00009752CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009753 // C++ [basic.stc.dynamic.deallocation]p1:
9754 // A program is ill-formed if deallocation functions are declared in a
9755 // namespace scope other than global scope or declared static in global
9756 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009757 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9758 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009759
9760 // C++ [basic.stc.dynamic.deallocation]p2:
9761 // Each deallocation function shall return void and its first parameter
9762 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009763 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9764 SemaRef.Context.VoidPtrTy,
9765 diag::err_operator_delete_dependent_param_type,
9766 diag::err_operator_delete_param_type))
9767 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009768
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009769 return false;
9770}
9771
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009772/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9773/// of this overloaded operator is well-formed. If so, returns false;
9774/// otherwise, emits appropriate diagnostics and returns true.
9775bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009776 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009777 "Expected an overloaded operator declaration");
9778
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009779 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9780
Mike Stump1eb44332009-09-09 15:08:12 +00009781 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009782 // The allocation and deallocation functions, operator new,
9783 // operator new[], operator delete and operator delete[], are
9784 // described completely in 3.7.3. The attributes and restrictions
9785 // found in the rest of this subclause do not apply to them unless
9786 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009787 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009788 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009789
Anders Carlssona3ccda52009-12-12 00:26:23 +00009790 if (Op == OO_New || Op == OO_Array_New)
9791 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009792
9793 // C++ [over.oper]p6:
9794 // An operator function shall either be a non-static member
9795 // function or be a non-member function and have at least one
9796 // parameter whose type is a class, a reference to a class, an
9797 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009798 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9799 if (MethodDecl->isStatic())
9800 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009801 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009802 } else {
9803 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009804 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9805 ParamEnd = FnDecl->param_end();
9806 Param != ParamEnd; ++Param) {
9807 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009808 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9809 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009810 ClassOrEnumParam = true;
9811 break;
9812 }
9813 }
9814
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009815 if (!ClassOrEnumParam)
9816 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009817 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009818 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009819 }
9820
9821 // C++ [over.oper]p8:
9822 // An operator function cannot have default arguments (8.3.6),
9823 // except where explicitly stated below.
9824 //
Mike Stump1eb44332009-09-09 15:08:12 +00009825 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009826 // (C++ [over.call]p1).
9827 if (Op != OO_Call) {
9828 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9829 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009830 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009831 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009832 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009833 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009834 }
9835 }
9836
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009837 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9838 { false, false, false }
9839#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9840 , { Unary, Binary, MemberOnly }
9841#include "clang/Basic/OperatorKinds.def"
9842 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009843
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009844 bool CanBeUnaryOperator = OperatorUses[Op][0];
9845 bool CanBeBinaryOperator = OperatorUses[Op][1];
9846 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009847
9848 // C++ [over.oper]p8:
9849 // [...] Operator functions cannot have more or fewer parameters
9850 // than the number required for the corresponding operator, as
9851 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009852 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009853 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009854 if (Op != OO_Call &&
9855 ((NumParams == 1 && !CanBeUnaryOperator) ||
9856 (NumParams == 2 && !CanBeBinaryOperator) ||
9857 (NumParams < 1) || (NumParams > 2))) {
9858 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009859 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009860 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009861 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009862 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009863 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009864 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009865 assert(CanBeBinaryOperator &&
9866 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009867 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009868 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009869
Chris Lattner416e46f2008-11-21 07:57:12 +00009870 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009871 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009872 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009873
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009874 // Overloaded operators other than operator() cannot be variadic.
9875 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009876 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009877 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009878 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009879 }
9880
9881 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009882 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9883 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009884 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009885 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009886 }
9887
9888 // C++ [over.inc]p1:
9889 // The user-defined function called operator++ implements the
9890 // prefix and postfix ++ operator. If this function is a member
9891 // function with no parameters, or a non-member function with one
9892 // parameter of class or enumeration type, it defines the prefix
9893 // increment operator ++ for objects of that type. If the function
9894 // is a member function with one parameter (which shall be of type
9895 // int) or a non-member function with two parameters (the second
9896 // of which shall be of type int), it defines the postfix
9897 // increment operator ++ for objects of that type.
9898 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9899 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9900 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009901 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009902 ParamIsInt = BT->getKind() == BuiltinType::Int;
9903
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009904 if (!ParamIsInt)
9905 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009906 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009907 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009908 }
9909
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009910 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009911}
Chris Lattner5a003a42008-12-17 07:09:26 +00009912
Sean Hunta6c058d2010-01-13 09:01:02 +00009913/// CheckLiteralOperatorDeclaration - Check whether the declaration
9914/// of this literal operator function is well-formed. If so, returns
9915/// false; otherwise, emits appropriate diagnostics and returns true.
9916bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009917 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009918 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9919 << FnDecl->getDeclName();
9920 return true;
9921 }
9922
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009923 if (FnDecl->isExternC()) {
9924 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9925 return true;
9926 }
9927
Sean Hunta6c058d2010-01-13 09:01:02 +00009928 bool Valid = false;
9929
Richard Smith36f5cfe2012-03-09 08:00:36 +00009930 // This might be the definition of a literal operator template.
9931 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9932 // This might be a specialization of a literal operator template.
9933 if (!TpDecl)
9934 TpDecl = FnDecl->getPrimaryTemplate();
9935
Sean Hunt216c2782010-04-07 23:11:06 +00009936 // template <char...> type operator "" name() is the only valid template
9937 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009938 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009939 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009940 // Must have only one template parameter
9941 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9942 if (Params->size() == 1) {
9943 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009944 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009945
Sean Hunt216c2782010-04-07 23:11:06 +00009946 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009947 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9948 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9949 Valid = true;
9950 }
9951 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009952 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009953 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009954 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9955
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009956 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009957
Sean Hunt30019c02010-04-07 22:57:35 +00009958 // unsigned long long int, long double, and any character type are allowed
9959 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009960 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9961 Context.hasSameType(T, Context.LongDoubleTy) ||
9962 Context.hasSameType(T, Context.CharTy) ||
9963 Context.hasSameType(T, Context.WCharTy) ||
9964 Context.hasSameType(T, Context.Char16Ty) ||
9965 Context.hasSameType(T, Context.Char32Ty)) {
9966 if (++Param == FnDecl->param_end())
9967 Valid = true;
9968 goto FinishedParams;
9969 }
9970
Sean Hunt30019c02010-04-07 22:57:35 +00009971 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009972 const PointerType *PT = T->getAs<PointerType>();
9973 if (!PT)
9974 goto FinishedParams;
9975 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009976 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009977 goto FinishedParams;
9978 T = T.getUnqualifiedType();
9979
9980 // Move on to the second parameter;
9981 ++Param;
9982
9983 // If there is no second parameter, the first must be a const char *
9984 if (Param == FnDecl->param_end()) {
9985 if (Context.hasSameType(T, Context.CharTy))
9986 Valid = true;
9987 goto FinishedParams;
9988 }
9989
9990 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9991 // are allowed as the first parameter to a two-parameter function
9992 if (!(Context.hasSameType(T, Context.CharTy) ||
9993 Context.hasSameType(T, Context.WCharTy) ||
9994 Context.hasSameType(T, Context.Char16Ty) ||
9995 Context.hasSameType(T, Context.Char32Ty)))
9996 goto FinishedParams;
9997
9998 // The second and final parameter must be an std::size_t
9999 T = (*Param)->getType().getUnqualifiedType();
10000 if (Context.hasSameType(T, Context.getSizeType()) &&
10001 ++Param == FnDecl->param_end())
10002 Valid = true;
10003 }
10004
10005 // FIXME: This diagnostic is absolutely terrible.
10006FinishedParams:
10007 if (!Valid) {
10008 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10009 << FnDecl->getDeclName();
10010 return true;
10011 }
10012
Richard Smitha9e88b22012-03-09 08:16:22 +000010013 // A parameter-declaration-clause containing a default argument is not
10014 // equivalent to any of the permitted forms.
10015 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10016 ParamEnd = FnDecl->param_end();
10017 Param != ParamEnd; ++Param) {
10018 if ((*Param)->hasDefaultArg()) {
10019 Diag((*Param)->getDefaultArgRange().getBegin(),
10020 diag::err_literal_operator_default_argument)
10021 << (*Param)->getDefaultArgRange();
10022 break;
10023 }
10024 }
10025
Richard Smith2fb4ae32012-03-08 02:39:21 +000010026 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010027 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10028 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010029 // C++11 [usrlit.suffix]p1:
10030 // Literal suffix identifiers that do not start with an underscore
10031 // are reserved for future standardization.
10032 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010033 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010034
Sean Hunta6c058d2010-01-13 09:01:02 +000010035 return false;
10036}
10037
Douglas Gregor074149e2009-01-05 19:45:36 +000010038/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10039/// linkage specification, including the language and (if present)
10040/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10041/// the location of the language string literal, which is provided
10042/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10043/// the '{' brace. Otherwise, this linkage specification does not
10044/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010045Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10046 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010047 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010048 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010049 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010050 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010051 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010052 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010053 Language = LinkageSpecDecl::lang_cxx;
10054 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010055 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010056 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010057 }
Mike Stump1eb44332009-09-09 15:08:12 +000010058
Chris Lattnercc98eac2008-12-17 07:13:27 +000010059 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010060
Douglas Gregor074149e2009-01-05 19:45:36 +000010061 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010062 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010063 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010064 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010065 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010066}
10067
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010068/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010069/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10070/// valid, it's the position of the closing '}' brace in a linkage
10071/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010072Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010073 Decl *LinkageSpec,
10074 SourceLocation RBraceLoc) {
10075 if (LinkageSpec) {
10076 if (RBraceLoc.isValid()) {
10077 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10078 LSDecl->setRBraceLoc(RBraceLoc);
10079 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010080 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010081 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010082 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010083}
10084
Douglas Gregord308e622009-05-18 20:51:54 +000010085/// \brief Perform semantic analysis for the variable declaration that
10086/// occurs within a C++ catch clause, returning the newly-created
10087/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010088VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010089 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010090 SourceLocation StartLoc,
10091 SourceLocation Loc,
10092 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010093 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010094 QualType ExDeclType = TInfo->getType();
10095
Sebastian Redl4b07b292008-12-22 19:15:10 +000010096 // Arrays and functions decay.
10097 if (ExDeclType->isArrayType())
10098 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10099 else if (ExDeclType->isFunctionType())
10100 ExDeclType = Context.getPointerType(ExDeclType);
10101
10102 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10103 // The exception-declaration shall not denote a pointer or reference to an
10104 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010105 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010106 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010107 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010108 Invalid = true;
10109 }
Douglas Gregord308e622009-05-18 20:51:54 +000010110
Sebastian Redl4b07b292008-12-22 19:15:10 +000010111 QualType BaseType = ExDeclType;
10112 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010113 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010114 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010115 BaseType = Ptr->getPointeeType();
10116 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010117 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010118 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010119 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010120 BaseType = Ref->getPointeeType();
10121 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010122 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010123 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010124 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010125 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010126 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010127
Mike Stump1eb44332009-09-09 15:08:12 +000010128 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010129 RequireNonAbstractType(Loc, ExDeclType,
10130 diag::err_abstract_type_in_decl,
10131 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010132 Invalid = true;
10133
John McCall5a180392010-07-24 00:37:23 +000010134 // Only the non-fragile NeXT runtime currently supports C++ catches
10135 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010136 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010137 QualType T = ExDeclType;
10138 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10139 T = RT->getPointeeType();
10140
10141 if (T->isObjCObjectType()) {
10142 Diag(Loc, diag::err_objc_object_catch);
10143 Invalid = true;
10144 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010145 // FIXME: should this be a test for macosx-fragile specifically?
10146 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010147 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010148 }
10149 }
10150
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010151 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10152 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010153 ExDecl->setExceptionVariable(true);
10154
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010155 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010156 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010157 Invalid = true;
10158
Douglas Gregorc41b8782011-07-06 18:14:43 +000010159 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010160 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +000010161 // C++ [except.handle]p16:
10162 // The object declared in an exception-declaration or, if the
10163 // exception-declaration does not specify a name, a temporary (12.2) is
10164 // copy-initialized (8.5) from the exception object. [...]
10165 // The object is destroyed when the handler exits, after the destruction
10166 // of any automatic objects initialized within the handler.
10167 //
10168 // We just pretend to initialize the object with itself, then make sure
10169 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010170 QualType initType = ExDeclType;
10171
10172 InitializedEntity entity =
10173 InitializedEntity::InitializeVariable(ExDecl);
10174 InitializationKind initKind =
10175 InitializationKind::CreateCopy(Loc, SourceLocation());
10176
10177 Expr *opaqueValue =
10178 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10179 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10180 ExprResult result = sequence.Perform(*this, entity, initKind,
10181 MultiExprArg(&opaqueValue, 1));
10182 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010183 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010184 else {
10185 // If the constructor used was non-trivial, set this as the
10186 // "initializer".
10187 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10188 if (!construct->getConstructor()->isTrivial()) {
10189 Expr *init = MaybeCreateExprWithCleanups(construct);
10190 ExDecl->setInit(init);
10191 }
10192
10193 // And make sure it's destructable.
10194 FinalizeVarWithDestructor(ExDecl, recordType);
10195 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010196 }
10197 }
10198
Douglas Gregord308e622009-05-18 20:51:54 +000010199 if (Invalid)
10200 ExDecl->setInvalidDecl();
10201
10202 return ExDecl;
10203}
10204
10205/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10206/// handler.
John McCalld226f652010-08-21 09:40:31 +000010207Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010208 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010209 bool Invalid = D.isInvalidType();
10210
10211 // Check for unexpanded parameter packs.
10212 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10213 UPPC_ExceptionType)) {
10214 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10215 D.getIdentifierLoc());
10216 Invalid = true;
10217 }
10218
Sebastian Redl4b07b292008-12-22 19:15:10 +000010219 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010220 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010221 LookupOrdinaryName,
10222 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010223 // The scope should be freshly made just for us. There is just no way
10224 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010225 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010226 if (PrevDecl->isTemplateParameter()) {
10227 // Maybe we will complain about the shadowed template parameter.
10228 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010229 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010230 }
10231 }
10232
Chris Lattnereaaebc72009-04-25 08:06:05 +000010233 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010234 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10235 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010236 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010237 }
10238
Douglas Gregor83cb9422010-09-09 17:09:21 +000010239 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010240 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010241 D.getIdentifierLoc(),
10242 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010243 if (Invalid)
10244 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010245
Sebastian Redl4b07b292008-12-22 19:15:10 +000010246 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010247 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010248 PushOnScopeChains(ExDecl, S);
10249 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010250 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010251
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010252 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010253 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010254}
Anders Carlssonfb311762009-03-14 00:25:26 +000010255
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010256Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010257 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010258 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010259 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010260 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010261
Richard Smithe3f470a2012-07-11 22:37:56 +000010262 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10263 return 0;
10264
10265 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10266 AssertMessage, RParenLoc, false);
10267}
10268
10269Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10270 Expr *AssertExpr,
10271 StringLiteral *AssertMessage,
10272 SourceLocation RParenLoc,
10273 bool Failed) {
10274 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10275 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010276 // In a static_assert-declaration, the constant-expression shall be a
10277 // constant expression that can be contextually converted to bool.
10278 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10279 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010280 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010281
Richard Smithdaaefc52011-12-14 23:32:26 +000010282 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010283 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010284 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010285 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010286 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010287
Richard Smithe3f470a2012-07-11 22:37:56 +000010288 if (!Failed && !Cond) {
Richard Smith0cc323c2012-03-05 23:20:05 +000010289 llvm::SmallString<256> MsgBuffer;
10290 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010291 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010292 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010293 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010294 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010295 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010296 }
Mike Stump1eb44332009-09-09 15:08:12 +000010297
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010298 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010299 AssertExpr, AssertMessage, RParenLoc,
10300 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010301
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010302 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010303 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010304}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010305
Douglas Gregor1d869352010-04-07 16:53:43 +000010306/// \brief Perform semantic analysis of the given friend type declaration.
10307///
10308/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010309FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010310 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010311 TypeSourceInfo *TSInfo) {
10312 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10313
10314 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010315 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010316
Richard Smith6b130222011-10-18 21:39:00 +000010317 // C++03 [class.friend]p2:
10318 // An elaborated-type-specifier shall be used in a friend declaration
10319 // for a class.*
10320 //
10321 // * The class-key of the elaborated-type-specifier is required.
10322 if (!ActiveTemplateInstantiations.empty()) {
10323 // Do not complain about the form of friend template types during
10324 // template instantiation; we will already have complained when the
10325 // template was declared.
10326 } else if (!T->isElaboratedTypeSpecifier()) {
10327 // If we evaluated the type to a record type, suggest putting
10328 // a tag in front.
10329 if (const RecordType *RT = T->getAs<RecordType>()) {
10330 RecordDecl *RD = RT->getDecl();
10331
10332 std::string InsertionText = std::string(" ") + RD->getKindName();
10333
10334 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010335 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010336 diag::warn_cxx98_compat_unelaborated_friend_type :
10337 diag::ext_unelaborated_friend_type)
10338 << (unsigned) RD->getTagKind()
10339 << T
10340 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10341 InsertionText);
10342 } else {
10343 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +000010344 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010345 diag::warn_cxx98_compat_nonclass_type_friend :
10346 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010347 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010348 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010349 }
Richard Smith6b130222011-10-18 21:39:00 +000010350 } else if (T->getAs<EnumType>()) {
10351 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +000010352 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010353 diag::warn_cxx98_compat_enum_friend :
10354 diag::ext_enum_friend)
10355 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010356 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010357 }
10358
Richard Smithd6f80da2012-09-20 01:31:00 +000010359 // C++11 [class.friend]p3:
10360 // A friend declaration that does not declare a function shall have one
10361 // of the following forms:
10362 // friend elaborated-type-specifier ;
10363 // friend simple-type-specifier ;
10364 // friend typename-specifier ;
10365 if (getLangOpts().CPlusPlus0x && LocStart != FriendLoc)
10366 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10367
Douglas Gregor06245bf2010-04-07 17:57:12 +000010368 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010369 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010370 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010371 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010372}
10373
John McCall9a34edb2010-10-19 01:40:49 +000010374/// Handle a friend tag declaration where the scope specifier was
10375/// templated.
10376Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10377 unsigned TagSpec, SourceLocation TagLoc,
10378 CXXScopeSpec &SS,
10379 IdentifierInfo *Name, SourceLocation NameLoc,
10380 AttributeList *Attr,
10381 MultiTemplateParamsArg TempParamLists) {
10382 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10383
10384 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010385 bool Invalid = false;
10386
10387 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010388 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010389 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010390 TempParamLists.size(),
10391 /*friend*/ true,
10392 isExplicitSpecialization,
10393 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010394 if (TemplateParams->size() > 0) {
10395 // This is a declaration of a class template.
10396 if (Invalid)
10397 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010398
Eric Christopher4110e132011-07-21 05:34:24 +000010399 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10400 SS, Name, NameLoc, Attr,
10401 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010402 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010403 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010404 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010405 } else {
10406 // The "template<>" header is extraneous.
10407 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10408 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10409 isExplicitSpecialization = true;
10410 }
10411 }
10412
10413 if (Invalid) return 0;
10414
John McCall9a34edb2010-10-19 01:40:49 +000010415 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010416 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010417 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010418 isAllExplicitSpecializations = false;
10419 break;
10420 }
10421 }
10422
10423 // FIXME: don't ignore attributes.
10424
10425 // If it's explicit specializations all the way down, just forget
10426 // about the template header and build an appropriate non-templated
10427 // friend. TODO: for source fidelity, remember the headers.
10428 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010429 if (SS.isEmpty()) {
10430 bool Owned = false;
10431 bool IsDependent = false;
10432 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10433 Attr, AS_public,
10434 /*ModulePrivateLoc=*/SourceLocation(),
10435 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010436 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010437 /*ScopedEnumUsesClassTag=*/false,
10438 /*UnderlyingType=*/TypeResult());
10439 }
10440
Douglas Gregor2494dd02011-03-01 01:34:45 +000010441 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010442 ElaboratedTypeKeyword Keyword
10443 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010444 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010445 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010446 if (T.isNull())
10447 return 0;
10448
10449 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10450 if (isa<DependentNameType>(T)) {
10451 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010452 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010453 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010454 TL.setNameLoc(NameLoc);
10455 } else {
10456 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010457 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010458 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010459 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10460 }
10461
10462 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10463 TSI, FriendLoc);
10464 Friend->setAccess(AS_public);
10465 CurContext->addDecl(Friend);
10466 return Friend;
10467 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010468
10469 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10470
10471
John McCall9a34edb2010-10-19 01:40:49 +000010472
10473 // Handle the case of a templated-scope friend class. e.g.
10474 // template <class T> class A<T>::B;
10475 // FIXME: we don't support these right now.
10476 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10477 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10478 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10479 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010480 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010481 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010482 TL.setNameLoc(NameLoc);
10483
10484 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10485 TSI, FriendLoc);
10486 Friend->setAccess(AS_public);
10487 Friend->setUnsupportedFriend(true);
10488 CurContext->addDecl(Friend);
10489 return Friend;
10490}
10491
10492
John McCalldd4a3b02009-09-16 22:47:08 +000010493/// Handle a friend type declaration. This works in tandem with
10494/// ActOnTag.
10495///
10496/// Notes on friend class templates:
10497///
10498/// We generally treat friend class declarations as if they were
10499/// declaring a class. So, for example, the elaborated type specifier
10500/// in a friend declaration is required to obey the restrictions of a
10501/// class-head (i.e. no typedefs in the scope chain), template
10502/// parameters are required to match up with simple template-ids, &c.
10503/// However, unlike when declaring a template specialization, it's
10504/// okay to refer to a template specialization without an empty
10505/// template parameter declaration, e.g.
10506/// friend class A<T>::B<unsigned>;
10507/// We permit this as a special case; if there are any template
10508/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010509/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010510Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010511 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010512 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010513
10514 assert(DS.isFriendSpecified());
10515 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10516
John McCalldd4a3b02009-09-16 22:47:08 +000010517 // Try to convert the decl specifier to a type. This works for
10518 // friend templates because ActOnTag never produces a ClassTemplateDecl
10519 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010520 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010521 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10522 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010523 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010524 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010525
Douglas Gregor6ccab972010-12-16 01:14:37 +000010526 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10527 return 0;
10528
John McCalldd4a3b02009-09-16 22:47:08 +000010529 // This is definitely an error in C++98. It's probably meant to
10530 // be forbidden in C++0x, too, but the specification is just
10531 // poorly written.
10532 //
10533 // The problem is with declarations like the following:
10534 // template <T> friend A<T>::foo;
10535 // where deciding whether a class C is a friend or not now hinges
10536 // on whether there exists an instantiation of A that causes
10537 // 'foo' to equal C. There are restrictions on class-heads
10538 // (which we declare (by fiat) elaborated friend declarations to
10539 // be) that makes this tractable.
10540 //
10541 // FIXME: handle "template <> friend class A<T>;", which
10542 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010543 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010544 Diag(Loc, diag::err_tagless_friend_type_template)
10545 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010546 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010547 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010548
John McCall02cace72009-08-28 07:59:38 +000010549 // C++98 [class.friend]p1: A friend of a class is a function
10550 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010551 // This is fixed in DR77, which just barely didn't make the C++03
10552 // deadline. It's also a very silly restriction that seriously
10553 // affects inner classes and which nobody else seems to implement;
10554 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010555 //
10556 // But note that we could warn about it: it's always useless to
10557 // friend one of your own members (it's not, however, worthless to
10558 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010559
John McCalldd4a3b02009-09-16 22:47:08 +000010560 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010561 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010562 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010563 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010564 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010565 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010566 DS.getFriendSpecLoc());
10567 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010568 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010569
10570 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010571 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010572
John McCalldd4a3b02009-09-16 22:47:08 +000010573 D->setAccess(AS_public);
10574 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010575
John McCalld226f652010-08-21 09:40:31 +000010576 return D;
John McCall02cace72009-08-28 07:59:38 +000010577}
10578
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010579Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010580 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010581 const DeclSpec &DS = D.getDeclSpec();
10582
10583 assert(DS.isFriendSpecified());
10584 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10585
10586 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010587 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010588
10589 // C++ [class.friend]p1
10590 // A friend of a class is a function or class....
10591 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010592 // It *doesn't* see through dependent types, which is correct
10593 // according to [temp.arg.type]p3:
10594 // If a declaration acquires a function type through a
10595 // type dependent on a template-parameter and this causes
10596 // a declaration that does not use the syntactic form of a
10597 // function declarator to have a function type, the program
10598 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010599 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010600 Diag(Loc, diag::err_unexpected_friend);
10601
10602 // It might be worthwhile to try to recover by creating an
10603 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010604 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010605 }
10606
10607 // C++ [namespace.memdef]p3
10608 // - If a friend declaration in a non-local class first declares a
10609 // class or function, the friend class or function is a member
10610 // of the innermost enclosing namespace.
10611 // - The name of the friend is not found by simple name lookup
10612 // until a matching declaration is provided in that namespace
10613 // scope (either before or after the class declaration granting
10614 // friendship).
10615 // - If a friend function is called, its name may be found by the
10616 // name lookup that considers functions from namespaces and
10617 // classes associated with the types of the function arguments.
10618 // - When looking for a prior declaration of a class or a function
10619 // declared as a friend, scopes outside the innermost enclosing
10620 // namespace scope are not considered.
10621
John McCall337ec3d2010-10-12 23:13:28 +000010622 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010623 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10624 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010625 assert(Name);
10626
Douglas Gregor6ccab972010-12-16 01:14:37 +000010627 // Check for unexpanded parameter packs.
10628 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10629 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10630 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10631 return 0;
10632
John McCall67d1a672009-08-06 02:15:43 +000010633 // The context we found the declaration in, or in which we should
10634 // create the declaration.
10635 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010636 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010637 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010638 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010639
John McCall337ec3d2010-10-12 23:13:28 +000010640 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010641
John McCall337ec3d2010-10-12 23:13:28 +000010642 // There are four cases here.
10643 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010644 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010645 // there as appropriate.
10646 // Recover from invalid scope qualifiers as if they just weren't there.
10647 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010648 // C++0x [namespace.memdef]p3:
10649 // If the name in a friend declaration is neither qualified nor
10650 // a template-id and the declaration is a function or an
10651 // elaborated-type-specifier, the lookup to determine whether
10652 // the entity has been previously declared shall not consider
10653 // any scopes outside the innermost enclosing namespace.
10654 // C++0x [class.friend]p11:
10655 // If a friend declaration appears in a local class and the name
10656 // specified is an unqualified name, a prior declaration is
10657 // looked up without considering scopes that are outside the
10658 // innermost enclosing non-class scope. For a friend function
10659 // declaration, if there is no prior declaration, the program is
10660 // ill-formed.
10661 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010662 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010663
John McCall29ae6e52010-10-13 05:45:15 +000010664 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010665 DC = CurContext;
10666 while (true) {
10667 // Skip class contexts. If someone can cite chapter and verse
10668 // for this behavior, that would be nice --- it's what GCC and
10669 // EDG do, and it seems like a reasonable intent, but the spec
10670 // really only says that checks for unqualified existing
10671 // declarations should stop at the nearest enclosing namespace,
10672 // not that they should only consider the nearest enclosing
10673 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010674 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010675 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010676
John McCall68263142009-11-18 22:49:29 +000010677 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010678
10679 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010680 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010681 break;
John McCall29ae6e52010-10-13 05:45:15 +000010682
John McCall8a407372010-10-14 22:22:28 +000010683 if (isTemplateId) {
10684 if (isa<TranslationUnitDecl>(DC)) break;
10685 } else {
10686 if (DC->isFileContext()) break;
10687 }
John McCall67d1a672009-08-06 02:15:43 +000010688 DC = DC->getParent();
10689 }
10690
10691 // C++ [class.friend]p1: A friend of a class is a function or
10692 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010693 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010694 // Most C++ 98 compilers do seem to give an error here, so
10695 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010696 if (!Previous.empty() && DC->Equals(CurContext))
10697 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010698 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010699 diag::warn_cxx98_compat_friend_is_member :
10700 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010701
John McCall380aaa42010-10-13 06:22:15 +000010702 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010703
Douglas Gregor883af832011-10-10 01:11:59 +000010704 // C++ [class.friend]p6:
10705 // A function can be defined in a friend declaration of a class if and
10706 // only if the class is a non-local class (9.8), the function name is
10707 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010708 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010709 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10710 }
10711
John McCall337ec3d2010-10-12 23:13:28 +000010712 // - There's a non-dependent scope specifier, in which case we
10713 // compute it and do a previous lookup there for a function
10714 // or function template.
10715 } else if (!SS.getScopeRep()->isDependent()) {
10716 DC = computeDeclContext(SS);
10717 if (!DC) return 0;
10718
10719 if (RequireCompleteDeclContext(SS, DC)) return 0;
10720
10721 LookupQualifiedName(Previous, DC);
10722
10723 // Ignore things found implicitly in the wrong scope.
10724 // TODO: better diagnostics for this case. Suggesting the right
10725 // qualified scope would be nice...
10726 LookupResult::Filter F = Previous.makeFilter();
10727 while (F.hasNext()) {
10728 NamedDecl *D = F.next();
10729 if (!DC->InEnclosingNamespaceSetOf(
10730 D->getDeclContext()->getRedeclContext()))
10731 F.erase();
10732 }
10733 F.done();
10734
10735 if (Previous.empty()) {
10736 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010737 Diag(Loc, diag::err_qualified_friend_not_found)
10738 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010739 return 0;
10740 }
10741
10742 // C++ [class.friend]p1: A friend of a class is a function or
10743 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010744 if (DC->Equals(CurContext))
10745 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010746 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010747 diag::warn_cxx98_compat_friend_is_member :
10748 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010749
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010750 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010751 // C++ [class.friend]p6:
10752 // A function can be defined in a friend declaration of a class if and
10753 // only if the class is a non-local class (9.8), the function name is
10754 // unqualified, and the function has namespace scope.
10755 SemaDiagnosticBuilder DB
10756 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10757
10758 DB << SS.getScopeRep();
10759 if (DC->isFileContext())
10760 DB << FixItHint::CreateRemoval(SS.getRange());
10761 SS.clear();
10762 }
John McCall337ec3d2010-10-12 23:13:28 +000010763
10764 // - There's a scope specifier that does not match any template
10765 // parameter lists, in which case we use some arbitrary context,
10766 // create a method or method template, and wait for instantiation.
10767 // - There's a scope specifier that does match some template
10768 // parameter lists, which we don't handle right now.
10769 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010770 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010771 // C++ [class.friend]p6:
10772 // A function can be defined in a friend declaration of a class if and
10773 // only if the class is a non-local class (9.8), the function name is
10774 // unqualified, and the function has namespace scope.
10775 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10776 << SS.getScopeRep();
10777 }
10778
John McCall337ec3d2010-10-12 23:13:28 +000010779 DC = CurContext;
10780 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010781 }
Douglas Gregor883af832011-10-10 01:11:59 +000010782
John McCall29ae6e52010-10-13 05:45:15 +000010783 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010784 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010785 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10786 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10787 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010788 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010789 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10790 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010791 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010792 }
John McCall67d1a672009-08-06 02:15:43 +000010793 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010794
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010795 // FIXME: This is an egregious hack to cope with cases where the scope stack
10796 // does not contain the declaration context, i.e., in an out-of-line
10797 // definition of a class.
10798 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10799 if (!DCScope) {
10800 FakeDCScope.setEntity(DC);
10801 DCScope = &FakeDCScope;
10802 }
10803
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010804 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010805 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010806 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010807 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010808
Douglas Gregor182ddf02009-09-28 00:08:27 +000010809 assert(ND->getDeclContext() == DC);
10810 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010811
John McCallab88d972009-08-31 22:39:49 +000010812 // Add the function declaration to the appropriate lookup tables,
10813 // adjusting the redeclarations list as necessary. We don't
10814 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010815 //
John McCallab88d972009-08-31 22:39:49 +000010816 // Also update the scope-based lookup if the target context's
10817 // lookup context is in lexical scope.
10818 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010819 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010820 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010821 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010822 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010823 }
John McCall02cace72009-08-28 07:59:38 +000010824
10825 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010826 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010827 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010828 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010829 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010830
John McCall1f2e1a92012-08-10 03:15:35 +000010831 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010832 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010833 } else {
10834 if (DC->isRecord()) CheckFriendAccess(ND);
10835
John McCall6102ca12010-10-16 06:59:13 +000010836 FunctionDecl *FD;
10837 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10838 FD = FTD->getTemplatedDecl();
10839 else
10840 FD = cast<FunctionDecl>(ND);
10841
10842 // Mark templated-scope function declarations as unsupported.
10843 if (FD->getNumTemplateParameterLists())
10844 FrD->setUnsupportedFriend(true);
10845 }
John McCall337ec3d2010-10-12 23:13:28 +000010846
John McCalld226f652010-08-21 09:40:31 +000010847 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010848}
10849
John McCalld226f652010-08-21 09:40:31 +000010850void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10851 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010852
Sebastian Redl50de12f2009-03-24 22:27:57 +000010853 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10854 if (!Fn) {
10855 Diag(DelLoc, diag::err_deleted_non_function);
10856 return;
10857 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010858 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010859 // Don't consider the implicit declaration we generate for explicit
10860 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010861 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10862 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010863 Diag(DelLoc, diag::err_deleted_decl_not_first);
10864 Diag(Prev->getLocation(), diag::note_previous_declaration);
10865 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010866 // If the declaration wasn't the first, we delete the function anyway for
10867 // recovery.
10868 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010869 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010870}
Sebastian Redl13e88542009-04-27 21:33:24 +000010871
Sean Hunte4246a62011-05-12 06:15:49 +000010872void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10873 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10874
10875 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010876 if (MD->getParent()->isDependentType()) {
10877 MD->setDefaulted();
10878 MD->setExplicitlyDefaulted();
10879 return;
10880 }
10881
Sean Hunte4246a62011-05-12 06:15:49 +000010882 CXXSpecialMember Member = getSpecialMember(MD);
10883 if (Member == CXXInvalid) {
10884 Diag(DefaultLoc, diag::err_default_special_members);
10885 return;
10886 }
10887
10888 MD->setDefaulted();
10889 MD->setExplicitlyDefaulted();
10890
Sean Huntcd10dec2011-05-23 23:14:04 +000010891 // If this definition appears within the record, do the checking when
10892 // the record is complete.
10893 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010894 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010895 // Find the uninstantiated declaration that actually had the '= default'
10896 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010897 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010898
10899 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010900 return;
10901
Richard Smithb9d0b762012-07-27 04:22:15 +000010902 CheckExplicitlyDefaultedSpecialMember(MD);
10903
Richard Smith1d28caf2012-12-11 01:14:52 +000010904 // The exception specification is needed because we are defining the
10905 // function.
10906 ResolveExceptionSpec(DefaultLoc,
10907 MD->getType()->castAs<FunctionProtoType>());
10908
Sean Hunte4246a62011-05-12 06:15:49 +000010909 switch (Member) {
10910 case CXXDefaultConstructor: {
10911 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010912 if (!CD->isInvalidDecl())
10913 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10914 break;
10915 }
10916
10917 case CXXCopyConstructor: {
10918 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010919 if (!CD->isInvalidDecl())
10920 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010921 break;
10922 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010923
Sean Hunt2b188082011-05-14 05:23:28 +000010924 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010925 if (!MD->isInvalidDecl())
10926 DefineImplicitCopyAssignment(DefaultLoc, MD);
10927 break;
10928 }
10929
Sean Huntcb45a0f2011-05-12 22:46:25 +000010930 case CXXDestructor: {
10931 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010932 if (!DD->isInvalidDecl())
10933 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010934 break;
10935 }
10936
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010937 case CXXMoveConstructor: {
10938 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010939 if (!CD->isInvalidDecl())
10940 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010941 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010942 }
Sean Hunt82713172011-05-25 23:16:36 +000010943
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010944 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010945 if (!MD->isInvalidDecl())
10946 DefineImplicitMoveAssignment(DefaultLoc, MD);
10947 break;
10948 }
10949
10950 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010951 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010952 }
10953 } else {
10954 Diag(DefaultLoc, diag::err_default_special_members);
10955 }
10956}
10957
Sebastian Redl13e88542009-04-27 21:33:24 +000010958static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010959 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010960 Stmt *SubStmt = *CI;
10961 if (!SubStmt)
10962 continue;
10963 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010964 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010965 diag::err_return_in_constructor_handler);
10966 if (!isa<Expr>(SubStmt))
10967 SearchForReturnInStmt(Self, SubStmt);
10968 }
10969}
10970
10971void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10972 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10973 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10974 SearchForReturnInStmt(*this, Handler);
10975 }
10976}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010977
Aaron Ballmanfff32482012-12-09 17:45:41 +000010978bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
10979 const CXXMethodDecl *Old) {
10980 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
10981 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
10982
10983 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
10984
10985 // If the calling conventions match, everything is fine
10986 if (NewCC == OldCC)
10987 return false;
10988
10989 // If either of the calling conventions are set to "default", we need to pick
10990 // something more sensible based on the target. This supports code where the
10991 // one method explicitly sets thiscall, and another has no explicit calling
10992 // convention.
10993 CallingConv Default =
10994 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
10995 if (NewCC == CC_Default)
10996 NewCC = Default;
10997 if (OldCC == CC_Default)
10998 OldCC = Default;
10999
11000 // If the calling conventions still don't match, then report the error
11001 if (NewCC != OldCC) {
11002 Diag(New->getLocation(),
11003 diag::err_conflicting_overriding_cc_attributes)
11004 << New->getDeclName() << New->getType() << Old->getType();
11005 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11006 return true;
11007 }
11008
11009 return false;
11010}
11011
Mike Stump1eb44332009-09-09 15:08:12 +000011012bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011013 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011014 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11015 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011016
Chandler Carruth73857792010-02-15 11:53:20 +000011017 if (Context.hasSameType(NewTy, OldTy) ||
11018 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011019 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011020
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011021 // Check if the return types are covariant
11022 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011023
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011024 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011025 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11026 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011027 NewClassTy = NewPT->getPointeeType();
11028 OldClassTy = OldPT->getPointeeType();
11029 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011030 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11031 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11032 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11033 NewClassTy = NewRT->getPointeeType();
11034 OldClassTy = OldRT->getPointeeType();
11035 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011036 }
11037 }
Mike Stump1eb44332009-09-09 15:08:12 +000011038
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011039 // The return types aren't either both pointers or references to a class type.
11040 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011041 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011042 diag::err_different_return_type_for_overriding_virtual_function)
11043 << New->getDeclName() << NewTy << OldTy;
11044 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011045
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011046 return true;
11047 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011048
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011049 // C++ [class.virtual]p6:
11050 // If the return type of D::f differs from the return type of B::f, the
11051 // class type in the return type of D::f shall be complete at the point of
11052 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011053 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11054 if (!RT->isBeingDefined() &&
11055 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011056 diag::err_covariant_return_incomplete,
11057 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011058 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011059 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011060
Douglas Gregora4923eb2009-11-16 21:35:15 +000011061 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011062 // Check if the new class derives from the old class.
11063 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11064 Diag(New->getLocation(),
11065 diag::err_covariant_return_not_derived)
11066 << New->getDeclName() << NewTy << OldTy;
11067 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11068 return true;
11069 }
Mike Stump1eb44332009-09-09 15:08:12 +000011070
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011071 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011072 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011073 diag::err_covariant_return_inaccessible_base,
11074 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11075 // FIXME: Should this point to the return type?
11076 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011077 // FIXME: this note won't trigger for delayed access control
11078 // diagnostics, and it's impossible to get an undelayed error
11079 // here from access control during the original parse because
11080 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011081 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11082 return true;
11083 }
11084 }
Mike Stump1eb44332009-09-09 15:08:12 +000011085
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011086 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011087 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011088 Diag(New->getLocation(),
11089 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011090 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011091 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11092 return true;
11093 };
Mike Stump1eb44332009-09-09 15:08:12 +000011094
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011095
11096 // The new class type must have the same or less qualifiers as the old type.
11097 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11098 Diag(New->getLocation(),
11099 diag::err_covariant_return_type_class_type_more_qualified)
11100 << New->getDeclName() << NewTy << OldTy;
11101 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11102 return true;
11103 };
Mike Stump1eb44332009-09-09 15:08:12 +000011104
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011105 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011106}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011107
Douglas Gregor4ba31362009-12-01 17:24:26 +000011108/// \brief Mark the given method pure.
11109///
11110/// \param Method the method to be marked pure.
11111///
11112/// \param InitRange the source range that covers the "0" initializer.
11113bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011114 SourceLocation EndLoc = InitRange.getEnd();
11115 if (EndLoc.isValid())
11116 Method->setRangeEnd(EndLoc);
11117
Douglas Gregor4ba31362009-12-01 17:24:26 +000011118 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11119 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011120 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011121 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011122
11123 if (!Method->isInvalidDecl())
11124 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11125 << Method->getDeclName() << InitRange;
11126 return true;
11127}
11128
Douglas Gregor552e2992012-02-21 02:22:07 +000011129/// \brief Determine whether the given declaration is a static data member.
11130static bool isStaticDataMember(Decl *D) {
11131 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11132 if (!Var)
11133 return false;
11134
11135 return Var->isStaticDataMember();
11136}
John McCall731ad842009-12-19 09:28:58 +000011137/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11138/// an initializer for the out-of-line declaration 'Dcl'. The scope
11139/// is a fresh scope pushed for just this purpose.
11140///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011141/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11142/// static data member of class X, names should be looked up in the scope of
11143/// class X.
John McCalld226f652010-08-21 09:40:31 +000011144void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011145 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011146 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011147
John McCall731ad842009-12-19 09:28:58 +000011148 // We should only get called for declarations with scope specifiers, like:
11149 // int foo::bar;
11150 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011151 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011152
11153 // If we are parsing the initializer for a static data member, push a
11154 // new expression evaluation context that is associated with this static
11155 // data member.
11156 if (isStaticDataMember(D))
11157 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011158}
11159
11160/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011161/// initializer for the out-of-line declaration 'D'.
11162void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011163 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011164 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011165
Douglas Gregor552e2992012-02-21 02:22:07 +000011166 if (isStaticDataMember(D))
11167 PopExpressionEvaluationContext();
11168
John McCall731ad842009-12-19 09:28:58 +000011169 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011170 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011171}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011172
11173/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11174/// C++ if/switch/while/for statement.
11175/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011176DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011177 // C++ 6.4p2:
11178 // The declarator shall not specify a function or an array.
11179 // The type-specifier-seq shall not contain typedef and shall not declare a
11180 // new class or enumeration.
11181 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11182 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011183
11184 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011185 if (!Dcl)
11186 return true;
11187
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011188 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11189 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011190 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011191 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011192 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011193
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011194 return Dcl;
11195}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011196
Douglas Gregordfe65432011-07-28 19:11:31 +000011197void Sema::LoadExternalVTableUses() {
11198 if (!ExternalSource)
11199 return;
11200
11201 SmallVector<ExternalVTableUse, 4> VTables;
11202 ExternalSource->ReadUsedVTables(VTables);
11203 SmallVector<VTableUse, 4> NewUses;
11204 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11205 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11206 = VTablesUsed.find(VTables[I].Record);
11207 // Even if a definition wasn't required before, it may be required now.
11208 if (Pos != VTablesUsed.end()) {
11209 if (!Pos->second && VTables[I].DefinitionRequired)
11210 Pos->second = true;
11211 continue;
11212 }
11213
11214 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11215 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11216 }
11217
11218 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11219}
11220
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011221void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11222 bool DefinitionRequired) {
11223 // Ignore any vtable uses in unevaluated operands or for classes that do
11224 // not have a vtable.
11225 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11226 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011227 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011228 return;
11229
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011230 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011231 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011232 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11233 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11234 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11235 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011236 // If we already had an entry, check to see if we are promoting this vtable
11237 // to required a definition. If so, we need to reappend to the VTableUses
11238 // list, since we may have already processed the first entry.
11239 if (DefinitionRequired && !Pos.first->second) {
11240 Pos.first->second = true;
11241 } else {
11242 // Otherwise, we can early exit.
11243 return;
11244 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011245 }
11246
11247 // Local classes need to have their virtual members marked
11248 // immediately. For all other classes, we mark their virtual members
11249 // at the end of the translation unit.
11250 if (Class->isLocalClass())
11251 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011252 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011253 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011254}
11255
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011256bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011257 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011258 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011259 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011260
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011261 // Note: The VTableUses vector could grow as a result of marking
11262 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011263 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011264 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011265 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011266 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011267 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011268 if (!Class)
11269 continue;
11270
11271 SourceLocation Loc = VTableUses[I].second;
11272
Richard Smithb9d0b762012-07-27 04:22:15 +000011273 bool DefineVTable = true;
11274
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011275 // If this class has a key function, but that key function is
11276 // defined in another translation unit, we don't need to emit the
11277 // vtable even though we're using it.
11278 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011279 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011280 switch (KeyFunction->getTemplateSpecializationKind()) {
11281 case TSK_Undeclared:
11282 case TSK_ExplicitSpecialization:
11283 case TSK_ExplicitInstantiationDeclaration:
11284 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011285 DefineVTable = false;
11286 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011287
11288 case TSK_ExplicitInstantiationDefinition:
11289 case TSK_ImplicitInstantiation:
11290 // We will be instantiating the key function.
11291 break;
11292 }
11293 } else if (!KeyFunction) {
11294 // If we have a class with no key function that is the subject
11295 // of an explicit instantiation declaration, suppress the
11296 // vtable; it will live with the explicit instantiation
11297 // definition.
11298 bool IsExplicitInstantiationDeclaration
11299 = Class->getTemplateSpecializationKind()
11300 == TSK_ExplicitInstantiationDeclaration;
11301 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11302 REnd = Class->redecls_end();
11303 R != REnd; ++R) {
11304 TemplateSpecializationKind TSK
11305 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11306 if (TSK == TSK_ExplicitInstantiationDeclaration)
11307 IsExplicitInstantiationDeclaration = true;
11308 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11309 IsExplicitInstantiationDeclaration = false;
11310 break;
11311 }
11312 }
11313
11314 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011315 DefineVTable = false;
11316 }
11317
11318 // The exception specifications for all virtual members may be needed even
11319 // if we are not providing an authoritative form of the vtable in this TU.
11320 // We may choose to emit it available_externally anyway.
11321 if (!DefineVTable) {
11322 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11323 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011324 }
11325
11326 // Mark all of the virtual members of this class as referenced, so
11327 // that we can build a vtable. Then, tell the AST consumer that a
11328 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011329 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011330 MarkVirtualMembersReferenced(Loc, Class);
11331 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11332 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11333
11334 // Optionally warn if we're emitting a weak vtable.
11335 if (Class->getLinkage() == ExternalLinkage &&
11336 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011337 const FunctionDecl *KeyFunctionDef = 0;
11338 if (!KeyFunction ||
11339 (KeyFunction->hasBody(KeyFunctionDef) &&
11340 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011341 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11342 TSK_ExplicitInstantiationDefinition
11343 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11344 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011345 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011346 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011347 VTableUses.clear();
11348
Douglas Gregor78844032011-04-22 22:25:37 +000011349 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011350}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011351
Richard Smithb9d0b762012-07-27 04:22:15 +000011352void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11353 const CXXRecordDecl *RD) {
11354 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11355 E = RD->method_end(); I != E; ++I)
11356 if ((*I)->isVirtual() && !(*I)->isPure())
11357 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11358}
11359
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011360void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11361 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011362 // Mark all functions which will appear in RD's vtable as used.
11363 CXXFinalOverriderMap FinalOverriders;
11364 RD->getFinalOverriders(FinalOverriders);
11365 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11366 E = FinalOverriders.end();
11367 I != E; ++I) {
11368 for (OverridingMethods::const_iterator OI = I->second.begin(),
11369 OE = I->second.end();
11370 OI != OE; ++OI) {
11371 assert(OI->second.size() > 0 && "no final overrider");
11372 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011373
Richard Smithff817f72012-07-07 06:59:51 +000011374 // C++ [basic.def.odr]p2:
11375 // [...] A virtual member function is used if it is not pure. [...]
11376 if (!Overrider->isPure())
11377 MarkFunctionReferenced(Loc, Overrider);
11378 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011379 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011380
11381 // Only classes that have virtual bases need a VTT.
11382 if (RD->getNumVBases() == 0)
11383 return;
11384
11385 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11386 e = RD->bases_end(); i != e; ++i) {
11387 const CXXRecordDecl *Base =
11388 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011389 if (Base->getNumVBases() == 0)
11390 continue;
11391 MarkVirtualMembersReferenced(Loc, Base);
11392 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011393}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011394
11395/// SetIvarInitializers - This routine builds initialization ASTs for the
11396/// Objective-C implementation whose ivars need be initialized.
11397void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011398 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011399 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011400 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011401 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011402 CollectIvarsToConstructOrDestruct(OID, ivars);
11403 if (ivars.empty())
11404 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011405 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011406 for (unsigned i = 0; i < ivars.size(); i++) {
11407 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011408 if (Field->isInvalidDecl())
11409 continue;
11410
Sean Huntcbb67482011-01-08 20:30:50 +000011411 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011412 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11413 InitializationKind InitKind =
11414 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11415
11416 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011417 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011418 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011419 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011420 // Note, MemberInit could actually come back empty if no initialization
11421 // is required (e.g., because it would call a trivial default constructor)
11422 if (!MemberInit.get() || MemberInit.isInvalid())
11423 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011424
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011425 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011426 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11427 SourceLocation(),
11428 MemberInit.takeAs<Expr>(),
11429 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011430 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011431
11432 // Be sure that the destructor is accessible and is marked as referenced.
11433 if (const RecordType *RecordTy
11434 = Context.getBaseElementType(Field->getType())
11435 ->getAs<RecordType>()) {
11436 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011437 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011438 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011439 CheckDestructorAccess(Field->getLocation(), Destructor,
11440 PDiag(diag::err_access_dtor_ivar)
11441 << Context.getBaseElementType(Field->getType()));
11442 }
11443 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011444 }
11445 ObjCImplementation->setIvarInitializers(Context,
11446 AllToInit.data(), AllToInit.size());
11447 }
11448}
Sean Huntfe57eef2011-05-04 05:57:24 +000011449
Sean Huntebcbe1d2011-05-04 23:29:54 +000011450static
11451void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11452 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11453 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11454 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11455 Sema &S) {
11456 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11457 CE = Current.end();
11458 if (Ctor->isInvalidDecl())
11459 return;
11460
Richard Smitha8eaf002012-08-23 06:16:52 +000011461 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11462
11463 // Target may not be determinable yet, for instance if this is a dependent
11464 // call in an uninstantiated template.
11465 if (Target) {
11466 const FunctionDecl *FNTarget = 0;
11467 (void)Target->hasBody(FNTarget);
11468 Target = const_cast<CXXConstructorDecl*>(
11469 cast_or_null<CXXConstructorDecl>(FNTarget));
11470 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011471
11472 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11473 // Avoid dereferencing a null pointer here.
11474 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11475
11476 if (!Current.insert(Canonical))
11477 return;
11478
11479 // We know that beyond here, we aren't chaining into a cycle.
11480 if (!Target || !Target->isDelegatingConstructor() ||
11481 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11482 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11483 Valid.insert(*CI);
11484 Current.clear();
11485 // We've hit a cycle.
11486 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11487 Current.count(TCanonical)) {
11488 // If we haven't diagnosed this cycle yet, do so now.
11489 if (!Invalid.count(TCanonical)) {
11490 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011491 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011492 << Ctor;
11493
Richard Smitha8eaf002012-08-23 06:16:52 +000011494 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011495 if (TCanonical != Canonical)
11496 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11497
11498 CXXConstructorDecl *C = Target;
11499 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011500 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011501 (void)C->getTargetConstructor()->hasBody(FNTarget);
11502 assert(FNTarget && "Ctor cycle through bodiless function");
11503
Richard Smitha8eaf002012-08-23 06:16:52 +000011504 C = const_cast<CXXConstructorDecl*>(
11505 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011506 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11507 }
11508 }
11509
11510 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11511 Invalid.insert(*CI);
11512 Current.clear();
11513 } else {
11514 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11515 }
11516}
11517
11518
Sean Huntfe57eef2011-05-04 05:57:24 +000011519void Sema::CheckDelegatingCtorCycles() {
11520 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11521
Sean Huntebcbe1d2011-05-04 23:29:54 +000011522 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11523 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011524
Douglas Gregor0129b562011-07-27 21:57:17 +000011525 for (DelegatingCtorDeclsType::iterator
11526 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011527 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011528 I != E; ++I)
11529 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011530
11531 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11532 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011533}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011534
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011535namespace {
11536 /// \brief AST visitor that finds references to the 'this' expression.
11537 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11538 Sema &S;
11539
11540 public:
11541 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11542
11543 bool VisitCXXThisExpr(CXXThisExpr *E) {
11544 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11545 << E->isImplicit();
11546 return false;
11547 }
11548 };
11549}
11550
11551bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11552 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11553 if (!TSInfo)
11554 return false;
11555
11556 TypeLoc TL = TSInfo->getTypeLoc();
11557 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11558 if (!ProtoTL)
11559 return false;
11560
11561 // C++11 [expr.prim.general]p3:
11562 // [The expression this] shall not appear before the optional
11563 // cv-qualifier-seq and it shall not appear within the declaration of a
11564 // static member function (although its type and value category are defined
11565 // within a static member function as they are within a non-static member
11566 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011567 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011568 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11569 FindCXXThisExpr Finder(*this);
11570
11571 // If the return type came after the cv-qualifier-seq, check it now.
11572 if (Proto->hasTrailingReturn() &&
11573 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11574 return true;
11575
11576 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011577 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11578 return true;
11579
11580 return checkThisInStaticMemberFunctionAttributes(Method);
11581}
11582
11583bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11584 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11585 if (!TSInfo)
11586 return false;
11587
11588 TypeLoc TL = TSInfo->getTypeLoc();
11589 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11590 if (!ProtoTL)
11591 return false;
11592
11593 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11594 FindCXXThisExpr Finder(*this);
11595
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011596 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011597 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011598 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011599 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011600 case EST_DynamicNone:
11601 case EST_MSAny:
11602 case EST_None:
11603 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011604
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011605 case EST_ComputedNoexcept:
11606 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11607 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011608
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011609 case EST_Dynamic:
11610 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011611 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011612 E != EEnd; ++E) {
11613 if (!Finder.TraverseType(*E))
11614 return true;
11615 }
11616 break;
11617 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011618
11619 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011620}
11621
11622bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11623 FindCXXThisExpr Finder(*this);
11624
11625 // Check attributes.
11626 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11627 A != AEnd; ++A) {
11628 // FIXME: This should be emitted by tblgen.
11629 Expr *Arg = 0;
11630 ArrayRef<Expr *> Args;
11631 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11632 Arg = G->getArg();
11633 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11634 Arg = G->getArg();
11635 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11636 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11637 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11638 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11639 else if (ExclusiveLockFunctionAttr *ELF
11640 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11641 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11642 else if (SharedLockFunctionAttr *SLF
11643 = dyn_cast<SharedLockFunctionAttr>(*A))
11644 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11645 else if (ExclusiveTrylockFunctionAttr *ETLF
11646 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11647 Arg = ETLF->getSuccessValue();
11648 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11649 } else if (SharedTrylockFunctionAttr *STLF
11650 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11651 Arg = STLF->getSuccessValue();
11652 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11653 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11654 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11655 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11656 Arg = LR->getArg();
11657 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11658 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11659 else if (ExclusiveLocksRequiredAttr *ELR
11660 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11661 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11662 else if (SharedLocksRequiredAttr *SLR
11663 = dyn_cast<SharedLocksRequiredAttr>(*A))
11664 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11665
11666 if (Arg && !Finder.TraverseStmt(Arg))
11667 return true;
11668
11669 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11670 if (!Finder.TraverseStmt(Args[I]))
11671 return true;
11672 }
11673 }
11674
11675 return false;
11676}
11677
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011678void
11679Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11680 ArrayRef<ParsedType> DynamicExceptions,
11681 ArrayRef<SourceRange> DynamicExceptionRanges,
11682 Expr *NoexceptExpr,
11683 llvm::SmallVectorImpl<QualType> &Exceptions,
11684 FunctionProtoType::ExtProtoInfo &EPI) {
11685 Exceptions.clear();
11686 EPI.ExceptionSpecType = EST;
11687 if (EST == EST_Dynamic) {
11688 Exceptions.reserve(DynamicExceptions.size());
11689 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11690 // FIXME: Preserve type source info.
11691 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11692
11693 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11694 collectUnexpandedParameterPacks(ET, Unexpanded);
11695 if (!Unexpanded.empty()) {
11696 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11697 UPPC_ExceptionType,
11698 Unexpanded);
11699 continue;
11700 }
11701
11702 // Check that the type is valid for an exception spec, and
11703 // drop it if not.
11704 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11705 Exceptions.push_back(ET);
11706 }
11707 EPI.NumExceptions = Exceptions.size();
11708 EPI.Exceptions = Exceptions.data();
11709 return;
11710 }
11711
11712 if (EST == EST_ComputedNoexcept) {
11713 // If an error occurred, there's no expression here.
11714 if (NoexceptExpr) {
11715 assert((NoexceptExpr->isTypeDependent() ||
11716 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11717 Context.BoolTy) &&
11718 "Parser should have made sure that the expression is boolean");
11719 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11720 EPI.ExceptionSpecType = EST_BasicNoexcept;
11721 return;
11722 }
11723
11724 if (!NoexceptExpr->isValueDependent())
11725 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011726 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011727 /*AllowFold*/ false).take();
11728 EPI.NoexceptExpr = NoexceptExpr;
11729 }
11730 return;
11731 }
11732}
11733
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011734/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11735Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11736 // Implicitly declared functions (e.g. copy constructors) are
11737 // __host__ __device__
11738 if (D->isImplicit())
11739 return CFT_HostDevice;
11740
11741 if (D->hasAttr<CUDAGlobalAttr>())
11742 return CFT_Global;
11743
11744 if (D->hasAttr<CUDADeviceAttr>()) {
11745 if (D->hasAttr<CUDAHostAttr>())
11746 return CFT_HostDevice;
11747 else
11748 return CFT_Device;
11749 }
11750
11751 return CFT_Host;
11752}
11753
11754bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11755 CUDAFunctionTarget CalleeTarget) {
11756 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11757 // Callable from the device only."
11758 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11759 return true;
11760
11761 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11762 // Callable from the host only."
11763 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11764 // Callable from the host only."
11765 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11766 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11767 return true;
11768
11769 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11770 return true;
11771
11772 return false;
11773}