blob: 704ff834b469d8c7994ffd43f623fb0226ab3ee4 [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"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Eli Friedman7badd242012-02-09 20:13:14 +000019#include "clang/Sema/ScopeInfo.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000021#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000025#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000027#include "clang/AST/RecordLayout.h"
28#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000029#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000030#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000033#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000034#include "clang/Lex/Preprocessor.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000035#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000036#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000037#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000038#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000039
40using namespace clang;
41
Chris Lattner8123a952008-04-10 02:22:51 +000042//===----------------------------------------------------------------------===//
43// CheckDefaultArgumentVisitor
44//===----------------------------------------------------------------------===//
45
Chris Lattner9e979552008-04-12 23:52:44 +000046namespace {
47 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
48 /// the default argument of a parameter to determine whether it
49 /// contains any ill-formed subexpressions. For example, this will
50 /// diagnose the use of local variables or parameters within the
51 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000052 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000053 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000054 Expr *DefaultArg;
55 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000056
Chris Lattner9e979552008-04-12 23:52:44 +000057 public:
Mike Stump1eb44332009-09-09 15:08:12 +000058 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000059 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000060
Chris Lattner9e979552008-04-12 23:52:44 +000061 bool VisitExpr(Expr *Node);
62 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000063 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000064 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000065 };
Chris Lattner8123a952008-04-10 02:22:51 +000066
Chris Lattner9e979552008-04-12 23:52:44 +000067 /// VisitExpr - Visit all of the children of this expression.
68 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
69 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000070 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000071 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000072 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000073 }
74
Chris Lattner9e979552008-04-12 23:52:44 +000075 /// VisitDeclRefExpr - Visit a reference to a declaration, to
76 /// determine whether this declaration can be used in the default
77 /// argument expression.
78 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000079 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000080 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
81 // C++ [dcl.fct.default]p9
82 // Default arguments are evaluated each time the function is
83 // called. The order of evaluation of function arguments is
84 // unspecified. Consequently, parameters of a function shall not
85 // be used in default argument expressions, even if they are not
86 // evaluated. Parameters of a function declared before a default
87 // argument expression are in scope and can hide namespace and
88 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000089 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000090 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000091 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000092 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000093 // C++ [dcl.fct.default]p7
94 // Local variables shall not be used in default argument
95 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000096 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +000097 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000098 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000099 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000100 }
Chris Lattner8123a952008-04-10 02:22:51 +0000101
Douglas Gregor3996f232008-11-04 13:41:56 +0000102 return false;
103 }
Chris Lattner9e979552008-04-12 23:52:44 +0000104
Douglas Gregor796da182008-11-04 14:32:21 +0000105 /// VisitCXXThisExpr - Visit a C++ "this" expression.
106 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
107 // C++ [dcl.fct.default]p8:
108 // The keyword this shall not be used in a default argument of a
109 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000110 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000111 diag::err_param_default_argument_references_this)
112 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000113 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000114
115 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
116 // C++11 [expr.lambda.prim]p13:
117 // A lambda-expression appearing in a default argument shall not
118 // implicitly or explicitly capture any entity.
119 if (Lambda->capture_begin() == Lambda->capture_end())
120 return false;
121
122 return S->Diag(Lambda->getLocStart(),
123 diag::err_lambda_capture_default_arg);
124 }
Chris Lattner8123a952008-04-10 02:22:51 +0000125}
126
Sean Hunt001cad92011-05-10 00:49:42 +0000127void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000128 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith7a614d82011-06-11 17:19:42 +0000129 // If we have an MSAny or unknown spec already, don't bother.
130 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000131 return;
132
133 const FunctionProtoType *Proto
134 = Method->getType()->getAs<FunctionProtoType>();
135
136 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
137
138 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000139 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000140 ClearExceptions();
141 ComputedEST = EST;
142 return;
143 }
144
Richard Smith7a614d82011-06-11 17:19:42 +0000145 // FIXME: If the call to this decl is using any of its default arguments, we
146 // need to search them for potentially-throwing calls.
147
Sean Hunt001cad92011-05-10 00:49:42 +0000148 // If this function has a basic noexcept, it doesn't affect the outcome.
149 if (EST == EST_BasicNoexcept)
150 return;
151
152 // If we have a throw-all spec at this point, ignore the function.
153 if (ComputedEST == EST_None)
154 return;
155
156 // If we're still at noexcept(true) and there's a nothrow() callee,
157 // change to that specification.
158 if (EST == EST_DynamicNone) {
159 if (ComputedEST == EST_BasicNoexcept)
160 ComputedEST = EST_DynamicNone;
161 return;
162 }
163
164 // Check out noexcept specs.
165 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000166 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000167 assert(NR != FunctionProtoType::NR_NoNoexcept &&
168 "Must have noexcept result for EST_ComputedNoexcept.");
169 assert(NR != FunctionProtoType::NR_Dependent &&
170 "Should not generate implicit declarations for dependent cases, "
171 "and don't know how to handle them anyway.");
172
173 // noexcept(false) -> no spec on the new function
174 if (NR == FunctionProtoType::NR_Throw) {
175 ClearExceptions();
176 ComputedEST = EST_None;
177 }
178 // noexcept(true) won't change anything either.
179 return;
180 }
181
182 assert(EST == EST_Dynamic && "EST case not considered earlier.");
183 assert(ComputedEST != EST_None &&
184 "Shouldn't collect exceptions when throw-all is guaranteed.");
185 ComputedEST = EST_Dynamic;
186 // Record the exceptions in this function's exception specification.
187 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
188 EEnd = Proto->exception_end();
189 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000190 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000191 Exceptions.push_back(*E);
192}
193
Richard Smith7a614d82011-06-11 17:19:42 +0000194void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
195 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
196 return;
197
198 // FIXME:
199 //
200 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000201 // [An] implicit exception-specification specifies the type-id T if and
202 // only if T is allowed by the exception-specification of a function directly
203 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000204 // function it directly invokes allows all exceptions, and f shall allow no
205 // exceptions if every function it directly invokes allows no exceptions.
206 //
207 // Note in particular that if an implicit exception-specification is generated
208 // for a function containing a throw-expression, that specification can still
209 // be noexcept(true).
210 //
211 // Note also that 'directly invoked' is not defined in the standard, and there
212 // is no indication that we should only consider potentially-evaluated calls.
213 //
214 // Ultimately we should implement the intent of the standard: the exception
215 // specification should be the set of exceptions which can be thrown by the
216 // implicit definition. For now, we assume that any non-nothrow expression can
217 // throw any exception.
218
219 if (E->CanThrow(*Context))
220 ComputedEST = EST_None;
221}
222
Anders Carlssoned961f92009-08-25 02:29:20 +0000223bool
John McCall9ae2f072010-08-23 23:25:46 +0000224Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000225 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000226 if (RequireCompleteType(Param->getLocation(), Param->getType(),
227 diag::err_typecheck_decl_incomplete_type)) {
228 Param->setInvalidDecl();
229 return true;
230 }
231
Anders Carlssoned961f92009-08-25 02:29:20 +0000232 // C++ [dcl.fct.default]p5
233 // A default argument expression is implicitly converted (clause
234 // 4) to the parameter type. The default argument expression has
235 // the same semantic constraints as the initializer expression in
236 // a declaration of a variable of the parameter type, using the
237 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000238 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
239 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000240 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
241 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000242 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000243 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000244 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000245 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000246 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000247 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000248
John McCallb4eb64d2010-10-08 02:01:28 +0000249 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000250 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Anders Carlssoned961f92009-08-25 02:29:20 +0000252 // Okay: add the default argument to the parameter
253 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000255 // We have already instantiated this parameter; provide each of the
256 // instantiations with the uninstantiated default argument.
257 UnparsedDefaultArgInstantiationsMap::iterator InstPos
258 = UnparsedDefaultArgInstantiations.find(Param);
259 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
260 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
261 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
262
263 // We're done tracking this parameter's instantiations.
264 UnparsedDefaultArgInstantiations.erase(InstPos);
265 }
266
Anders Carlsson9351c172009-08-25 03:18:48 +0000267 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000268}
269
Chris Lattner8123a952008-04-10 02:22:51 +0000270/// ActOnParamDefaultArgument - Check whether the default argument
271/// provided for a function parameter is well-formed. If so, attach it
272/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000273void
John McCalld226f652010-08-21 09:40:31 +0000274Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000275 Expr *DefaultArg) {
276 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000277 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000278
John McCalld226f652010-08-21 09:40:31 +0000279 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000280 UnparsedDefaultArgLocs.erase(Param);
281
Chris Lattner3d1cee32008-04-08 05:04:30 +0000282 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000283 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000284 Diag(EqualLoc, diag::err_param_default_argument)
285 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000286 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000287 return;
288 }
289
Douglas Gregor6f526752010-12-16 08:48:57 +0000290 // Check for unexpanded parameter packs.
291 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
292 Param->setInvalidDecl();
293 return;
294 }
295
Anders Carlsson66e30672009-08-25 01:02:06 +0000296 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000297 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
298 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000299 Param->setInvalidDecl();
300 return;
301 }
Mike Stump1eb44332009-09-09 15:08:12 +0000302
John McCall9ae2f072010-08-23 23:25:46 +0000303 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000304}
305
Douglas Gregor61366e92008-12-24 00:01:03 +0000306/// ActOnParamUnparsedDefaultArgument - We've seen a default
307/// argument for a function parameter, but we can't parse it yet
308/// because we're inside a class definition. Note that this default
309/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000310void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000311 SourceLocation EqualLoc,
312 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000313 if (!param)
314 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
John McCalld226f652010-08-21 09:40:31 +0000316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000317 if (Param)
318 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Anders Carlsson5e300d12009-06-12 16:51:40 +0000320 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000321}
322
Douglas Gregor72b505b2008-12-16 21:30:33 +0000323/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
324/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000325void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000326 if (!param)
327 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000328
John McCalld226f652010-08-21 09:40:31 +0000329 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Anders Carlsson5e300d12009-06-12 16:51:40 +0000331 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Anders Carlsson5e300d12009-06-12 16:51:40 +0000333 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000334}
335
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000336/// CheckExtraCXXDefaultArguments - Check for any extra default
337/// arguments in the declarator, which is not a function declaration
338/// or definition and therefore is not permitted to have default
339/// arguments. This routine should be invoked for every declarator
340/// that is not a function declaration or definition.
341void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
342 // C++ [dcl.fct.default]p3
343 // A default argument expression shall be specified only in the
344 // parameter-declaration-clause of a function declaration or in a
345 // template-parameter (14.1). It shall not be specified for a
346 // parameter pack. If it is specified in a
347 // parameter-declaration-clause, it shall not occur within a
348 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000349 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000350 DeclaratorChunk &chunk = D.getTypeObject(i);
351 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000352 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
353 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000354 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000355 if (Param->hasUnparsedDefaultArg()) {
356 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000357 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
358 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
359 delete Toks;
360 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000361 } else if (Param->getDefaultArg()) {
362 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
363 << Param->getDefaultArg()->getSourceRange();
364 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000365 }
366 }
367 }
368 }
369}
370
Chris Lattner3d1cee32008-04-08 05:04:30 +0000371// MergeCXXFunctionDecl - Merge two declarations of the same C++
372// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000373// type. Subroutine of MergeFunctionDecl. Returns true if there was an
374// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000375bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
376 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000377 bool Invalid = false;
378
Chris Lattner3d1cee32008-04-08 05:04:30 +0000379 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000380 // For non-template functions, default arguments can be added in
381 // later declarations of a function in the same
382 // scope. Declarations in different scopes have completely
383 // distinct sets of default arguments. That is, declarations in
384 // inner scopes do not acquire default arguments from
385 // declarations in outer scopes, and vice versa. In a given
386 // function declaration, all parameters subsequent to a
387 // parameter with a default argument shall have default
388 // arguments supplied in this or previous declarations. A
389 // default argument shall not be redefined by a later
390 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000391 //
392 // C++ [dcl.fct.default]p6:
393 // Except for member functions of class templates, the default arguments
394 // in a member function definition that appears outside of the class
395 // definition are added to the set of default arguments provided by the
396 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
398 ParmVarDecl *OldParam = Old->getParamDecl(p);
399 ParmVarDecl *NewParam = New->getParamDecl(p);
400
James Molloy9cda03f2012-03-13 08:55:35 +0000401 bool OldParamHasDfl = OldParam->hasDefaultArg();
402 bool NewParamHasDfl = NewParam->hasDefaultArg();
403
404 NamedDecl *ND = Old;
405 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
406 // Ignore default parameters of old decl if they are not in
407 // the same scope.
408 OldParamHasDfl = false;
409
410 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000411
Francois Pichet8d051e02011-04-10 03:03:52 +0000412 unsigned DiagDefaultParamID =
413 diag::err_param_default_argument_redefinition;
414
415 // MSVC accepts that default parameters be redefined for member functions
416 // of template class. The new default parameter's value is ignored.
417 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000418 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000419 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
420 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000421 // Merge the old default argument into the new parameter.
422 NewParam->setHasInheritedDefaultArg();
423 if (OldParam->hasUninstantiatedDefaultArg())
424 NewParam->setUninstantiatedDefaultArg(
425 OldParam->getUninstantiatedDefaultArg());
426 else
427 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000428 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000429 Invalid = false;
430 }
431 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000432
Francois Pichet8cf90492011-04-10 04:58:30 +0000433 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
434 // hint here. Alternatively, we could walk the type-source information
435 // for NewParam to find the last source location in the type... but it
436 // isn't worth the effort right now. This is the kind of test case that
437 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000438 // int f(int);
439 // void g(int (*fp)(int) = f);
440 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000441 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000442 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000443
444 // Look for the function declaration where the default argument was
445 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000446 for (FunctionDecl *Older = Old->getPreviousDecl();
447 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000448 if (!Older->getParamDecl(p)->hasDefaultArg())
449 break;
450
451 OldParam = Older->getParamDecl(p);
452 }
453
454 Diag(OldParam->getLocation(), diag::note_previous_definition)
455 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000456 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000457 // Merge the old default argument into the new parameter.
458 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000459 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000460 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000461 if (OldParam->hasUninstantiatedDefaultArg())
462 NewParam->setUninstantiatedDefaultArg(
463 OldParam->getUninstantiatedDefaultArg());
464 else
John McCall3d6c1782010-05-04 01:53:42 +0000465 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000466 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000467 if (New->getDescribedFunctionTemplate()) {
468 // Paragraph 4, quoted above, only applies to non-template functions.
469 Diag(NewParam->getLocation(),
470 diag::err_param_default_argument_template_redecl)
471 << NewParam->getDefaultArgRange();
472 Diag(Old->getLocation(), diag::note_template_prev_declaration)
473 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000474 } else if (New->getTemplateSpecializationKind()
475 != TSK_ImplicitInstantiation &&
476 New->getTemplateSpecializationKind() != TSK_Undeclared) {
477 // C++ [temp.expr.spec]p21:
478 // Default function arguments shall not be specified in a declaration
479 // or a definition for one of the following explicit specializations:
480 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000481 // - the explicit specialization of a member function template;
482 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000483 // template where the class template specialization to which the
484 // member function specialization belongs is implicitly
485 // instantiated.
486 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
487 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
488 << New->getDeclName()
489 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000490 } else if (New->getDeclContext()->isDependentContext()) {
491 // C++ [dcl.fct.default]p6 (DR217):
492 // Default arguments for a member function of a class template shall
493 // be specified on the initial declaration of the member function
494 // within the class template.
495 //
496 // Reading the tea leaves a bit in DR217 and its reference to DR205
497 // leads me to the conclusion that one cannot add default function
498 // arguments for an out-of-line definition of a member function of a
499 // dependent type.
500 int WhichKind = 2;
501 if (CXXRecordDecl *Record
502 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
503 if (Record->getDescribedClassTemplate())
504 WhichKind = 0;
505 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
506 WhichKind = 1;
507 else
508 WhichKind = 2;
509 }
510
511 Diag(NewParam->getLocation(),
512 diag::err_param_default_argument_member_template_redecl)
513 << WhichKind
514 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000515 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
516 CXXSpecialMember NewSM = getSpecialMember(Ctor),
517 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
518 if (NewSM != OldSM) {
519 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
520 << NewParam->getDefaultArgRange() << NewSM;
521 Diag(Old->getLocation(), diag::note_previous_declaration_special)
522 << OldSM;
523 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000524 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000525 }
526 }
527
Richard Smithff234882012-02-20 23:28:05 +0000528 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000529 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000530 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000531 if (New->isConstexpr() != Old->isConstexpr()) {
532 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
533 << New << New->isConstexpr();
534 Diag(Old->getLocation(), diag::note_previous_declaration);
535 Invalid = true;
536 }
537
Douglas Gregore13ad832010-02-12 07:32:17 +0000538 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000539 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000540
Douglas Gregorcda9c672009-02-16 17:45:42 +0000541 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000542}
543
Sebastian Redl60618fa2011-03-12 11:50:43 +0000544/// \brief Merge the exception specifications of two variable declarations.
545///
546/// This is called when there's a redeclaration of a VarDecl. The function
547/// checks if the redeclaration might have an exception specification and
548/// validates compatibility and merges the specs if necessary.
549void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
550 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000551 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000552 return;
553
554 assert(Context.hasSameType(New->getType(), Old->getType()) &&
555 "Should only be called if types are otherwise the same.");
556
557 QualType NewType = New->getType();
558 QualType OldType = Old->getType();
559
560 // We're only interested in pointers and references to functions, as well
561 // as pointers to member functions.
562 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
563 NewType = R->getPointeeType();
564 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
565 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
566 NewType = P->getPointeeType();
567 OldType = OldType->getAs<PointerType>()->getPointeeType();
568 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
569 NewType = M->getPointeeType();
570 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
571 }
572
573 if (!NewType->isFunctionProtoType())
574 return;
575
576 // There's lots of special cases for functions. For function pointers, system
577 // libraries are hopefully not as broken so that we don't need these
578 // workarounds.
579 if (CheckEquivalentExceptionSpec(
580 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
581 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
582 New->setInvalidDecl();
583 }
584}
585
Chris Lattner3d1cee32008-04-08 05:04:30 +0000586/// CheckCXXDefaultArguments - Verify that the default arguments for a
587/// function declaration are well-formed according to C++
588/// [dcl.fct.default].
589void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
590 unsigned NumParams = FD->getNumParams();
591 unsigned p;
592
Douglas Gregorc6889e72012-02-14 22:28:59 +0000593 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
594 isa<CXXMethodDecl>(FD) &&
595 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
596
Chris Lattner3d1cee32008-04-08 05:04:30 +0000597 // Find first parameter with a default argument
598 for (p = 0; p < NumParams; ++p) {
599 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000600 if (Param->hasDefaultArg()) {
601 // C++11 [expr.prim.lambda]p5:
602 // [...] Default arguments (8.3.6) shall not be specified in the
603 // parameter-declaration-clause of a lambda-declarator.
604 //
605 // FIXME: Core issue 974 strikes this sentence, we only provide an
606 // extension warning.
607 if (IsLambda)
608 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
609 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000610 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000611 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000612 }
613
614 // C++ [dcl.fct.default]p4:
615 // In a given function declaration, all parameters
616 // subsequent to a parameter with a default argument shall
617 // have default arguments supplied in this or previous
618 // declarations. A default argument shall not be redefined
619 // by a later declaration (not even to the same value).
620 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000621 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000622 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000623 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000624 if (Param->isInvalidDecl())
625 /* We already complained about this parameter. */;
626 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000627 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000628 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000629 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000630 else
Mike Stump1eb44332009-09-09 15:08:12 +0000631 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000632 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Chris Lattner3d1cee32008-04-08 05:04:30 +0000634 LastMissingDefaultArg = p;
635 }
636 }
637
638 if (LastMissingDefaultArg > 0) {
639 // Some default arguments were missing. Clear out all of the
640 // default arguments up to (and including) the last missing
641 // default argument, so that we leave the function parameters
642 // in a semantically valid state.
643 for (p = 0; p <= LastMissingDefaultArg; ++p) {
644 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000645 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000646 Param->setDefaultArg(0);
647 }
648 }
649 }
650}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000651
Richard Smith9f569cc2011-10-01 02:31:28 +0000652// CheckConstexprParameterTypes - Check whether a function's parameter types
653// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000654// diagnostic and return false.
655static bool CheckConstexprParameterTypes(Sema &SemaRef,
656 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000657 unsigned ArgIndex = 0;
658 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
659 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
660 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
661 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
662 SourceLocation ParamLoc = PD->getLocation();
663 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000664 SemaRef.RequireLiteralType(ParamLoc, *i,
Richard Smith9f569cc2011-10-01 02:31:28 +0000665 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
666 << ArgIndex+1 << PD->getSourceRange()
Richard Smith86c3ae42012-02-13 03:54:03 +0000667 << isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000668 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000669 }
670 return true;
671}
672
673// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
Richard Smith86c3ae42012-02-13 03:54:03 +0000674// the requirements of a constexpr function definition or a constexpr
675// constructor definition. If so, return true. If not, produce appropriate
676// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000677//
Richard Smith86c3ae42012-02-13 03:54:03 +0000678// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
679bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000680 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
681 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000682 // C++11 [dcl.constexpr]p4:
683 // The definition of a constexpr constructor shall satisfy the following
684 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000685 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000686 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000687 if (RD->getNumVBases()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000688 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
689 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
690 << RD->getNumVBases();
691 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
692 E = RD->vbases_end(); I != E; ++I)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000693 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000694 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000695 return false;
696 }
Richard Smith35340502012-01-13 04:54:00 +0000697 }
698
699 if (!isa<CXXConstructorDecl>(NewFD)) {
700 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000701 // The definition of a constexpr function shall satisfy the following
702 // constraints:
703 // - it shall not be virtual;
704 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
705 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000706 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000707
Richard Smith86c3ae42012-02-13 03:54:03 +0000708 // If it's not obvious why this function is virtual, find an overridden
709 // function which uses the 'virtual' keyword.
710 const CXXMethodDecl *WrittenVirtual = Method;
711 while (!WrittenVirtual->isVirtualAsWritten())
712 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
713 if (WrittenVirtual != Method)
714 Diag(WrittenVirtual->getLocation(),
715 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000716 return false;
717 }
718
719 // - its return type shall be a literal type;
720 QualType RT = NewFD->getResultType();
721 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000722 RequireLiteralType(NewFD->getLocation(), RT,
723 PDiag(diag::err_constexpr_non_literal_return)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000724 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000725 }
726
Richard Smith35340502012-01-13 04:54:00 +0000727 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000728 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000729 return false;
730
Richard Smith9f569cc2011-10-01 02:31:28 +0000731 return true;
732}
733
734/// Check the given declaration statement is legal within a constexpr function
735/// body. C++0x [dcl.constexpr]p3,p4.
736///
737/// \return true if the body is OK, false if we have diagnosed a problem.
738static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
739 DeclStmt *DS) {
740 // C++0x [dcl.constexpr]p3 and p4:
741 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
742 // contain only
743 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
744 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
745 switch ((*DclIt)->getKind()) {
746 case Decl::StaticAssert:
747 case Decl::Using:
748 case Decl::UsingShadow:
749 case Decl::UsingDirective:
750 case Decl::UnresolvedUsingTypename:
751 // - static_assert-declarations
752 // - using-declarations,
753 // - using-directives,
754 continue;
755
756 case Decl::Typedef:
757 case Decl::TypeAlias: {
758 // - typedef declarations and alias-declarations that do not define
759 // classes or enumerations,
760 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
761 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
762 // Don't allow variably-modified types in constexpr functions.
763 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
764 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
765 << TL.getSourceRange() << TL.getType()
766 << isa<CXXConstructorDecl>(Dcl);
767 return false;
768 }
769 continue;
770 }
771
772 case Decl::Enum:
773 case Decl::CXXRecord:
774 // As an extension, we allow the declaration (but not the definition) of
775 // classes and enumerations in all declarations, not just in typedef and
776 // alias declarations.
777 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
778 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
779 << isa<CXXConstructorDecl>(Dcl);
780 return false;
781 }
782 continue;
783
784 case Decl::Var:
785 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
786 << isa<CXXConstructorDecl>(Dcl);
787 return false;
788
789 default:
790 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
791 << isa<CXXConstructorDecl>(Dcl);
792 return false;
793 }
794 }
795
796 return true;
797}
798
799/// Check that the given field is initialized within a constexpr constructor.
800///
801/// \param Dcl The constexpr constructor being checked.
802/// \param Field The field being checked. This may be a member of an anonymous
803/// struct or union nested within the class being checked.
804/// \param Inits All declarations, including anonymous struct/union members and
805/// indirect members, for which any initialization was provided.
806/// \param Diagnosed Set to true if an error is produced.
807static void CheckConstexprCtorInitializer(Sema &SemaRef,
808 const FunctionDecl *Dcl,
809 FieldDecl *Field,
810 llvm::SmallSet<Decl*, 16> &Inits,
811 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000812 if (Field->isUnnamedBitfield())
813 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000814
815 if (Field->isAnonymousStructOrUnion() &&
816 Field->getType()->getAsCXXRecordDecl()->isEmpty())
817 return;
818
Richard Smith9f569cc2011-10-01 02:31:28 +0000819 if (!Inits.count(Field)) {
820 if (!Diagnosed) {
821 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
822 Diagnosed = true;
823 }
824 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
825 } else if (Field->isAnonymousStructOrUnion()) {
826 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
827 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
828 I != E; ++I)
829 // If an anonymous union contains an anonymous struct of which any member
830 // is initialized, all members must be initialized.
831 if (!RD->isUnion() || Inits.count(*I))
832 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
833 }
834}
835
836/// Check the body for the given constexpr function declaration only contains
837/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
838///
839/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000840bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000841 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000842 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000843 // The definition of a constexpr function shall satisfy the following
844 // constraints: [...]
845 // - its function-body shall be = delete, = default, or a
846 // compound-statement
847 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000848 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000849 // In the definition of a constexpr constructor, [...]
850 // - its function-body shall not be a function-try-block;
851 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
852 << isa<CXXConstructorDecl>(Dcl);
853 return false;
854 }
855
856 // - its function-body shall be [...] a compound-statement that contains only
857 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
858
859 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
860 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
861 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
862 switch ((*BodyIt)->getStmtClass()) {
863 case Stmt::NullStmtClass:
864 // - null statements,
865 continue;
866
867 case Stmt::DeclStmtClass:
868 // - static_assert-declarations
869 // - using-declarations,
870 // - using-directives,
871 // - typedef declarations and alias-declarations that do not define
872 // classes or enumerations,
873 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
874 return false;
875 continue;
876
877 case Stmt::ReturnStmtClass:
878 // - and exactly one return statement;
879 if (isa<CXXConstructorDecl>(Dcl))
880 break;
881
882 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000883 continue;
884
885 default:
886 break;
887 }
888
889 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
890 << isa<CXXConstructorDecl>(Dcl);
891 return false;
892 }
893
894 if (const CXXConstructorDecl *Constructor
895 = dyn_cast<CXXConstructorDecl>(Dcl)) {
896 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000897 // DR1359:
898 // - every non-variant non-static data member and base class sub-object
899 // shall be initialized;
900 // - if the class is a non-empty union, or for each non-empty anonymous
901 // union member of a non-union class, exactly one non-static data member
902 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000903 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000904 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000905 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
906 return false;
907 }
Richard Smith6e433752011-10-10 16:38:04 +0000908 } else if (!Constructor->isDependentContext() &&
909 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000910 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
911
912 // Skip detailed checking if we have enough initializers, and we would
913 // allow at most one initializer per member.
914 bool AnyAnonStructUnionMembers = false;
915 unsigned Fields = 0;
916 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
917 E = RD->field_end(); I != E; ++I, ++Fields) {
918 if ((*I)->isAnonymousStructOrUnion()) {
919 AnyAnonStructUnionMembers = true;
920 break;
921 }
922 }
923 if (AnyAnonStructUnionMembers ||
924 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
925 // Check initialization of non-static data members. Base classes are
926 // always initialized so do not need to be checked. Dependent bases
927 // might not have initializers in the member initializer list.
928 llvm::SmallSet<Decl*, 16> Inits;
929 for (CXXConstructorDecl::init_const_iterator
930 I = Constructor->init_begin(), E = Constructor->init_end();
931 I != E; ++I) {
932 if (FieldDecl *FD = (*I)->getMember())
933 Inits.insert(FD);
934 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
935 Inits.insert(ID->chain_begin(), ID->chain_end());
936 }
937
938 bool Diagnosed = false;
939 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
940 E = RD->field_end(); I != E; ++I)
941 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
942 if (Diagnosed)
943 return false;
944 }
945 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000946 } else {
947 if (ReturnStmts.empty()) {
948 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
949 return false;
950 }
951 if (ReturnStmts.size() > 1) {
952 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
953 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
954 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
955 return false;
956 }
957 }
958
Richard Smith5ba73e12012-02-04 00:33:54 +0000959 // C++11 [dcl.constexpr]p5:
960 // if no function argument values exist such that the function invocation
961 // substitution would produce a constant expression, the program is
962 // ill-formed; no diagnostic required.
963 // C++11 [dcl.constexpr]p3:
964 // - every constructor call and implicit conversion used in initializing the
965 // return value shall be one of those allowed in a constant expression.
966 // C++11 [dcl.constexpr]p4:
967 // - every constructor involved in initializing non-static data members and
968 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000969 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000970 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000971 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
972 << isa<CXXConstructorDecl>(Dcl);
973 for (size_t I = 0, N = Diags.size(); I != N; ++I)
974 Diag(Diags[I].first, Diags[I].second);
975 return false;
976 }
977
Richard Smith9f569cc2011-10-01 02:31:28 +0000978 return true;
979}
980
Douglas Gregorb48fe382008-10-31 09:07:45 +0000981/// isCurrentClassName - Determine whether the identifier II is the
982/// name of the class type currently being defined. In the case of
983/// nested classes, this will only return true if II is the name of
984/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000985bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
986 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000987 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000988
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000989 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000990 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000991 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000992 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
993 } else
994 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
995
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000996 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000997 return &II == CurDecl->getIdentifier();
998 else
999 return false;
1000}
1001
Mike Stump1eb44332009-09-09 15:08:12 +00001002/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001003///
1004/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1005/// and returns NULL otherwise.
1006CXXBaseSpecifier *
1007Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1008 SourceRange SpecifierRange,
1009 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001010 TypeSourceInfo *TInfo,
1011 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001012 QualType BaseType = TInfo->getType();
1013
Douglas Gregor2943aed2009-03-03 04:44:36 +00001014 // C++ [class.union]p1:
1015 // A union shall not have base classes.
1016 if (Class->isUnion()) {
1017 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1018 << SpecifierRange;
1019 return 0;
1020 }
1021
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001022 if (EllipsisLoc.isValid() &&
1023 !TInfo->getType()->containsUnexpandedParameterPack()) {
1024 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1025 << TInfo->getTypeLoc().getSourceRange();
1026 EllipsisLoc = SourceLocation();
1027 }
1028
Douglas Gregor2943aed2009-03-03 04:44:36 +00001029 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001030 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001031 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001032 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001033
1034 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001035
1036 // Base specifiers must be record types.
1037 if (!BaseType->isRecordType()) {
1038 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1039 return 0;
1040 }
1041
1042 // C++ [class.union]p1:
1043 // A union shall not be used as a base class.
1044 if (BaseType->isUnionType()) {
1045 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1046 return 0;
1047 }
1048
1049 // C++ [class.derived]p2:
1050 // The class-name in a base-specifier shall not be an incompletely
1051 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001052 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001053 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001054 << SpecifierRange)) {
1055 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001056 return 0;
John McCall572fc622010-08-17 07:23:57 +00001057 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001058
Eli Friedman1d954f62009-08-15 21:55:26 +00001059 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001060 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001061 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001062 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001063 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001064 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1065 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001066
Anders Carlsson1d209272011-03-25 14:55:14 +00001067 // C++ [class]p3:
1068 // If a class is marked final and it appears as a base-type-specifier in
1069 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001070 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001071 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1072 << CXXBaseDecl->getDeclName();
1073 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1074 << CXXBaseDecl->getDeclName();
1075 return 0;
1076 }
1077
John McCall572fc622010-08-17 07:23:57 +00001078 if (BaseDecl->isInvalidDecl())
1079 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001080
1081 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001082 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001083 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001084 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001085}
1086
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001087/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1088/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001089/// example:
1090/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001091/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001092BaseResult
John McCalld226f652010-08-21 09:40:31 +00001093Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001094 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001095 ParsedType basetype, SourceLocation BaseLoc,
1096 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001097 if (!classdecl)
1098 return true;
1099
Douglas Gregor40808ce2009-03-09 23:48:35 +00001100 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001101 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001102 if (!Class)
1103 return true;
1104
Nick Lewycky56062202010-07-26 16:56:01 +00001105 TypeSourceInfo *TInfo = 0;
1106 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001107
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001108 if (EllipsisLoc.isInvalid() &&
1109 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001110 UPPC_BaseType))
1111 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001112
Douglas Gregor2943aed2009-03-03 04:44:36 +00001113 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001114 Virtual, Access, TInfo,
1115 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001116 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001117
Douglas Gregor2943aed2009-03-03 04:44:36 +00001118 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001119}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001120
Douglas Gregor2943aed2009-03-03 04:44:36 +00001121/// \brief Performs the actual work of attaching the given base class
1122/// specifiers to a C++ class.
1123bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1124 unsigned NumBases) {
1125 if (NumBases == 0)
1126 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001127
1128 // Used to keep track of which base types we have already seen, so
1129 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001130 // that the key is always the unqualified canonical type of the base
1131 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001132 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1133
1134 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001135 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001136 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001137 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001138 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001139 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001140 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001141
1142 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1143 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001144 // C++ [class.mi]p3:
1145 // A class shall not be specified as a direct base class of a
1146 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001147 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001148 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001149 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001150 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001151
1152 // Delete the duplicate base class specifier; we're going to
1153 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001154 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001155
1156 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001157 } else {
1158 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001159 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001160 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001161 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001162 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1163 if (RD->hasAttr<WeakAttr>())
1164 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001165 }
1166 }
1167
1168 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001169 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001170
1171 // Delete the remaining (good) base class specifiers, since their
1172 // data has been copied into the CXXRecordDecl.
1173 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001174 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001175
1176 return Invalid;
1177}
1178
1179/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1180/// class, after checking whether there are any duplicate base
1181/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001182void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001183 unsigned NumBases) {
1184 if (!ClassDecl || !Bases || !NumBases)
1185 return;
1186
1187 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001188 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001189 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001190}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001191
John McCall3cb0ebd2010-03-10 03:28:59 +00001192static CXXRecordDecl *GetClassForType(QualType T) {
1193 if (const RecordType *RT = T->getAs<RecordType>())
1194 return cast<CXXRecordDecl>(RT->getDecl());
1195 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1196 return ICT->getDecl();
1197 else
1198 return 0;
1199}
1200
Douglas Gregora8f32e02009-10-06 17:59:45 +00001201/// \brief Determine whether the type \p Derived is a C++ class that is
1202/// derived from the type \p Base.
1203bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001204 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001205 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001206
1207 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1208 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001209 return false;
1210
John McCall3cb0ebd2010-03-10 03:28:59 +00001211 CXXRecordDecl *BaseRD = GetClassForType(Base);
1212 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001213 return false;
1214
John McCall86ff3082010-02-04 22:26:26 +00001215 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1216 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001217}
1218
1219/// \brief Determine whether the type \p Derived is a C++ class that is
1220/// derived from the type \p Base.
1221bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001222 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001223 return false;
1224
John McCall3cb0ebd2010-03-10 03:28:59 +00001225 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1226 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001227 return false;
1228
John McCall3cb0ebd2010-03-10 03:28:59 +00001229 CXXRecordDecl *BaseRD = GetClassForType(Base);
1230 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001231 return false;
1232
Douglas Gregora8f32e02009-10-06 17:59:45 +00001233 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1234}
1235
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001236void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001237 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001238 assert(BasePathArray.empty() && "Base path array must be empty!");
1239 assert(Paths.isRecordingPaths() && "Must record paths!");
1240
1241 const CXXBasePath &Path = Paths.front();
1242
1243 // We first go backward and check if we have a virtual base.
1244 // FIXME: It would be better if CXXBasePath had the base specifier for
1245 // the nearest virtual base.
1246 unsigned Start = 0;
1247 for (unsigned I = Path.size(); I != 0; --I) {
1248 if (Path[I - 1].Base->isVirtual()) {
1249 Start = I - 1;
1250 break;
1251 }
1252 }
1253
1254 // Now add all bases.
1255 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001256 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001257}
1258
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001259/// \brief Determine whether the given base path includes a virtual
1260/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001261bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1262 for (CXXCastPath::const_iterator B = BasePath.begin(),
1263 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001264 B != BEnd; ++B)
1265 if ((*B)->isVirtual())
1266 return true;
1267
1268 return false;
1269}
1270
Douglas Gregora8f32e02009-10-06 17:59:45 +00001271/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1272/// conversion (where Derived and Base are class types) is
1273/// well-formed, meaning that the conversion is unambiguous (and
1274/// that all of the base classes are accessible). Returns true
1275/// and emits a diagnostic if the code is ill-formed, returns false
1276/// otherwise. Loc is the location where this routine should point to
1277/// if there is an error, and Range is the source range to highlight
1278/// if there is an error.
1279bool
1280Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001281 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001282 unsigned AmbigiousBaseConvID,
1283 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001284 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001285 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001286 // First, determine whether the path from Derived to Base is
1287 // ambiguous. This is slightly more expensive than checking whether
1288 // the Derived to Base conversion exists, because here we need to
1289 // explore multiple paths to determine if there is an ambiguity.
1290 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1291 /*DetectVirtual=*/false);
1292 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1293 assert(DerivationOkay &&
1294 "Can only be used with a derived-to-base conversion");
1295 (void)DerivationOkay;
1296
1297 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001298 if (InaccessibleBaseID) {
1299 // Check that the base class can be accessed.
1300 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1301 InaccessibleBaseID)) {
1302 case AR_inaccessible:
1303 return true;
1304 case AR_accessible:
1305 case AR_dependent:
1306 case AR_delayed:
1307 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001308 }
John McCall6b2accb2010-02-10 09:31:12 +00001309 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001310
1311 // Build a base path if necessary.
1312 if (BasePath)
1313 BuildBasePathArray(Paths, *BasePath);
1314 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001315 }
1316
1317 // We know that the derived-to-base conversion is ambiguous, and
1318 // we're going to produce a diagnostic. Perform the derived-to-base
1319 // search just one more time to compute all of the possible paths so
1320 // that we can print them out. This is more expensive than any of
1321 // the previous derived-to-base checks we've done, but at this point
1322 // performance isn't as much of an issue.
1323 Paths.clear();
1324 Paths.setRecordingPaths(true);
1325 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1326 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1327 (void)StillOkay;
1328
1329 // Build up a textual representation of the ambiguous paths, e.g.,
1330 // D -> B -> A, that will be used to illustrate the ambiguous
1331 // conversions in the diagnostic. We only print one of the paths
1332 // to each base class subobject.
1333 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1334
1335 Diag(Loc, AmbigiousBaseConvID)
1336 << Derived << Base << PathDisplayStr << Range << Name;
1337 return true;
1338}
1339
1340bool
1341Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001342 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001343 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001344 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001345 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001346 IgnoreAccess ? 0
1347 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001348 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001349 Loc, Range, DeclarationName(),
1350 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001351}
1352
1353
1354/// @brief Builds a string representing ambiguous paths from a
1355/// specific derived class to different subobjects of the same base
1356/// class.
1357///
1358/// This function builds a string that can be used in error messages
1359/// to show the different paths that one can take through the
1360/// inheritance hierarchy to go from the derived class to different
1361/// subobjects of a base class. The result looks something like this:
1362/// @code
1363/// struct D -> struct B -> struct A
1364/// struct D -> struct C -> struct A
1365/// @endcode
1366std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1367 std::string PathDisplayStr;
1368 std::set<unsigned> DisplayedPaths;
1369 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1370 Path != Paths.end(); ++Path) {
1371 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1372 // We haven't displayed a path to this particular base
1373 // class subobject yet.
1374 PathDisplayStr += "\n ";
1375 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1376 for (CXXBasePath::const_iterator Element = Path->begin();
1377 Element != Path->end(); ++Element)
1378 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1379 }
1380 }
1381
1382 return PathDisplayStr;
1383}
1384
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001385//===----------------------------------------------------------------------===//
1386// C++ class member Handling
1387//===----------------------------------------------------------------------===//
1388
Abramo Bagnara6206d532010-06-05 05:09:32 +00001389/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001390bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1391 SourceLocation ASLoc,
1392 SourceLocation ColonLoc,
1393 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001394 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001395 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001396 ASLoc, ColonLoc);
1397 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001398 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001399}
1400
Anders Carlsson9e682d92011-01-20 05:57:14 +00001401/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001402void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001403 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001404 if (!MD || !MD->isVirtual())
1405 return;
1406
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001407 if (MD->isDependentContext())
1408 return;
1409
Anders Carlsson9e682d92011-01-20 05:57:14 +00001410 // C++0x [class.virtual]p3:
1411 // If a virtual function is marked with the virt-specifier override and does
1412 // not override a member function of a base class,
1413 // the program is ill-formed.
1414 bool HasOverriddenMethods =
1415 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001416 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001417 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001418 diag::err_function_marked_override_not_overriding)
1419 << MD->getDeclName();
1420 return;
1421 }
1422}
1423
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001424/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1425/// function overrides a virtual member function marked 'final', according to
1426/// C++0x [class.virtual]p3.
1427bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1428 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001429 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001430 return false;
1431
1432 Diag(New->getLocation(), diag::err_final_function_overridden)
1433 << New->getDeclName();
1434 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1435 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001436}
1437
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001438/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1439/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001440/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1441/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1442/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001443Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001444Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001445 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001446 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001447 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001448 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001449 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1450 DeclarationName Name = NameInfo.getName();
1451 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001452
1453 // For anonymous bitfields, the location should point to the type.
1454 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001455 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001456
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001457 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001458
John McCall4bde1e12010-06-04 08:34:12 +00001459 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001460 assert(!DS.isFriendSpecified());
1461
Richard Smith1ab0d902011-06-25 02:28:38 +00001462 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001463
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001464 // C++ 9.2p6: A member shall not be declared to have automatic storage
1465 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001466 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1467 // data members and cannot be applied to names declared const or static,
1468 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001469 switch (DS.getStorageClassSpec()) {
1470 case DeclSpec::SCS_unspecified:
1471 case DeclSpec::SCS_typedef:
1472 case DeclSpec::SCS_static:
1473 // FALL THROUGH.
1474 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001475 case DeclSpec::SCS_mutable:
1476 if (isFunc) {
1477 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001478 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001479 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001480 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Sebastian Redla11f42f2008-11-17 23:24:37 +00001482 // FIXME: It would be nicer if the keyword was ignored only for this
1483 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001484 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001485 }
1486 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001487 default:
1488 if (DS.getStorageClassSpecLoc().isValid())
1489 Diag(DS.getStorageClassSpecLoc(),
1490 diag::err_storageclass_invalid_for_member);
1491 else
1492 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1493 D.getMutableDeclSpec().ClearStorageClassSpecs();
1494 }
1495
Sebastian Redl669d5d72008-11-14 23:42:31 +00001496 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1497 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001498 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001499
1500 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001501 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001502 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001503
1504 // Data members must have identifiers for names.
1505 if (Name.getNameKind() != DeclarationName::Identifier) {
1506 Diag(Loc, diag::err_bad_variable_name)
1507 << Name;
1508 return 0;
1509 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001510
Douglas Gregorf2503652011-09-21 14:40:46 +00001511 IdentifierInfo *II = Name.getAsIdentifierInfo();
1512
1513 // Member field could not be with "template" keyword.
1514 // So TemplateParameterLists should be empty in this case.
1515 if (TemplateParameterLists.size()) {
1516 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1517 if (TemplateParams->size()) {
1518 // There is no such thing as a member field template.
1519 Diag(D.getIdentifierLoc(), diag::err_template_member)
1520 << II
1521 << SourceRange(TemplateParams->getTemplateLoc(),
1522 TemplateParams->getRAngleLoc());
1523 } else {
1524 // There is an extraneous 'template<>' for this member.
1525 Diag(TemplateParams->getTemplateLoc(),
1526 diag::err_template_member_noparams)
1527 << II
1528 << SourceRange(TemplateParams->getTemplateLoc(),
1529 TemplateParams->getRAngleLoc());
1530 }
1531 return 0;
1532 }
1533
Douglas Gregor922fff22010-10-13 22:19:53 +00001534 if (SS.isSet() && !SS.isInvalid()) {
1535 // The user provided a superfluous scope specifier inside a class
1536 // definition:
1537 //
1538 // class X {
1539 // int X::member;
1540 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001541 if (DeclContext *DC = computeDeclContext(SS, false))
1542 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001543 else
1544 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1545 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001546
Douglas Gregor922fff22010-10-13 22:19:53 +00001547 SS.clear();
1548 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001549
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001550 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001551 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001552 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001553 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001554 assert(!HasDeferredInit);
1555
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001556 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001557 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001558 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001559 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001560
1561 // Non-instance-fields can't have a bitfield.
1562 if (BitWidth) {
1563 if (Member->isInvalidDecl()) {
1564 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001565 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001566 // C++ 9.6p3: A bit-field shall not be a static member.
1567 // "static member 'A' cannot be a bit-field"
1568 Diag(Loc, diag::err_static_not_bitfield)
1569 << Name << BitWidth->getSourceRange();
1570 } else if (isa<TypedefDecl>(Member)) {
1571 // "typedef member 'x' cannot be a bit-field"
1572 Diag(Loc, diag::err_typedef_not_bitfield)
1573 << Name << BitWidth->getSourceRange();
1574 } else {
1575 // A function typedef ("typedef int f(); f a;").
1576 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1577 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001578 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001579 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001580 }
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Chris Lattner8b963ef2009-03-05 23:01:03 +00001582 BitWidth = 0;
1583 Member->setInvalidDecl();
1584 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001585
1586 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Douglas Gregor37b372b2009-08-20 22:52:58 +00001588 // If we have declared a member function template, set the access of the
1589 // templated declaration as well.
1590 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1591 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001592 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001593
Anders Carlssonaae5af22011-01-20 04:34:22 +00001594 if (VS.isOverrideSpecified()) {
1595 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1596 if (!MD || !MD->isVirtual()) {
1597 Diag(Member->getLocStart(),
1598 diag::override_keyword_only_allowed_on_virtual_member_functions)
1599 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001600 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001601 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001602 }
1603 if (VS.isFinalSpecified()) {
1604 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1605 if (!MD || !MD->isVirtual()) {
1606 Diag(Member->getLocStart(),
1607 diag::override_keyword_only_allowed_on_virtual_member_functions)
1608 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001609 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001610 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001611 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001612
Douglas Gregorf5251602011-03-08 17:10:18 +00001613 if (VS.getLastLocation().isValid()) {
1614 // Update the end location of a method that has a virt-specifiers.
1615 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1616 MD->setRangeEnd(VS.getLastLocation());
1617 }
1618
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001619 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001620
Douglas Gregor10bd3682008-11-17 22:58:34 +00001621 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001622
John McCallb25b2952011-02-15 07:12:36 +00001623 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001624 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001625 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001626}
1627
Richard Smith7a614d82011-06-11 17:19:42 +00001628/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001629/// in-class initializer for a non-static C++ class member, and after
1630/// instantiating an in-class initializer in a class template. Such actions
1631/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001632void
1633Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1634 Expr *InitExpr) {
1635 FieldDecl *FD = cast<FieldDecl>(D);
1636
1637 if (!InitExpr) {
1638 FD->setInvalidDecl();
1639 FD->removeInClassInitializer();
1640 return;
1641 }
1642
Peter Collingbournefef21892011-10-23 18:59:44 +00001643 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1644 FD->setInvalidDecl();
1645 FD->removeInClassInitializer();
1646 return;
1647 }
1648
Richard Smith7a614d82011-06-11 17:19:42 +00001649 ExprResult Init = InitExpr;
1650 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001651 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001652 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001653 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1654 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001655 Expr **Inits = &InitExpr;
1656 unsigned NumInits = 1;
1657 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1658 InitializationKind Kind = EqualLoc.isInvalid()
1659 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1660 : InitializationKind::CreateCopy(InitExpr->getLocStart(), EqualLoc);
1661 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1662 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001663 if (Init.isInvalid()) {
1664 FD->setInvalidDecl();
1665 return;
1666 }
1667
1668 CheckImplicitConversions(Init.get(), EqualLoc);
1669 }
1670
1671 // C++0x [class.base.init]p7:
1672 // The initialization of each base and member constitutes a
1673 // full-expression.
1674 Init = MaybeCreateExprWithCleanups(Init);
1675 if (Init.isInvalid()) {
1676 FD->setInvalidDecl();
1677 return;
1678 }
1679
1680 InitExpr = Init.release();
1681
1682 FD->setInClassInitializer(InitExpr);
1683}
1684
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001685/// \brief Find the direct and/or virtual base specifiers that
1686/// correspond to the given base type, for use in base initialization
1687/// within a constructor.
1688static bool FindBaseInitializer(Sema &SemaRef,
1689 CXXRecordDecl *ClassDecl,
1690 QualType BaseType,
1691 const CXXBaseSpecifier *&DirectBaseSpec,
1692 const CXXBaseSpecifier *&VirtualBaseSpec) {
1693 // First, check for a direct base class.
1694 DirectBaseSpec = 0;
1695 for (CXXRecordDecl::base_class_const_iterator Base
1696 = ClassDecl->bases_begin();
1697 Base != ClassDecl->bases_end(); ++Base) {
1698 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1699 // We found a direct base of this type. That's what we're
1700 // initializing.
1701 DirectBaseSpec = &*Base;
1702 break;
1703 }
1704 }
1705
1706 // Check for a virtual base class.
1707 // FIXME: We might be able to short-circuit this if we know in advance that
1708 // there are no virtual bases.
1709 VirtualBaseSpec = 0;
1710 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1711 // We haven't found a base yet; search the class hierarchy for a
1712 // virtual base class.
1713 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1714 /*DetectVirtual=*/false);
1715 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1716 BaseType, Paths)) {
1717 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1718 Path != Paths.end(); ++Path) {
1719 if (Path->back().Base->isVirtual()) {
1720 VirtualBaseSpec = Path->back().Base;
1721 break;
1722 }
1723 }
1724 }
1725 }
1726
1727 return DirectBaseSpec || VirtualBaseSpec;
1728}
1729
Sebastian Redl6df65482011-09-24 17:48:25 +00001730/// \brief Handle a C++ member initializer using braced-init-list syntax.
1731MemInitResult
1732Sema::ActOnMemInitializer(Decl *ConstructorD,
1733 Scope *S,
1734 CXXScopeSpec &SS,
1735 IdentifierInfo *MemberOrBase,
1736 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001737 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001738 SourceLocation IdLoc,
1739 Expr *InitList,
1740 SourceLocation EllipsisLoc) {
1741 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001742 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001743 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001744}
1745
1746/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001747MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001748Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001749 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001750 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001751 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001752 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001753 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001754 SourceLocation IdLoc,
1755 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001756 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001757 SourceLocation RParenLoc,
1758 SourceLocation EllipsisLoc) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001759 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1760 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001761 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001762 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001763}
1764
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001765namespace {
1766
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001767// Callback to only accept typo corrections that can be a valid C++ member
1768// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001769class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1770 public:
1771 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1772 : ClassDecl(ClassDecl) {}
1773
1774 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1775 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1776 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1777 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1778 else
1779 return isa<TypeDecl>(ND);
1780 }
1781 return false;
1782 }
1783
1784 private:
1785 CXXRecordDecl *ClassDecl;
1786};
1787
1788}
1789
Sebastian Redl6df65482011-09-24 17:48:25 +00001790/// \brief Handle a C++ member initializer.
1791MemInitResult
1792Sema::BuildMemInitializer(Decl *ConstructorD,
1793 Scope *S,
1794 CXXScopeSpec &SS,
1795 IdentifierInfo *MemberOrBase,
1796 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001797 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001798 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001799 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001800 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001801 if (!ConstructorD)
1802 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001804 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001805
1806 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001807 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001808 if (!Constructor) {
1809 // The user wrote a constructor initializer on a function that is
1810 // not a C++ constructor. Ignore the error for now, because we may
1811 // have more member initializers coming; we'll diagnose it just
1812 // once in ActOnMemInitializers.
1813 return true;
1814 }
1815
1816 CXXRecordDecl *ClassDecl = Constructor->getParent();
1817
1818 // C++ [class.base.init]p2:
1819 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001820 // constructor's class and, if not found in that scope, are looked
1821 // up in the scope containing the constructor's definition.
1822 // [Note: if the constructor's class contains a member with the
1823 // same name as a direct or virtual base class of the class, a
1824 // mem-initializer-id naming the member or base class and composed
1825 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001826 // mem-initializer-id for the hidden base class may be specified
1827 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001828 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001829 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001830 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001831 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001832 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001833 ValueDecl *Member;
1834 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1835 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001836 if (EllipsisLoc.isValid())
1837 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001838 << MemberOrBase
1839 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001840
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001841 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001842 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001843 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001844 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001845 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001846 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001847 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001848
1849 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001850 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001851 } else if (DS.getTypeSpecType() == TST_decltype) {
1852 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001853 } else {
1854 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1855 LookupParsedName(R, S, &SS);
1856
1857 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1858 if (!TyD) {
1859 if (R.isAmbiguous()) return true;
1860
John McCallfd225442010-04-09 19:01:14 +00001861 // We don't want access-control diagnostics here.
1862 R.suppressDiagnostics();
1863
Douglas Gregor7a886e12010-01-19 06:46:48 +00001864 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1865 bool NotUnknownSpecialization = false;
1866 DeclContext *DC = computeDeclContext(SS, false);
1867 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1868 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1869
1870 if (!NotUnknownSpecialization) {
1871 // When the scope specifier can refer to a member of an unknown
1872 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001873 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1874 SS.getWithLocInContext(Context),
1875 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001876 if (BaseType.isNull())
1877 return true;
1878
Douglas Gregor7a886e12010-01-19 06:46:48 +00001879 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001880 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001881 }
1882 }
1883
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001884 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001885 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001886 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001887 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001888 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001889 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001890 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1891 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001892 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001893 // We have found a non-static data member with a similar
1894 // name to what was typed; complain and initialize that
1895 // member.
1896 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1897 << MemberOrBase << true << CorrectedQuotedStr
1898 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1899 Diag(Member->getLocation(), diag::note_previous_decl)
1900 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001901
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001902 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001903 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001904 const CXXBaseSpecifier *DirectBaseSpec;
1905 const CXXBaseSpecifier *VirtualBaseSpec;
1906 if (FindBaseInitializer(*this, ClassDecl,
1907 Context.getTypeDeclType(Type),
1908 DirectBaseSpec, VirtualBaseSpec)) {
1909 // We have found a direct or virtual base class with a
1910 // similar name to what was typed; complain and initialize
1911 // that base class.
1912 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001913 << MemberOrBase << false << CorrectedQuotedStr
1914 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001915
1916 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1917 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00001918 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00001919 diag::note_base_class_specified_here)
1920 << BaseSpec->getType()
1921 << BaseSpec->getSourceRange();
1922
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001923 TyD = Type;
1924 }
1925 }
1926 }
1927
Douglas Gregor7a886e12010-01-19 06:46:48 +00001928 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001929 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001930 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001931 return true;
1932 }
John McCall2b194412009-12-21 10:41:20 +00001933 }
1934
Douglas Gregor7a886e12010-01-19 06:46:48 +00001935 if (BaseType.isNull()) {
1936 BaseType = Context.getTypeDeclType(TyD);
1937 if (SS.isSet()) {
1938 NestedNameSpecifier *Qualifier =
1939 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001940
Douglas Gregor7a886e12010-01-19 06:46:48 +00001941 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001942 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001943 }
John McCall2b194412009-12-21 10:41:20 +00001944 }
1945 }
Mike Stump1eb44332009-09-09 15:08:12 +00001946
John McCalla93c9342009-12-07 02:54:59 +00001947 if (!TInfo)
1948 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001949
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001950 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001951}
1952
Chandler Carruth81c64772011-09-03 01:14:15 +00001953/// Checks a member initializer expression for cases where reference (or
1954/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001955static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1956 Expr *Init,
1957 SourceLocation IdLoc) {
1958 QualType MemberTy = Member->getType();
1959
1960 // We only handle pointers and references currently.
1961 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1962 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1963 return;
1964
1965 const bool IsPointer = MemberTy->isPointerType();
1966 if (IsPointer) {
1967 if (const UnaryOperator *Op
1968 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1969 // The only case we're worried about with pointers requires taking the
1970 // address.
1971 if (Op->getOpcode() != UO_AddrOf)
1972 return;
1973
1974 Init = Op->getSubExpr();
1975 } else {
1976 // We only handle address-of expression initializers for pointers.
1977 return;
1978 }
1979 }
1980
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001981 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1982 // Taking the address of a temporary will be diagnosed as a hard error.
1983 if (IsPointer)
1984 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001985
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001986 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1987 << Member << Init->getSourceRange();
1988 } else if (const DeclRefExpr *DRE
1989 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1990 // We only warn when referring to a non-reference parameter declaration.
1991 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1992 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001993 return;
1994
1995 S.Diag(Init->getExprLoc(),
1996 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1997 : diag::warn_bind_ref_member_to_parameter)
1998 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001999 } else {
2000 // Other initializers are fine.
2001 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002002 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002003
2004 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2005 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002006}
2007
John McCallb4190042009-11-04 23:02:40 +00002008/// Checks an initializer expression for use of uninitialized fields, such as
2009/// containing the field that is being initialized. Returns true if there is an
2010/// uninitialized field was used an updates the SourceLocation parameter; false
2011/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002012static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002013 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002014 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002015 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2016
Nick Lewycky43ad1822010-06-15 07:32:55 +00002017 if (isa<CallExpr>(S)) {
2018 // Do not descend into function calls or constructors, as the use
2019 // of an uninitialized field may be valid. One would have to inspect
2020 // the contents of the function/ctor to determine if it is safe or not.
2021 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2022 // may be safe, depending on what the function/ctor does.
2023 return false;
2024 }
2025 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2026 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002027
2028 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2029 // The member expression points to a static data member.
2030 assert(VD->isStaticDataMember() &&
2031 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002032 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002033 return false;
2034 }
2035
2036 if (isa<EnumConstantDecl>(RhsField)) {
2037 // The member expression points to an enum.
2038 return false;
2039 }
2040
John McCallb4190042009-11-04 23:02:40 +00002041 if (RhsField == LhsField) {
2042 // Initializing a field with itself. Throw a warning.
2043 // But wait; there are exceptions!
2044 // Exception #1: The field may not belong to this record.
2045 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002046 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002047 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2048 // Even though the field matches, it does not belong to this record.
2049 return false;
2050 }
2051 // None of the exceptions triggered; return true to indicate an
2052 // uninitialized field was used.
2053 *L = ME->getMemberLoc();
2054 return true;
2055 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002056 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002057 // sizeof/alignof doesn't reference contents, do not warn.
2058 return false;
2059 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2060 // address-of doesn't reference contents (the pointer may be dereferenced
2061 // in the same expression but it would be rare; and weird).
2062 if (UOE->getOpcode() == UO_AddrOf)
2063 return false;
John McCallb4190042009-11-04 23:02:40 +00002064 }
John McCall7502c1d2011-02-13 04:07:26 +00002065 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002066 if (!*it) {
2067 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002068 continue;
2069 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002070 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2071 return true;
John McCallb4190042009-11-04 23:02:40 +00002072 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002073 return false;
John McCallb4190042009-11-04 23:02:40 +00002074}
2075
John McCallf312b1e2010-08-26 23:41:50 +00002076MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002077Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002078 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002079 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2080 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2081 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002082 "Member must be a FieldDecl or IndirectFieldDecl");
2083
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002084 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002085 return true;
2086
Douglas Gregor464b2f02010-11-05 22:21:31 +00002087 if (Member->isInvalidDecl())
2088 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002089
John McCallb4190042009-11-04 23:02:40 +00002090 // Diagnose value-uses of fields to initialize themselves, e.g.
2091 // foo(foo)
2092 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002093 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002094 Expr **Args;
2095 unsigned NumArgs;
2096 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2097 Args = ParenList->getExprs();
2098 NumArgs = ParenList->getNumExprs();
2099 } else {
2100 InitListExpr *InitList = cast<InitListExpr>(Init);
2101 Args = InitList->getInits();
2102 NumArgs = InitList->getNumInits();
2103 }
2104 for (unsigned i = 0; i < NumArgs; ++i) {
John McCallb4190042009-11-04 23:02:40 +00002105 SourceLocation L;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002106 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002107 // FIXME: Return true in the case when other fields are used before being
2108 // uninitialized. For example, let this field be the i'th field. When
2109 // initializing the i'th field, throw a warning if any of the >= i'th
2110 // fields are used, as they are not yet initialized.
2111 // Right now we are only handling the case where the i'th field uses
2112 // itself in its initializer.
2113 Diag(L, diag::warn_field_is_uninit);
2114 }
2115 }
2116
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002117 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002118
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002119 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002120 // Can't check initialization for a member of dependent type or when
2121 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002122 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002123 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002124 bool InitList = false;
2125 if (isa<InitListExpr>(Init)) {
2126 InitList = true;
2127 Args = &Init;
2128 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002129
2130 if (isStdInitializerList(Member->getType(), 0)) {
2131 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2132 << /*at end of ctor*/1 << InitRange;
2133 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002134 }
2135
Chandler Carruth894aed92010-12-06 09:23:57 +00002136 // Initialize the member.
2137 InitializedEntity MemberEntity =
2138 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2139 : InitializedEntity::InitializeMember(IndirectMember, 0);
2140 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002141 InitList ? InitializationKind::CreateDirectList(IdLoc)
2142 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2143 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002144
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002145 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2146 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2147 MultiExprArg(*this, Args, NumArgs),
2148 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002149 if (MemberInit.isInvalid())
2150 return true;
2151
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002152 CheckImplicitConversions(MemberInit.get(),
2153 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002154
2155 // C++0x [class.base.init]p7:
2156 // The initialization of each base and member constitutes a
2157 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002158 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002159 if (MemberInit.isInvalid())
2160 return true;
2161
2162 // If we are in a dependent context, template instantiation will
2163 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002164 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002165 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2166 // of the information that we have about the member
2167 // initializer. However, deconstructing the ASTs is a dicey process,
2168 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002169 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002170 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002171 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002172 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002173 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2174 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002175 }
2176
Chandler Carruth894aed92010-12-06 09:23:57 +00002177 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002178 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2179 InitRange.getBegin(), Init,
2180 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002181 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002182 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2183 InitRange.getBegin(), Init,
2184 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002185 }
Eli Friedman59c04372009-07-29 19:44:27 +00002186}
2187
John McCallf312b1e2010-08-26 23:41:50 +00002188MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002189Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002190 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002191 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002192 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002193 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002194 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002195 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002196
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002197 bool InitList = true;
2198 Expr **Args = &Init;
2199 unsigned NumArgs = 1;
2200 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2201 InitList = false;
2202 Args = ParenList->getExprs();
2203 NumArgs = ParenList->getNumExprs();
2204 }
2205
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002206 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002207 // Initialize the object.
2208 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2209 QualType(ClassDecl->getTypeForDecl(), 0));
2210 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002211 InitList ? InitializationKind::CreateDirectList(NameLoc)
2212 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2213 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002214 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2215 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2216 MultiExprArg(*this, Args,NumArgs),
2217 0);
Sean Hunt41717662011-02-26 19:13:13 +00002218 if (DelegationInit.isInvalid())
2219 return true;
2220
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002221 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2222 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002223
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002224 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002225
2226 // C++0x [class.base.init]p7:
2227 // The initialization of each base and member constitutes a
2228 // full-expression.
2229 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2230 if (DelegationInit.isInvalid())
2231 return true;
2232
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002233 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002234 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002235 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002236}
2237
2238MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002239Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002240 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002241 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002242 SourceLocation BaseLoc
2243 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002244
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002245 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2246 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2247 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2248
2249 // C++ [class.base.init]p2:
2250 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002251 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002252 // of that class, the mem-initializer is ill-formed. A
2253 // mem-initializer-list can initialize a base class using any
2254 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002255 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002256
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002257 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002258 if (EllipsisLoc.isValid()) {
2259 // This is a pack expansion.
2260 if (!BaseType->containsUnexpandedParameterPack()) {
2261 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002262 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002263
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002264 EllipsisLoc = SourceLocation();
2265 }
2266 } else {
2267 // Check for any unexpanded parameter packs.
2268 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2269 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002270
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002271 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002272 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002273 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002274
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002275 // Check for direct and virtual base classes.
2276 const CXXBaseSpecifier *DirectBaseSpec = 0;
2277 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2278 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002279 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2280 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002281 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002282
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002283 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2284 VirtualBaseSpec);
2285
2286 // C++ [base.class.init]p2:
2287 // Unless the mem-initializer-id names a nonstatic data member of the
2288 // constructor's class or a direct or virtual base of that class, the
2289 // mem-initializer is ill-formed.
2290 if (!DirectBaseSpec && !VirtualBaseSpec) {
2291 // If the class has any dependent bases, then it's possible that
2292 // one of those types will resolve to the same type as
2293 // BaseType. Therefore, just treat this as a dependent base
2294 // class initialization. FIXME: Should we try to check the
2295 // initialization anyway? It seems odd.
2296 if (ClassDecl->hasAnyDependentBases())
2297 Dependent = true;
2298 else
2299 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2300 << BaseType << Context.getTypeDeclType(ClassDecl)
2301 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2302 }
2303 }
2304
2305 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002306 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Sebastian Redl6df65482011-09-24 17:48:25 +00002308 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2309 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002310 InitRange.getBegin(), Init,
2311 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002312 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002313
2314 // C++ [base.class.init]p2:
2315 // If a mem-initializer-id is ambiguous because it designates both
2316 // a direct non-virtual base class and an inherited virtual base
2317 // class, the mem-initializer is ill-formed.
2318 if (DirectBaseSpec && VirtualBaseSpec)
2319 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002320 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002321
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002322 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002323 if (!BaseSpec)
2324 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2325
2326 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002327 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002328 Expr **Args = &Init;
2329 unsigned NumArgs = 1;
2330 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002331 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002332 Args = ParenList->getExprs();
2333 NumArgs = ParenList->getNumExprs();
2334 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002335
2336 InitializedEntity BaseEntity =
2337 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2338 InitializationKind Kind =
2339 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2340 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2341 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002342 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2343 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2344 MultiExprArg(*this, Args, NumArgs),
2345 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002346 if (BaseInit.isInvalid())
2347 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002348
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002349 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002350
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002351 // C++0x [class.base.init]p7:
2352 // The initialization of each base and member constitutes a
2353 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002354 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002355 if (BaseInit.isInvalid())
2356 return true;
2357
2358 // If we are in a dependent context, template instantiation will
2359 // perform this type-checking again. Just save the arguments that we
2360 // received in a ParenListExpr.
2361 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2362 // of the information that we have about the base
2363 // initializer. However, deconstructing the ASTs is a dicey process,
2364 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002365 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002366 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002367
Sean Huntcbb67482011-01-08 20:30:50 +00002368 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002369 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002370 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002371 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002372 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002373}
2374
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002375// Create a static_cast\<T&&>(expr).
2376static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2377 QualType ExprType = E->getType();
2378 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2379 SourceLocation ExprLoc = E->getLocStart();
2380 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2381 TargetType, ExprLoc);
2382
2383 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2384 SourceRange(ExprLoc, ExprLoc),
2385 E->getSourceRange()).take();
2386}
2387
Anders Carlssone5ef7402010-04-23 03:10:23 +00002388/// ImplicitInitializerKind - How an implicit base or member initializer should
2389/// initialize its base or member.
2390enum ImplicitInitializerKind {
2391 IIK_Default,
2392 IIK_Copy,
2393 IIK_Move
2394};
2395
Anders Carlssondefefd22010-04-23 02:00:02 +00002396static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002397BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002398 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002399 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002400 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002401 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002402 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002403 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2404 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002405
John McCall60d7b3a2010-08-24 06:29:42 +00002406 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002407
2408 switch (ImplicitInitKind) {
2409 case IIK_Default: {
2410 InitializationKind InitKind
2411 = InitializationKind::CreateDefault(Constructor->getLocation());
2412 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2413 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002414 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002415 break;
2416 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002417
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002418 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002419 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002420 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002421 ParmVarDecl *Param = Constructor->getParamDecl(0);
2422 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002423
Anders Carlssone5ef7402010-04-23 03:10:23 +00002424 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002425 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002426 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002427 Constructor->getLocation(), ParamType,
2428 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002429
Eli Friedman5f2987c2012-02-02 03:46:19 +00002430 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2431
Anders Carlssonc7957502010-04-24 22:02:54 +00002432 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002433 QualType ArgTy =
2434 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2435 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002436
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002437 if (Moving) {
2438 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2439 }
2440
John McCallf871d0c2010-08-07 06:22:56 +00002441 CXXCastPath BasePath;
2442 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002443 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2444 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002445 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002446 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002447
Anders Carlssone5ef7402010-04-23 03:10:23 +00002448 InitializationKind InitKind
2449 = InitializationKind::CreateDirect(Constructor->getLocation(),
2450 SourceLocation(), SourceLocation());
2451 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2452 &CopyCtorArg, 1);
2453 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002454 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002455 break;
2456 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002457 }
John McCall9ae2f072010-08-23 23:25:46 +00002458
Douglas Gregor53c374f2010-12-07 00:41:46 +00002459 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002460 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002461 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002462
Anders Carlssondefefd22010-04-23 02:00:02 +00002463 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002464 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002465 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2466 SourceLocation()),
2467 BaseSpec->isVirtual(),
2468 SourceLocation(),
2469 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002470 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002471 SourceLocation());
2472
Anders Carlssondefefd22010-04-23 02:00:02 +00002473 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002474}
2475
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002476static bool RefersToRValueRef(Expr *MemRef) {
2477 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2478 return Referenced->getType()->isRValueReferenceType();
2479}
2480
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002481static bool
2482BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002483 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002484 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002485 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002486 if (Field->isInvalidDecl())
2487 return true;
2488
Chandler Carruthf186b542010-06-29 23:50:44 +00002489 SourceLocation Loc = Constructor->getLocation();
2490
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002491 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2492 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002493 ParmVarDecl *Param = Constructor->getParamDecl(0);
2494 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002495
2496 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002497 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2498 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002499
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002500 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002501 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002502 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002503 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002504
Eli Friedman5f2987c2012-02-02 03:46:19 +00002505 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2506
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002507 if (Moving) {
2508 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2509 }
2510
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002511 // Build a reference to this field within the parameter.
2512 CXXScopeSpec SS;
2513 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2514 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002515 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2516 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002517 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002518 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002519 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002520 ParamType, Loc,
2521 /*IsArrow=*/false,
2522 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002523 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002524 /*FirstQualifierInScope=*/0,
2525 MemberLookup,
2526 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002527 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002528 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002529
2530 // C++11 [class.copy]p15:
2531 // - if a member m has rvalue reference type T&&, it is direct-initialized
2532 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002533 if (RefersToRValueRef(CtorArg.get())) {
2534 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002535 }
2536
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002537 // When the field we are copying is an array, create index variables for
2538 // each dimension of the array. We use these index variables to subscript
2539 // the source array, and other clients (e.g., CodeGen) will perform the
2540 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002541 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002542 QualType BaseType = Field->getType();
2543 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002544 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002545 while (const ConstantArrayType *Array
2546 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002547 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002548 // Create the iteration variable for this array index.
2549 IdentifierInfo *IterationVarName = 0;
2550 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002551 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002552 llvm::raw_svector_ostream OS(Str);
2553 OS << "__i" << IndexVariables.size();
2554 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2555 }
2556 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002557 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002558 IterationVarName, SizeType,
2559 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002560 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002561 IndexVariables.push_back(IterationVar);
2562
2563 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002564 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002565 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002566 assert(!IterationVarRef.isInvalid() &&
2567 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002568 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2569 assert(!IterationVarRef.isInvalid() &&
2570 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002571
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002572 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002573 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002574 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002575 Loc);
2576 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002577 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002578
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002579 BaseType = Array->getElementType();
2580 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002581
2582 // The array subscript expression is an lvalue, which is wrong for moving.
2583 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002584 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002585
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002586 // Construct the entity that we will be initializing. For an array, this
2587 // will be first element in the array, which may require several levels
2588 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002589 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002590 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002591 if (Indirect)
2592 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2593 else
2594 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002595 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2596 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2597 0,
2598 Entities.back()));
2599
2600 // Direct-initialize to use the copy constructor.
2601 InitializationKind InitKind =
2602 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2603
Sebastian Redl74e611a2011-09-04 18:14:28 +00002604 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002605 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002606 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002607
John McCall60d7b3a2010-08-24 06:29:42 +00002608 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002609 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002610 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002611 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002612 if (MemberInit.isInvalid())
2613 return true;
2614
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002615 if (Indirect) {
2616 assert(IndexVariables.size() == 0 &&
2617 "Indirect field improperly initialized");
2618 CXXMemberInit
2619 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2620 Loc, Loc,
2621 MemberInit.takeAs<Expr>(),
2622 Loc);
2623 } else
2624 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2625 Loc, MemberInit.takeAs<Expr>(),
2626 Loc,
2627 IndexVariables.data(),
2628 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002629 return false;
2630 }
2631
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002632 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2633
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002634 QualType FieldBaseElementType =
2635 SemaRef.Context.getBaseElementType(Field->getType());
2636
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002637 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002638 InitializedEntity InitEntity
2639 = Indirect? InitializedEntity::InitializeMember(Indirect)
2640 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002641 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002642 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002643
2644 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002645 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002646 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002647
Douglas Gregor53c374f2010-12-07 00:41:46 +00002648 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002649 if (MemberInit.isInvalid())
2650 return true;
2651
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002652 if (Indirect)
2653 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2654 Indirect, Loc,
2655 Loc,
2656 MemberInit.get(),
2657 Loc);
2658 else
2659 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2660 Field, Loc, Loc,
2661 MemberInit.get(),
2662 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002663 return false;
2664 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002665
Sean Hunt1f2f3842011-05-17 00:19:05 +00002666 if (!Field->getParent()->isUnion()) {
2667 if (FieldBaseElementType->isReferenceType()) {
2668 SemaRef.Diag(Constructor->getLocation(),
2669 diag::err_uninitialized_member_in_ctor)
2670 << (int)Constructor->isImplicit()
2671 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2672 << 0 << Field->getDeclName();
2673 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2674 return true;
2675 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002676
Sean Hunt1f2f3842011-05-17 00:19:05 +00002677 if (FieldBaseElementType.isConstQualified()) {
2678 SemaRef.Diag(Constructor->getLocation(),
2679 diag::err_uninitialized_member_in_ctor)
2680 << (int)Constructor->isImplicit()
2681 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2682 << 1 << Field->getDeclName();
2683 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2684 return true;
2685 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002686 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002687
David Blaikie4e4d0842012-03-11 07:00:24 +00002688 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002689 FieldBaseElementType->isObjCRetainableType() &&
2690 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2691 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2692 // Instant objects:
2693 // Default-initialize Objective-C pointers to NULL.
2694 CXXMemberInit
2695 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2696 Loc, Loc,
2697 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2698 Loc);
2699 return false;
2700 }
2701
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002702 // Nothing to initialize.
2703 CXXMemberInit = 0;
2704 return false;
2705}
John McCallf1860e52010-05-20 23:23:51 +00002706
2707namespace {
2708struct BaseAndFieldInfo {
2709 Sema &S;
2710 CXXConstructorDecl *Ctor;
2711 bool AnyErrorsInInits;
2712 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002713 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002714 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002715
2716 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2717 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002718 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2719 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002720 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002721 else if (Generated && Ctor->isMoveConstructor())
2722 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002723 else
2724 IIK = IIK_Default;
2725 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002726
2727 bool isImplicitCopyOrMove() const {
2728 switch (IIK) {
2729 case IIK_Copy:
2730 case IIK_Move:
2731 return true;
2732
2733 case IIK_Default:
2734 return false;
2735 }
David Blaikie30263482012-01-20 21:50:17 +00002736
2737 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002738 }
John McCallf1860e52010-05-20 23:23:51 +00002739};
2740}
2741
Richard Smitha4950662011-09-19 13:34:43 +00002742/// \brief Determine whether the given indirect field declaration is somewhere
2743/// within an anonymous union.
2744static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2745 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2746 CEnd = F->chain_end();
2747 C != CEnd; ++C)
2748 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2749 if (Record->isUnion())
2750 return true;
2751
2752 return false;
2753}
2754
Douglas Gregorddb21472011-11-02 23:04:16 +00002755/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2756/// array type.
2757static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2758 if (T->isIncompleteArrayType())
2759 return true;
2760
2761 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2762 if (!ArrayT->getSize())
2763 return true;
2764
2765 T = ArrayT->getElementType();
2766 }
2767
2768 return false;
2769}
2770
Richard Smith7a614d82011-06-11 17:19:42 +00002771static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002772 FieldDecl *Field,
2773 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002774
Chandler Carruthe861c602010-06-30 02:59:29 +00002775 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002776 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002777 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002778 return false;
2779 }
2780
Richard Smith7a614d82011-06-11 17:19:42 +00002781 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2782 // has a brace-or-equal-initializer, the entity is initialized as specified
2783 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002784 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002785 CXXCtorInitializer *Init;
2786 if (Indirect)
2787 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2788 SourceLocation(),
2789 SourceLocation(), 0,
2790 SourceLocation());
2791 else
2792 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2793 SourceLocation(),
2794 SourceLocation(), 0,
2795 SourceLocation());
2796 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002797 return false;
2798 }
2799
Richard Smithc115f632011-09-18 11:14:50 +00002800 // Don't build an implicit initializer for union members if none was
2801 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002802 if (Field->getParent()->isUnion() ||
2803 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002804 return false;
2805
Douglas Gregorddb21472011-11-02 23:04:16 +00002806 // Don't initialize incomplete or zero-length arrays.
2807 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2808 return false;
2809
John McCallf1860e52010-05-20 23:23:51 +00002810 // Don't try to build an implicit initializer if there were semantic
2811 // errors in any of the initializers (and therefore we might be
2812 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002813 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002814 return false;
2815
Sean Huntcbb67482011-01-08 20:30:50 +00002816 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002817 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2818 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002819 return true;
John McCallf1860e52010-05-20 23:23:51 +00002820
Francois Pichet00eb3f92010-12-04 09:14:42 +00002821 if (Init)
2822 Info.AllToInit.push_back(Init);
2823
John McCallf1860e52010-05-20 23:23:51 +00002824 return false;
2825}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002826
2827bool
2828Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2829 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002830 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002831 Constructor->setNumCtorInitializers(1);
2832 CXXCtorInitializer **initializer =
2833 new (Context) CXXCtorInitializer*[1];
2834 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2835 Constructor->setCtorInitializers(initializer);
2836
Sean Huntb76af9c2011-05-03 23:05:34 +00002837 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002838 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002839 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2840 }
2841
Sean Huntc1598702011-05-05 00:05:47 +00002842 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002843
Sean Hunt059ce0d2011-05-01 07:04:31 +00002844 return false;
2845}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002846
John McCallb77115d2011-06-17 00:18:42 +00002847bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2848 CXXCtorInitializer **Initializers,
2849 unsigned NumInitializers,
2850 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002851 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002852 // Just store the initializers as written, they will be checked during
2853 // instantiation.
2854 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002855 Constructor->setNumCtorInitializers(NumInitializers);
2856 CXXCtorInitializer **baseOrMemberInitializers =
2857 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002858 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002859 NumInitializers * sizeof(CXXCtorInitializer*));
2860 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002861 }
2862
2863 return false;
2864 }
2865
John McCallf1860e52010-05-20 23:23:51 +00002866 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002867
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002868 // We need to build the initializer AST according to order of construction
2869 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002870 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002871 if (!ClassDecl)
2872 return true;
2873
Eli Friedman80c30da2009-11-09 19:20:36 +00002874 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002875
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002876 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002877 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002878
2879 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002880 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002881 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002882 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002883 }
2884
Anders Carlsson711f34a2010-04-21 19:52:01 +00002885 // Keep track of the direct virtual bases.
2886 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2887 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2888 E = ClassDecl->bases_end(); I != E; ++I) {
2889 if (I->isVirtual())
2890 DirectVBases.insert(I);
2891 }
2892
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002893 // Push virtual bases before others.
2894 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2895 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2896
Sean Huntcbb67482011-01-08 20:30:50 +00002897 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002898 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2899 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002900 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002901 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002902 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002903 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002904 VBase, IsInheritedVirtualBase,
2905 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002906 HadError = true;
2907 continue;
2908 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002909
John McCallf1860e52010-05-20 23:23:51 +00002910 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002911 }
2912 }
Mike Stump1eb44332009-09-09 15:08:12 +00002913
John McCallf1860e52010-05-20 23:23:51 +00002914 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002915 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2916 E = ClassDecl->bases_end(); Base != E; ++Base) {
2917 // Virtuals are in the virtual base list and already constructed.
2918 if (Base->isVirtual())
2919 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002920
Sean Huntcbb67482011-01-08 20:30:50 +00002921 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002922 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2923 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002924 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002925 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002926 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002927 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002928 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002929 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002930 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002931 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002932
John McCallf1860e52010-05-20 23:23:51 +00002933 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002934 }
2935 }
Mike Stump1eb44332009-09-09 15:08:12 +00002936
John McCallf1860e52010-05-20 23:23:51 +00002937 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002938 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2939 MemEnd = ClassDecl->decls_end();
2940 Mem != MemEnd; ++Mem) {
2941 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002942 // C++ [class.bit]p2:
2943 // A declaration for a bit-field that omits the identifier declares an
2944 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2945 // initialized.
2946 if (F->isUnnamedBitfield())
2947 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002948
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002949 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002950 // handle anonymous struct/union fields based on their individual
2951 // indirect fields.
2952 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2953 continue;
2954
2955 if (CollectFieldInitializer(*this, Info, F))
2956 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002957 continue;
2958 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002959
2960 // Beyond this point, we only consider default initialization.
2961 if (Info.IIK != IIK_Default)
2962 continue;
2963
2964 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2965 if (F->getType()->isIncompleteArrayType()) {
2966 assert(ClassDecl->hasFlexibleArrayMember() &&
2967 "Incomplete array type is not valid");
2968 continue;
2969 }
2970
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002971 // Initialize each field of an anonymous struct individually.
2972 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2973 HadError = true;
2974
2975 continue;
2976 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002977 }
Mike Stump1eb44332009-09-09 15:08:12 +00002978
John McCallf1860e52010-05-20 23:23:51 +00002979 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002980 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002981 Constructor->setNumCtorInitializers(NumInitializers);
2982 CXXCtorInitializer **baseOrMemberInitializers =
2983 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002984 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002985 NumInitializers * sizeof(CXXCtorInitializer*));
2986 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002987
John McCallef027fe2010-03-16 21:39:52 +00002988 // Constructors implicitly reference the base and member
2989 // destructors.
2990 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2991 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002992 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002993
2994 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002995}
2996
Eli Friedman6347f422009-07-21 19:28:10 +00002997static void *GetKeyForTopLevelField(FieldDecl *Field) {
2998 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002999 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003000 if (RT->getDecl()->isAnonymousStructOrUnion())
3001 return static_cast<void *>(RT->getDecl());
3002 }
3003 return static_cast<void *>(Field);
3004}
3005
Anders Carlssonea356fb2010-04-02 05:42:15 +00003006static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003007 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003008}
3009
Anders Carlssonea356fb2010-04-02 05:42:15 +00003010static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003011 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003012 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003013 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003014
Eli Friedman6347f422009-07-21 19:28:10 +00003015 // For fields injected into the class via declaration of an anonymous union,
3016 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003017 FieldDecl *Field = Member->getAnyMember();
3018
John McCall3c3ccdb2010-04-10 09:28:51 +00003019 // If the field is a member of an anonymous struct or union, our key
3020 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003021 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003022 if (RD->isAnonymousStructOrUnion()) {
3023 while (true) {
3024 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3025 if (Parent->isAnonymousStructOrUnion())
3026 RD = Parent;
3027 else
3028 break;
3029 }
3030
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003031 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003032 }
Mike Stump1eb44332009-09-09 15:08:12 +00003033
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003034 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003035}
3036
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003037static void
3038DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003039 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003040 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003041 unsigned NumInits) {
3042 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003043 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003045 // Don't check initializers order unless the warning is enabled at the
3046 // location of at least one initializer.
3047 bool ShouldCheckOrder = false;
3048 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003049 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003050 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3051 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003052 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003053 ShouldCheckOrder = true;
3054 break;
3055 }
3056 }
3057 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003058 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003059
John McCalld6ca8da2010-04-10 07:37:23 +00003060 // Build the list of bases and members in the order that they'll
3061 // actually be initialized. The explicit initializers should be in
3062 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003063 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003064
Anders Carlsson071d6102010-04-02 03:38:04 +00003065 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3066
John McCalld6ca8da2010-04-10 07:37:23 +00003067 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003068 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003069 ClassDecl->vbases_begin(),
3070 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003071 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003072
John McCalld6ca8da2010-04-10 07:37:23 +00003073 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003074 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003075 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003076 if (Base->isVirtual())
3077 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003078 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003079 }
Mike Stump1eb44332009-09-09 15:08:12 +00003080
John McCalld6ca8da2010-04-10 07:37:23 +00003081 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003082 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003083 E = ClassDecl->field_end(); Field != E; ++Field) {
3084 if (Field->isUnnamedBitfield())
3085 continue;
3086
John McCalld6ca8da2010-04-10 07:37:23 +00003087 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003088 }
3089
John McCalld6ca8da2010-04-10 07:37:23 +00003090 unsigned NumIdealInits = IdealInitKeys.size();
3091 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003092
Sean Huntcbb67482011-01-08 20:30:50 +00003093 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003094 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003095 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003096 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003097
3098 // Scan forward to try to find this initializer in the idealized
3099 // initializers list.
3100 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3101 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003102 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003103
3104 // If we didn't find this initializer, it must be because we
3105 // scanned past it on a previous iteration. That can only
3106 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003107 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003108 Sema::SemaDiagnosticBuilder D =
3109 SemaRef.Diag(PrevInit->getSourceLocation(),
3110 diag::warn_initializer_out_of_order);
3111
Francois Pichet00eb3f92010-12-04 09:14:42 +00003112 if (PrevInit->isAnyMemberInitializer())
3113 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003114 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003115 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003116
Francois Pichet00eb3f92010-12-04 09:14:42 +00003117 if (Init->isAnyMemberInitializer())
3118 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003119 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003120 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003121
3122 // Move back to the initializer's location in the ideal list.
3123 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3124 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003125 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003126
3127 assert(IdealIndex != NumIdealInits &&
3128 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003129 }
John McCalld6ca8da2010-04-10 07:37:23 +00003130
3131 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003132 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003133}
3134
John McCall3c3ccdb2010-04-10 09:28:51 +00003135namespace {
3136bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003137 CXXCtorInitializer *Init,
3138 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003139 if (!PrevInit) {
3140 PrevInit = Init;
3141 return false;
3142 }
3143
3144 if (FieldDecl *Field = Init->getMember())
3145 S.Diag(Init->getSourceLocation(),
3146 diag::err_multiple_mem_initialization)
3147 << Field->getDeclName()
3148 << Init->getSourceRange();
3149 else {
John McCallf4c73712011-01-19 06:33:43 +00003150 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003151 assert(BaseClass && "neither field nor base");
3152 S.Diag(Init->getSourceLocation(),
3153 diag::err_multiple_base_initialization)
3154 << QualType(BaseClass, 0)
3155 << Init->getSourceRange();
3156 }
3157 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3158 << 0 << PrevInit->getSourceRange();
3159
3160 return true;
3161}
3162
Sean Huntcbb67482011-01-08 20:30:50 +00003163typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003164typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3165
3166bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003167 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003168 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003169 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003170 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003171 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003172
3173 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003174 if (Parent->isUnion()) {
3175 UnionEntry &En = Unions[Parent];
3176 if (En.first && En.first != Child) {
3177 S.Diag(Init->getSourceLocation(),
3178 diag::err_multiple_mem_union_initialization)
3179 << Field->getDeclName()
3180 << Init->getSourceRange();
3181 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3182 << 0 << En.second->getSourceRange();
3183 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003184 }
3185 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003186 En.first = Child;
3187 En.second = Init;
3188 }
David Blaikie6fe29652011-11-17 06:01:57 +00003189 if (!Parent->isAnonymousStructOrUnion())
3190 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003191 }
3192
3193 Child = Parent;
3194 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003195 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003196
3197 return false;
3198}
3199}
3200
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003201/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003202void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003203 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003204 CXXCtorInitializer **meminits,
3205 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003206 bool AnyErrors) {
3207 if (!ConstructorDecl)
3208 return;
3209
3210 AdjustDeclIfTemplate(ConstructorDecl);
3211
3212 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003213 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003214
3215 if (!Constructor) {
3216 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3217 return;
3218 }
3219
Sean Huntcbb67482011-01-08 20:30:50 +00003220 CXXCtorInitializer **MemInits =
3221 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003222
3223 // Mapping for the duplicate initializers check.
3224 // For member initializers, this is keyed with a FieldDecl*.
3225 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003226 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003227
3228 // Mapping for the inconsistent anonymous-union initializers check.
3229 RedundantUnionMap MemberUnions;
3230
Anders Carlssonea356fb2010-04-02 05:42:15 +00003231 bool HadError = false;
3232 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003233 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003234
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003235 // Set the source order index.
3236 Init->setSourceOrder(i);
3237
Francois Pichet00eb3f92010-12-04 09:14:42 +00003238 if (Init->isAnyMemberInitializer()) {
3239 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003240 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3241 CheckRedundantUnionInit(*this, Init, MemberUnions))
3242 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003243 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003244 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3245 if (CheckRedundantInit(*this, Init, Members[Key]))
3246 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003247 } else {
3248 assert(Init->isDelegatingInitializer());
3249 // This must be the only initializer
3250 if (i != 0 || NumMemInits > 1) {
3251 Diag(MemInits[0]->getSourceLocation(),
3252 diag::err_delegating_initializer_alone)
3253 << MemInits[0]->getSourceRange();
3254 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003255 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003256 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003257 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003258 // Return immediately as the initializer is set.
3259 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003260 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003261 }
3262
Anders Carlssonea356fb2010-04-02 05:42:15 +00003263 if (HadError)
3264 return;
3265
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003266 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003267
Sean Huntcbb67482011-01-08 20:30:50 +00003268 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003269}
3270
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003271void
John McCallef027fe2010-03-16 21:39:52 +00003272Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3273 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003274 // Ignore dependent contexts. Also ignore unions, since their members never
3275 // have destructors implicitly called.
3276 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003277 return;
John McCall58e6f342010-03-16 05:22:47 +00003278
3279 // FIXME: all the access-control diagnostics are positioned on the
3280 // field/base declaration. That's probably good; that said, the
3281 // user might reasonably want to know why the destructor is being
3282 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003283
Anders Carlsson9f853df2009-11-17 04:44:12 +00003284 // Non-static data members.
3285 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3286 E = ClassDecl->field_end(); I != E; ++I) {
3287 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003288 if (Field->isInvalidDecl())
3289 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003290
3291 // Don't destroy incomplete or zero-length arrays.
3292 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3293 continue;
3294
Anders Carlsson9f853df2009-11-17 04:44:12 +00003295 QualType FieldType = Context.getBaseElementType(Field->getType());
3296
3297 const RecordType* RT = FieldType->getAs<RecordType>();
3298 if (!RT)
3299 continue;
3300
3301 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003302 if (FieldClassDecl->isInvalidDecl())
3303 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003304 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003305 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003306 // The destructor for an implicit anonymous union member is never invoked.
3307 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3308 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003309
Douglas Gregordb89f282010-07-01 22:47:18 +00003310 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003311 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003312 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003313 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003314 << Field->getDeclName()
3315 << FieldType);
3316
Eli Friedman5f2987c2012-02-02 03:46:19 +00003317 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003318 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003319 }
3320
John McCall58e6f342010-03-16 05:22:47 +00003321 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3322
Anders Carlsson9f853df2009-11-17 04:44:12 +00003323 // Bases.
3324 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3325 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003326 // Bases are always records in a well-formed non-dependent class.
3327 const RecordType *RT = Base->getType()->getAs<RecordType>();
3328
3329 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003330 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003331 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003332
John McCall58e6f342010-03-16 05:22:47 +00003333 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003334 // If our base class is invalid, we probably can't get its dtor anyway.
3335 if (BaseClassDecl->isInvalidDecl())
3336 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003337 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003338 continue;
John McCall58e6f342010-03-16 05:22:47 +00003339
Douglas Gregordb89f282010-07-01 22:47:18 +00003340 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003341 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003342
3343 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003344 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003345 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003346 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003347 << Base->getSourceRange(),
3348 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003349
Eli Friedman5f2987c2012-02-02 03:46:19 +00003350 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003351 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003352 }
3353
3354 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003355 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3356 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003357
3358 // Bases are always records in a well-formed non-dependent class.
3359 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3360
3361 // Ignore direct virtual bases.
3362 if (DirectVirtualBases.count(RT))
3363 continue;
3364
John McCall58e6f342010-03-16 05:22:47 +00003365 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003366 // If our base class is invalid, we probably can't get its dtor anyway.
3367 if (BaseClassDecl->isInvalidDecl())
3368 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003369 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003370 continue;
John McCall58e6f342010-03-16 05:22:47 +00003371
Douglas Gregordb89f282010-07-01 22:47:18 +00003372 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003373 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003374 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003375 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003376 << VBase->getType());
3377
Eli Friedman5f2987c2012-02-02 03:46:19 +00003378 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003379 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003380 }
3381}
3382
John McCalld226f652010-08-21 09:40:31 +00003383void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003384 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003385 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003386
Mike Stump1eb44332009-09-09 15:08:12 +00003387 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003388 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003389 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003390}
3391
Mike Stump1eb44332009-09-09 15:08:12 +00003392bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003393 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003394 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003395 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003396 else
John McCall94c3b562010-08-18 09:41:07 +00003397 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003398}
3399
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003400bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003401 const PartialDiagnostic &PD) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003402 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003403 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003404
Anders Carlsson11f21a02009-03-23 19:10:31 +00003405 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003406 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003407
Ted Kremenek6217b802009-07-29 21:53:49 +00003408 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003409 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003410 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003411 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003413 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003414 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003415 }
Mike Stump1eb44332009-09-09 15:08:12 +00003416
Ted Kremenek6217b802009-07-29 21:53:49 +00003417 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003418 if (!RT)
3419 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003420
John McCall86ff3082010-02-04 22:26:26 +00003421 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003422
John McCall94c3b562010-08-18 09:41:07 +00003423 // We can't answer whether something is abstract until it has a
3424 // definition. If it's currently being defined, we'll walk back
3425 // over all the declarations when we have a full definition.
3426 const CXXRecordDecl *Def = RD->getDefinition();
3427 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003428 return false;
3429
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003430 if (!RD->isAbstract())
3431 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003432
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003433 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003434 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003435
John McCall94c3b562010-08-18 09:41:07 +00003436 return true;
3437}
3438
3439void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3440 // Check if we've already emitted the list of pure virtual functions
3441 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003442 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003443 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003444
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003445 CXXFinalOverriderMap FinalOverriders;
3446 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003447
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003448 // Keep a set of seen pure methods so we won't diagnose the same method
3449 // more than once.
3450 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3451
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003452 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3453 MEnd = FinalOverriders.end();
3454 M != MEnd;
3455 ++M) {
3456 for (OverridingMethods::iterator SO = M->second.begin(),
3457 SOEnd = M->second.end();
3458 SO != SOEnd; ++SO) {
3459 // C++ [class.abstract]p4:
3460 // A class is abstract if it contains or inherits at least one
3461 // pure virtual function for which the final overrider is pure
3462 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003463
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003464 //
3465 if (SO->second.size() != 1)
3466 continue;
3467
3468 if (!SO->second.front().Method->isPure())
3469 continue;
3470
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003471 if (!SeenPureMethods.insert(SO->second.front().Method))
3472 continue;
3473
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003474 Diag(SO->second.front().Method->getLocation(),
3475 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003476 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003477 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003478 }
3479
3480 if (!PureVirtualClassDiagSet)
3481 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3482 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003483}
3484
Anders Carlsson8211eff2009-03-24 01:19:16 +00003485namespace {
John McCall94c3b562010-08-18 09:41:07 +00003486struct AbstractUsageInfo {
3487 Sema &S;
3488 CXXRecordDecl *Record;
3489 CanQualType AbstractType;
3490 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003491
John McCall94c3b562010-08-18 09:41:07 +00003492 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3493 : S(S), Record(Record),
3494 AbstractType(S.Context.getCanonicalType(
3495 S.Context.getTypeDeclType(Record))),
3496 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003497
John McCall94c3b562010-08-18 09:41:07 +00003498 void DiagnoseAbstractType() {
3499 if (Invalid) return;
3500 S.DiagnoseAbstractType(Record);
3501 Invalid = true;
3502 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003503
John McCall94c3b562010-08-18 09:41:07 +00003504 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3505};
3506
3507struct CheckAbstractUsage {
3508 AbstractUsageInfo &Info;
3509 const NamedDecl *Ctx;
3510
3511 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3512 : Info(Info), Ctx(Ctx) {}
3513
3514 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3515 switch (TL.getTypeLocClass()) {
3516#define ABSTRACT_TYPELOC(CLASS, PARENT)
3517#define TYPELOC(CLASS, PARENT) \
3518 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3519#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003520 }
John McCall94c3b562010-08-18 09:41:07 +00003521 }
Mike Stump1eb44332009-09-09 15:08:12 +00003522
John McCall94c3b562010-08-18 09:41:07 +00003523 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3524 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3525 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003526 if (!TL.getArg(I))
3527 continue;
3528
John McCall94c3b562010-08-18 09:41:07 +00003529 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3530 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003531 }
John McCall94c3b562010-08-18 09:41:07 +00003532 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003533
John McCall94c3b562010-08-18 09:41:07 +00003534 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3535 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3536 }
Mike Stump1eb44332009-09-09 15:08:12 +00003537
John McCall94c3b562010-08-18 09:41:07 +00003538 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3539 // Visit the type parameters from a permissive context.
3540 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3541 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3542 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3543 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3544 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3545 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003546 }
John McCall94c3b562010-08-18 09:41:07 +00003547 }
Mike Stump1eb44332009-09-09 15:08:12 +00003548
John McCall94c3b562010-08-18 09:41:07 +00003549 // Visit pointee types from a permissive context.
3550#define CheckPolymorphic(Type) \
3551 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3552 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3553 }
3554 CheckPolymorphic(PointerTypeLoc)
3555 CheckPolymorphic(ReferenceTypeLoc)
3556 CheckPolymorphic(MemberPointerTypeLoc)
3557 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003558 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003559
John McCall94c3b562010-08-18 09:41:07 +00003560 /// Handle all the types we haven't given a more specific
3561 /// implementation for above.
3562 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3563 // Every other kind of type that we haven't called out already
3564 // that has an inner type is either (1) sugar or (2) contains that
3565 // inner type in some way as a subobject.
3566 if (TypeLoc Next = TL.getNextTypeLoc())
3567 return Visit(Next, Sel);
3568
3569 // If there's no inner type and we're in a permissive context,
3570 // don't diagnose.
3571 if (Sel == Sema::AbstractNone) return;
3572
3573 // Check whether the type matches the abstract type.
3574 QualType T = TL.getType();
3575 if (T->isArrayType()) {
3576 Sel = Sema::AbstractArrayType;
3577 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003578 }
John McCall94c3b562010-08-18 09:41:07 +00003579 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3580 if (CT != Info.AbstractType) return;
3581
3582 // It matched; do some magic.
3583 if (Sel == Sema::AbstractArrayType) {
3584 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3585 << T << TL.getSourceRange();
3586 } else {
3587 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3588 << Sel << T << TL.getSourceRange();
3589 }
3590 Info.DiagnoseAbstractType();
3591 }
3592};
3593
3594void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3595 Sema::AbstractDiagSelID Sel) {
3596 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3597}
3598
3599}
3600
3601/// Check for invalid uses of an abstract type in a method declaration.
3602static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3603 CXXMethodDecl *MD) {
3604 // No need to do the check on definitions, which require that
3605 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003606 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003607 return;
3608
3609 // For safety's sake, just ignore it if we don't have type source
3610 // information. This should never happen for non-implicit methods,
3611 // but...
3612 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3613 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3614}
3615
3616/// Check for invalid uses of an abstract type within a class definition.
3617static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3618 CXXRecordDecl *RD) {
3619 for (CXXRecordDecl::decl_iterator
3620 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3621 Decl *D = *I;
3622 if (D->isImplicit()) continue;
3623
3624 // Methods and method templates.
3625 if (isa<CXXMethodDecl>(D)) {
3626 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3627 } else if (isa<FunctionTemplateDecl>(D)) {
3628 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3629 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3630
3631 // Fields and static variables.
3632 } else if (isa<FieldDecl>(D)) {
3633 FieldDecl *FD = cast<FieldDecl>(D);
3634 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3635 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3636 } else if (isa<VarDecl>(D)) {
3637 VarDecl *VD = cast<VarDecl>(D);
3638 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3639 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3640
3641 // Nested classes and class templates.
3642 } else if (isa<CXXRecordDecl>(D)) {
3643 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3644 } else if (isa<ClassTemplateDecl>(D)) {
3645 CheckAbstractClassUsage(Info,
3646 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3647 }
3648 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003649}
3650
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003651/// \brief Perform semantic checks on a class definition that has been
3652/// completing, introducing implicitly-declared members, checking for
3653/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003654void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003655 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003656 return;
3657
John McCall94c3b562010-08-18 09:41:07 +00003658 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3659 AbstractUsageInfo Info(*this, Record);
3660 CheckAbstractClassUsage(Info, Record);
3661 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003662
3663 // If this is not an aggregate type and has no user-declared constructor,
3664 // complain about any non-static data members of reference or const scalar
3665 // type, since they will never get initializers.
3666 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003667 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3668 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003669 bool Complained = false;
3670 for (RecordDecl::field_iterator F = Record->field_begin(),
3671 FEnd = Record->field_end();
3672 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003673 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003674 continue;
3675
Douglas Gregor325e5932010-04-15 00:00:53 +00003676 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003677 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003678 if (!Complained) {
3679 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3680 << Record->getTagKind() << Record;
3681 Complained = true;
3682 }
3683
3684 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3685 << F->getType()->isReferenceType()
3686 << F->getDeclName();
3687 }
3688 }
3689 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003690
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003691 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003692 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003693
3694 if (Record->getIdentifier()) {
3695 // C++ [class.mem]p13:
3696 // If T is the name of a class, then each of the following shall have a
3697 // name different from T:
3698 // - every member of every anonymous union that is a member of class T.
3699 //
3700 // C++ [class.mem]p14:
3701 // In addition, if class T has a user-declared constructor (12.1), every
3702 // non-static data member of class T shall have a name different from T.
3703 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003704 R.first != R.second; ++R.first) {
3705 NamedDecl *D = *R.first;
3706 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3707 isa<IndirectFieldDecl>(D)) {
3708 Diag(D->getLocation(), diag::err_member_name_of_class)
3709 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003710 break;
3711 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003712 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003713 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003714
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003715 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003716 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003717 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003718 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003719 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3720 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3721 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003722
3723 // See if a method overloads virtual methods in a base
3724 /// class without overriding any.
3725 if (!Record->isDependentType()) {
3726 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3727 MEnd = Record->method_end();
3728 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003729 if (!(*M)->isStatic())
3730 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003731 }
3732 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003733
Richard Smith9f569cc2011-10-01 02:31:28 +00003734 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3735 // function that is not a constructor declares that member function to be
3736 // const. [...] The class of which that function is a member shall be
3737 // a literal type.
3738 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003739 // If the class has virtual bases, any constexpr members will already have
3740 // been diagnosed by the checks performed on the member declaration, so
3741 // suppress this (less useful) diagnostic.
3742 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3743 !Record->isLiteral() && !Record->getNumVBases()) {
3744 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3745 MEnd = Record->method_end();
3746 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003747 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003748 switch (Record->getTemplateSpecializationKind()) {
3749 case TSK_ImplicitInstantiation:
3750 case TSK_ExplicitInstantiationDeclaration:
3751 case TSK_ExplicitInstantiationDefinition:
3752 // If a template instantiates to a non-literal type, but its members
3753 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003754 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003755 continue;
3756
3757 case TSK_Undeclared:
3758 case TSK_ExplicitSpecialization:
3759 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3760 PDiag(diag::err_constexpr_method_non_literal));
3761 break;
3762 }
3763
3764 // Only produce one error per class.
3765 break;
3766 }
3767 }
3768 }
3769
Sebastian Redlf677ea32011-02-05 19:23:19 +00003770 // Declare inherited constructors. We do this eagerly here because:
3771 // - The standard requires an eager diagnostic for conflicting inherited
3772 // constructors from different classes.
3773 // - The lazy declaration of the other implicit constructors is so as to not
3774 // waste space and performance on classes that are not meant to be
3775 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3776 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003777 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003778
Sean Hunteb88ae52011-05-23 21:07:59 +00003779 if (!Record->isDependentType())
3780 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003781}
3782
3783void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003784 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3785 ME = Record->method_end();
3786 MI != ME; ++MI) {
3787 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3788 switch (getSpecialMember(*MI)) {
3789 case CXXDefaultConstructor:
3790 CheckExplicitlyDefaultedDefaultConstructor(
3791 cast<CXXConstructorDecl>(*MI));
3792 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003793
Sean Huntcb45a0f2011-05-12 22:46:25 +00003794 case CXXDestructor:
3795 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3796 break;
3797
3798 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003799 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3800 break;
3801
Sean Huntcb45a0f2011-05-12 22:46:25 +00003802 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003803 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003804 break;
3805
Sean Hunt82713172011-05-25 23:16:36 +00003806 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003807 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003808 break;
3809
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003810 case CXXMoveAssignment:
3811 CheckExplicitlyDefaultedMoveAssignment(*MI);
3812 break;
3813
3814 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003815 llvm_unreachable("non-special member explicitly defaulted!");
3816 }
Sean Hunt001cad92011-05-10 00:49:42 +00003817 }
3818 }
3819
Sean Hunt001cad92011-05-10 00:49:42 +00003820}
3821
3822void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3823 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3824
3825 // Whether this was the first-declared instance of the constructor.
3826 // This affects whether we implicitly add an exception spec (and, eventually,
3827 // constexpr). It is also ill-formed to explicitly default a constructor such
3828 // that it would be deleted. (C++0x [decl.fct.def.default])
3829 bool First = CD == CD->getCanonicalDecl();
3830
Sean Hunt49634cf2011-05-13 06:10:58 +00003831 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003832 if (CD->getNumParams() != 0) {
3833 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3834 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003835 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003836 }
3837
3838 ImplicitExceptionSpecification Spec
3839 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3840 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003841 if (EPI.ExceptionSpecType == EST_Delayed) {
3842 // Exception specification depends on some deferred part of the class. We'll
3843 // try again when the class's definition has been fully processed.
3844 return;
3845 }
Sean Hunt001cad92011-05-10 00:49:42 +00003846 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3847 *ExceptionType = Context.getFunctionType(
3848 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3849
Richard Smith61802452011-12-22 02:22:31 +00003850 // C++11 [dcl.fct.def.default]p2:
3851 // An explicitly-defaulted function may be declared constexpr only if it
3852 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00003853 // Do not apply this rule to templates, since core issue 1358 makes such
3854 // functions always instantiate to constexpr functions.
3855 if (CD->isConstexpr() &&
3856 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00003857 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3858 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3859 << CXXDefaultConstructor;
3860 HadError = true;
3861 }
3862 }
3863 // and may have an explicit exception-specification only if it is compatible
3864 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003865 if (CtorType->hasExceptionSpec()) {
3866 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003867 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003868 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003869 PDiag(),
3870 ExceptionType, SourceLocation(),
3871 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003872 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003873 }
Richard Smith61802452011-12-22 02:22:31 +00003874 }
3875
3876 // If a function is explicitly defaulted on its first declaration,
3877 if (First) {
3878 // -- it is implicitly considered to be constexpr if the implicit
3879 // definition would be,
3880 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3881
3882 // -- it is implicitly considered to have the same
3883 // exception-specification as if it had been implicitly declared
3884 //
3885 // FIXME: a compatible, but different, explicit exception specification
3886 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003887 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smithe653ba22012-02-26 00:31:33 +00003888
3889 // Such a function is also trivial if the implicitly-declared function
3890 // would have been.
3891 CD->setTrivial(CD->getParent()->hasTrivialDefaultConstructor());
Sean Hunt001cad92011-05-10 00:49:42 +00003892 }
Sean Huntca46d132011-05-12 03:51:48 +00003893
Sean Hunt49634cf2011-05-13 06:10:58 +00003894 if (HadError) {
3895 CD->setInvalidDecl();
3896 return;
3897 }
3898
Sean Hunte16da072011-10-10 06:18:57 +00003899 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003900 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003901 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003902 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003903 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003904 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003905 CD->setInvalidDecl();
3906 }
3907 }
3908}
3909
3910void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3911 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3912
3913 // Whether this was the first-declared instance of the constructor.
3914 bool First = CD == CD->getCanonicalDecl();
3915
3916 bool HadError = false;
3917 if (CD->getNumParams() != 1) {
3918 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3919 << CD->getSourceRange();
3920 HadError = true;
3921 }
3922
3923 ImplicitExceptionSpecification Spec(Context);
3924 bool Const;
3925 llvm::tie(Spec, Const) =
3926 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3927
3928 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3929 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3930 *ExceptionType = Context.getFunctionType(
3931 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3932
3933 // Check for parameter type matching.
3934 // This is a copy ctor so we know it's a cv-qualified reference to T.
3935 QualType ArgType = CtorType->getArgType(0);
3936 if (ArgType->getPointeeType().isVolatileQualified()) {
3937 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3938 HadError = true;
3939 }
3940 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3941 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3942 HadError = true;
3943 }
3944
Richard Smith61802452011-12-22 02:22:31 +00003945 // C++11 [dcl.fct.def.default]p2:
3946 // An explicitly-defaulted function may be declared constexpr only if it
3947 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00003948 // Do not apply this rule to templates, since core issue 1358 makes such
3949 // functions always instantiate to constexpr functions.
3950 if (CD->isConstexpr() &&
3951 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00003952 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3953 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3954 << CXXCopyConstructor;
3955 HadError = true;
3956 }
3957 }
3958 // and may have an explicit exception-specification only if it is compatible
3959 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003960 if (CtorType->hasExceptionSpec()) {
3961 if (CheckEquivalentExceptionSpec(
3962 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003963 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003964 PDiag(),
3965 ExceptionType, SourceLocation(),
3966 CtorType, CD->getLocation())) {
3967 HadError = true;
3968 }
Richard Smith61802452011-12-22 02:22:31 +00003969 }
3970
3971 // If a function is explicitly defaulted on its first declaration,
3972 if (First) {
3973 // -- it is implicitly considered to be constexpr if the implicit
3974 // definition would be,
3975 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3976
3977 // -- it is implicitly considered to have the same
3978 // exception-specification as if it had been implicitly declared, and
3979 //
3980 // FIXME: a compatible, but different, explicit exception specification
3981 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003982 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003983
3984 // -- [...] it shall have the same parameter type as if it had been
3985 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003986 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00003987
3988 // Such a function is also trivial if the implicitly-declared function
3989 // would have been.
3990 CD->setTrivial(CD->getParent()->hasTrivialCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00003991 }
3992
3993 if (HadError) {
3994 CD->setInvalidDecl();
3995 return;
3996 }
3997
Sean Huntc32d6842011-10-11 04:55:36 +00003998 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003999 if (First) {
4000 CD->setDeletedAsWritten();
4001 } else {
4002 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004003 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004004 CD->setInvalidDecl();
4005 }
Sean Huntca46d132011-05-12 03:51:48 +00004006 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004007}
Sean Hunt001cad92011-05-10 00:49:42 +00004008
Sean Hunt2b188082011-05-14 05:23:28 +00004009void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
4010 assert(MD->isExplicitlyDefaulted());
4011
4012 // Whether this was the first-declared instance of the operator
4013 bool First = MD == MD->getCanonicalDecl();
4014
4015 bool HadError = false;
4016 if (MD->getNumParams() != 1) {
4017 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
4018 << MD->getSourceRange();
4019 HadError = true;
4020 }
4021
4022 QualType ReturnType =
4023 MD->getType()->getAs<FunctionType>()->getResultType();
4024 if (!ReturnType->isLValueReferenceType() ||
4025 !Context.hasSameType(
4026 Context.getCanonicalType(ReturnType->getPointeeType()),
4027 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4028 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
4029 HadError = true;
4030 }
4031
4032 ImplicitExceptionSpecification Spec(Context);
4033 bool Const;
4034 llvm::tie(Spec, Const) =
4035 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4036
4037 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4038 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4039 *ExceptionType = Context.getFunctionType(
4040 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4041
Sean Hunt2b188082011-05-14 05:23:28 +00004042 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004043 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00004044 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004045 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00004046 } else {
4047 if (ArgType->getPointeeType().isVolatileQualified()) {
4048 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4049 HadError = true;
4050 }
4051 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4052 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4053 HadError = true;
4054 }
Sean Hunt2b188082011-05-14 05:23:28 +00004055 }
Sean Huntbe631222011-05-17 20:44:43 +00004056
Sean Hunt2b188082011-05-14 05:23:28 +00004057 if (OperType->getTypeQuals()) {
4058 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4059 HadError = true;
4060 }
4061
4062 if (OperType->hasExceptionSpec()) {
4063 if (CheckEquivalentExceptionSpec(
4064 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004065 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004066 PDiag(),
4067 ExceptionType, SourceLocation(),
4068 OperType, MD->getLocation())) {
4069 HadError = true;
4070 }
Richard Smith61802452011-12-22 02:22:31 +00004071 }
4072 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004073 // We set the declaration to have the computed exception spec here.
4074 // We duplicate the one parameter type.
4075 EPI.RefQualifier = OperType->getRefQualifier();
4076 EPI.ExtInfo = OperType->getExtInfo();
4077 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004078
4079 // Such a function is also trivial if the implicitly-declared function
4080 // would have been.
4081 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
Sean Hunt2b188082011-05-14 05:23:28 +00004082 }
4083
4084 if (HadError) {
4085 MD->setInvalidDecl();
4086 return;
4087 }
4088
Richard Smith7d5088a2012-02-18 02:02:13 +00004089 if (ShouldDeleteSpecialMember(MD, CXXCopyAssignment)) {
Sean Hunt2b188082011-05-14 05:23:28 +00004090 if (First) {
4091 MD->setDeletedAsWritten();
4092 } else {
4093 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004094 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004095 MD->setInvalidDecl();
4096 }
4097 }
4098}
4099
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004100void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4101 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4102
4103 // Whether this was the first-declared instance of the constructor.
4104 bool First = CD == CD->getCanonicalDecl();
4105
4106 bool HadError = false;
4107 if (CD->getNumParams() != 1) {
4108 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4109 << CD->getSourceRange();
4110 HadError = true;
4111 }
4112
4113 ImplicitExceptionSpecification Spec(
4114 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4115
4116 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4117 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4118 *ExceptionType = Context.getFunctionType(
4119 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4120
4121 // Check for parameter type matching.
4122 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4123 QualType ArgType = CtorType->getArgType(0);
4124 if (ArgType->getPointeeType().isVolatileQualified()) {
4125 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4126 HadError = true;
4127 }
4128 if (ArgType->getPointeeType().isConstQualified()) {
4129 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4130 HadError = true;
4131 }
4132
Richard Smith61802452011-12-22 02:22:31 +00004133 // C++11 [dcl.fct.def.default]p2:
4134 // An explicitly-defaulted function may be declared constexpr only if it
4135 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00004136 // Do not apply this rule to templates, since core issue 1358 makes such
4137 // functions always instantiate to constexpr functions.
4138 if (CD->isConstexpr() &&
4139 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00004140 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4141 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4142 << CXXMoveConstructor;
4143 HadError = true;
4144 }
4145 }
4146 // and may have an explicit exception-specification only if it is compatible
4147 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004148 if (CtorType->hasExceptionSpec()) {
4149 if (CheckEquivalentExceptionSpec(
4150 PDiag(diag::err_incorrect_defaulted_exception_spec)
4151 << CXXMoveConstructor,
4152 PDiag(),
4153 ExceptionType, SourceLocation(),
4154 CtorType, CD->getLocation())) {
4155 HadError = true;
4156 }
Richard Smith61802452011-12-22 02:22:31 +00004157 }
4158
4159 // If a function is explicitly defaulted on its first declaration,
4160 if (First) {
4161 // -- it is implicitly considered to be constexpr if the implicit
4162 // definition would be,
4163 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4164
4165 // -- it is implicitly considered to have the same
4166 // exception-specification as if it had been implicitly declared, and
4167 //
4168 // FIXME: a compatible, but different, explicit exception specification
4169 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004170 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004171
4172 // -- [...] it shall have the same parameter type as if it had been
4173 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004174 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004175
4176 // Such a function is also trivial if the implicitly-declared function
4177 // would have been.
4178 CD->setTrivial(CD->getParent()->hasTrivialMoveConstructor());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004179 }
4180
4181 if (HadError) {
4182 CD->setInvalidDecl();
4183 return;
4184 }
4185
Sean Hunt769bb2d2011-10-11 06:43:29 +00004186 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004187 if (First) {
4188 CD->setDeletedAsWritten();
4189 } else {
4190 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4191 << CXXMoveConstructor;
4192 CD->setInvalidDecl();
4193 }
4194 }
4195}
4196
4197void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4198 assert(MD->isExplicitlyDefaulted());
4199
4200 // Whether this was the first-declared instance of the operator
4201 bool First = MD == MD->getCanonicalDecl();
4202
4203 bool HadError = false;
4204 if (MD->getNumParams() != 1) {
4205 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4206 << MD->getSourceRange();
4207 HadError = true;
4208 }
4209
4210 QualType ReturnType =
4211 MD->getType()->getAs<FunctionType>()->getResultType();
4212 if (!ReturnType->isLValueReferenceType() ||
4213 !Context.hasSameType(
4214 Context.getCanonicalType(ReturnType->getPointeeType()),
4215 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4216 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4217 HadError = true;
4218 }
4219
4220 ImplicitExceptionSpecification Spec(
4221 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4222
4223 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4224 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4225 *ExceptionType = Context.getFunctionType(
4226 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4227
4228 QualType ArgType = OperType->getArgType(0);
4229 if (!ArgType->isRValueReferenceType()) {
4230 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4231 HadError = true;
4232 } else {
4233 if (ArgType->getPointeeType().isVolatileQualified()) {
4234 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4235 HadError = true;
4236 }
4237 if (ArgType->getPointeeType().isConstQualified()) {
4238 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4239 HadError = true;
4240 }
4241 }
4242
4243 if (OperType->getTypeQuals()) {
4244 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4245 HadError = true;
4246 }
4247
4248 if (OperType->hasExceptionSpec()) {
4249 if (CheckEquivalentExceptionSpec(
4250 PDiag(diag::err_incorrect_defaulted_exception_spec)
4251 << CXXMoveAssignment,
4252 PDiag(),
4253 ExceptionType, SourceLocation(),
4254 OperType, MD->getLocation())) {
4255 HadError = true;
4256 }
Richard Smith61802452011-12-22 02:22:31 +00004257 }
4258 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004259 // We set the declaration to have the computed exception spec here.
4260 // We duplicate the one parameter type.
4261 EPI.RefQualifier = OperType->getRefQualifier();
4262 EPI.ExtInfo = OperType->getExtInfo();
4263 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004264
4265 // Such a function is also trivial if the implicitly-declared function
4266 // would have been.
4267 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004268 }
4269
4270 if (HadError) {
4271 MD->setInvalidDecl();
4272 return;
4273 }
4274
Richard Smith7d5088a2012-02-18 02:02:13 +00004275 if (ShouldDeleteSpecialMember(MD, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004276 if (First) {
4277 MD->setDeletedAsWritten();
4278 } else {
4279 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4280 << CXXMoveAssignment;
4281 MD->setInvalidDecl();
4282 }
4283 }
4284}
4285
Sean Huntcb45a0f2011-05-12 22:46:25 +00004286void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4287 assert(DD->isExplicitlyDefaulted());
4288
4289 // Whether this was the first-declared instance of the destructor.
4290 bool First = DD == DD->getCanonicalDecl();
4291
4292 ImplicitExceptionSpecification Spec
4293 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4294 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4295 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4296 *ExceptionType = Context.getFunctionType(
4297 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4298
4299 if (DtorType->hasExceptionSpec()) {
4300 if (CheckEquivalentExceptionSpec(
4301 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004302 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004303 PDiag(),
4304 ExceptionType, SourceLocation(),
4305 DtorType, DD->getLocation())) {
4306 DD->setInvalidDecl();
4307 return;
4308 }
Richard Smith61802452011-12-22 02:22:31 +00004309 }
4310 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004311 // We set the declaration to have the computed exception spec here.
4312 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004313 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004314 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004315
4316 // Such a function is also trivial if the implicitly-declared function
4317 // would have been.
4318 DD->setTrivial(DD->getParent()->hasTrivialDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00004319 }
4320
Richard Smith7d5088a2012-02-18 02:02:13 +00004321 if (ShouldDeleteSpecialMember(DD, CXXDestructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004322 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004323 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004324 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004325 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004326 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004327 DD->setInvalidDecl();
4328 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004329 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004330}
4331
Richard Smith7d5088a2012-02-18 02:02:13 +00004332namespace {
4333struct SpecialMemberDeletionInfo {
4334 Sema &S;
4335 CXXMethodDecl *MD;
4336 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004337 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004338
4339 // Properties of the special member, computed for convenience.
4340 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4341 SourceLocation Loc;
4342
4343 bool AllFieldsAreConst;
4344
4345 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004346 Sema::CXXSpecialMember CSM, bool Diagnose)
4347 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004348 IsConstructor(false), IsAssignment(false), IsMove(false),
4349 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4350 AllFieldsAreConst(true) {
4351 switch (CSM) {
4352 case Sema::CXXDefaultConstructor:
4353 case Sema::CXXCopyConstructor:
4354 IsConstructor = true;
4355 break;
4356 case Sema::CXXMoveConstructor:
4357 IsConstructor = true;
4358 IsMove = true;
4359 break;
4360 case Sema::CXXCopyAssignment:
4361 IsAssignment = true;
4362 break;
4363 case Sema::CXXMoveAssignment:
4364 IsAssignment = true;
4365 IsMove = true;
4366 break;
4367 case Sema::CXXDestructor:
4368 break;
4369 case Sema::CXXInvalid:
4370 llvm_unreachable("invalid special member kind");
4371 }
4372
4373 if (MD->getNumParams()) {
4374 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4375 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4376 }
4377 }
4378
4379 bool inUnion() const { return MD->getParent()->isUnion(); }
4380
4381 /// Look up the corresponding special member in the given class.
4382 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class) {
4383 unsigned TQ = MD->getTypeQualifiers();
4384 return S.LookupSpecialMember(Class, CSM, ConstArg, VolatileArg,
4385 MD->getRefQualifier() == RQ_RValue,
4386 TQ & Qualifiers::Const,
4387 TQ & Qualifiers::Volatile);
4388 }
4389
Richard Smith6c4c36c2012-03-30 20:53:28 +00004390 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004391
Richard Smith6c4c36c2012-03-30 20:53:28 +00004392 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004393 bool shouldDeleteForField(FieldDecl *FD);
4394 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004395
4396 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj);
4397 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4398 Sema::SpecialMemberOverloadResult *SMOR,
4399 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004400
4401 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004402};
4403}
4404
John McCall12d8d802012-04-09 20:53:23 +00004405/// Is the given special member inaccessible when used on the given
4406/// sub-object.
4407bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4408 CXXMethodDecl *target) {
4409 /// If we're operating on a base class, the object type is the
4410 /// type of this special member.
4411 QualType objectTy;
4412 AccessSpecifier access = target->getAccess();;
4413 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4414 objectTy = S.Context.getTypeDeclType(MD->getParent());
4415 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4416
4417 // If we're operating on a field, the object type is the type of the field.
4418 } else {
4419 objectTy = S.Context.getTypeDeclType(target->getParent());
4420 }
4421
4422 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4423}
4424
Richard Smith6c4c36c2012-03-30 20:53:28 +00004425/// Check whether we should delete a special member due to the implicit
4426/// definition containing a call to a special member of a subobject.
4427bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4428 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4429 bool IsDtorCallInCtor) {
4430 CXXMethodDecl *Decl = SMOR->getMethod();
4431 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4432
4433 int DiagKind = -1;
4434
4435 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4436 DiagKind = !Decl ? 0 : 1;
4437 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4438 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004439 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004440 DiagKind = 3;
4441 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4442 !Decl->isTrivial()) {
4443 // A member of a union must have a trivial corresponding special member.
4444 // As a weird special case, a destructor call from a union's constructor
4445 // must be accessible and non-deleted, but need not be trivial. Such a
4446 // destructor is never actually called, but is semantically checked as
4447 // if it were.
4448 DiagKind = 4;
4449 }
4450
4451 if (DiagKind == -1)
4452 return false;
4453
4454 if (Diagnose) {
4455 if (Field) {
4456 S.Diag(Field->getLocation(),
4457 diag::note_deleted_special_member_class_subobject)
4458 << CSM << MD->getParent() << /*IsField*/true
4459 << Field << DiagKind << IsDtorCallInCtor;
4460 } else {
4461 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4462 S.Diag(Base->getLocStart(),
4463 diag::note_deleted_special_member_class_subobject)
4464 << CSM << MD->getParent() << /*IsField*/false
4465 << Base->getType() << DiagKind << IsDtorCallInCtor;
4466 }
4467
4468 if (DiagKind == 1)
4469 S.NoteDeletedFunction(Decl);
4470 // FIXME: Explain inaccessibility if DiagKind == 3.
4471 }
4472
4473 return true;
4474}
4475
Richard Smith9a561d52012-02-26 09:11:52 +00004476/// Check whether we should delete a special member function due to having a
4477/// direct or virtual base class or static data member of class type M.
4478bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith6c4c36c2012-03-30 20:53:28 +00004479 CXXRecordDecl *Class, Subobject Subobj) {
4480 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004481
4482 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004483 // -- any direct or virtual base class, or non-static data member with no
4484 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004485 // either M has no default constructor or overload resolution as applied
4486 // to M's default constructor results in an ambiguity or in a function
4487 // that is deleted or inaccessible
4488 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4489 // -- a direct or virtual base class B that cannot be copied/moved because
4490 // overload resolution, as applied to B's corresponding special member,
4491 // results in an ambiguity or a function that is deleted or inaccessible
4492 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004493 // C++11 [class.dtor]p5:
4494 // -- any direct or virtual base class [...] has a type with a destructor
4495 // that is deleted or inaccessible
4496 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004497 Field && Field->hasInClassInitializer()) &&
4498 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class), false))
4499 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004500
Richard Smith6c4c36c2012-03-30 20:53:28 +00004501 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4502 // -- any direct or virtual base class or non-static data member has a
4503 // type with a destructor that is deleted or inaccessible
4504 if (IsConstructor) {
4505 Sema::SpecialMemberOverloadResult *SMOR =
4506 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4507 false, false, false, false, false);
4508 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4509 return true;
4510 }
4511
Richard Smith9a561d52012-02-26 09:11:52 +00004512 return false;
4513}
4514
4515/// Check whether we should delete a special member function due to the class
4516/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004517bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004518 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4519 return shouldDeleteForClassSubobject(BaseClass, Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004520}
4521
4522/// Check whether we should delete a special member function due to the class
4523/// having a particular non-static data member.
4524bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4525 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4526 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4527
4528 if (CSM == Sema::CXXDefaultConstructor) {
4529 // For a default constructor, all references must be initialized in-class
4530 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004531 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4532 if (Diagnose)
4533 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4534 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004535 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004536 }
Richard Smith79363f52012-02-27 06:07:25 +00004537 // C++11 [class.ctor]p5: any non-variant non-static data member of
4538 // const-qualified type (or array thereof) with no
4539 // brace-or-equal-initializer does not have a user-provided default
4540 // constructor.
4541 if (!inUnion() && FieldType.isConstQualified() &&
4542 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004543 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4544 if (Diagnose)
4545 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4546 << MD->getParent() << FD << FieldType << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004547 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004548 }
4549
4550 if (inUnion() && !FieldType.isConstQualified())
4551 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004552 } else if (CSM == Sema::CXXCopyConstructor) {
4553 // For a copy constructor, data members must not be of rvalue reference
4554 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004555 if (FieldType->isRValueReferenceType()) {
4556 if (Diagnose)
4557 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4558 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004559 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004560 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004561 } else if (IsAssignment) {
4562 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004563 if (FieldType->isReferenceType()) {
4564 if (Diagnose)
4565 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4566 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004567 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004568 }
4569 if (!FieldRecord && FieldType.isConstQualified()) {
4570 // C++11 [class.copy]p23:
4571 // -- a non-static data member of const non-class type (or array thereof)
4572 if (Diagnose)
4573 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4574 << IsMove << MD->getParent() << FD << FieldType << /*Const*/1;
4575 return true;
4576 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004577 }
4578
4579 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004580 // Some additional restrictions exist on the variant members.
4581 if (!inUnion() && FieldRecord->isUnion() &&
4582 FieldRecord->isAnonymousStructOrUnion()) {
4583 bool AllVariantFieldsAreConst = true;
4584
Richard Smithdf8dc862012-03-29 19:00:10 +00004585 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004586 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4587 UE = FieldRecord->field_end();
4588 UI != UE; ++UI) {
4589 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004590
4591 if (!UnionFieldType.isConstQualified())
4592 AllVariantFieldsAreConst = false;
4593
Richard Smith9a561d52012-02-26 09:11:52 +00004594 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4595 if (UnionFieldRecord &&
4596 shouldDeleteForClassSubobject(UnionFieldRecord, *UI))
4597 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004598 }
4599
4600 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004601 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004602 FieldRecord->field_begin() != FieldRecord->field_end()) {
4603 if (Diagnose)
4604 S.Diag(FieldRecord->getLocation(),
4605 diag::note_deleted_default_ctor_all_const)
4606 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004607 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004608 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004609
Richard Smithdf8dc862012-03-29 19:00:10 +00004610 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004611 // This is technically non-conformant, but sanity demands it.
4612 return false;
4613 }
4614
Richard Smithdf8dc862012-03-29 19:00:10 +00004615 if (shouldDeleteForClassSubobject(FieldRecord, FD))
4616 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004617 }
4618
4619 return false;
4620}
4621
4622/// C++11 [class.ctor] p5:
4623/// A defaulted default constructor for a class X is defined as deleted if
4624/// X is a union and all of its variant members are of const-qualified type.
4625bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004626 // This is a silly definition, because it gives an empty union a deleted
4627 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004628 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4629 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4630 if (Diagnose)
4631 S.Diag(MD->getParent()->getLocation(),
4632 diag::note_deleted_default_ctor_all_const)
4633 << MD->getParent() << /*not anonymous union*/0;
4634 return true;
4635 }
4636 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004637}
4638
4639/// Determine whether a defaulted special member function should be defined as
4640/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4641/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004642bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4643 bool Diagnose) {
Sean Hunte16da072011-10-10 06:18:57 +00004644 assert(!MD->isInvalidDecl());
4645 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004646 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004647 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004648 return false;
4649
Richard Smith7d5088a2012-02-18 02:02:13 +00004650 // C++11 [expr.lambda.prim]p19:
4651 // The closure type associated with a lambda-expression has a
4652 // deleted (8.4.3) default constructor and a deleted copy
4653 // assignment operator.
4654 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004655 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4656 if (Diagnose)
4657 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004658 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004659 }
4660
Richard Smith5bdaac52012-04-02 20:59:25 +00004661 // For an anonymous struct or union, the copy and assignment special members
4662 // will never be used, so skip the check. For an anonymous union declared at
4663 // namespace scope, the constructor and destructor are used.
4664 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4665 RD->isAnonymousStructOrUnion())
4666 return false;
4667
Richard Smith6c4c36c2012-03-30 20:53:28 +00004668 // C++11 [class.copy]p7, p18:
4669 // If the class definition declares a move constructor or move assignment
4670 // operator, an implicitly declared copy constructor or copy assignment
4671 // operator is defined as deleted.
4672 if (MD->isImplicit() &&
4673 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4674 CXXMethodDecl *UserDeclaredMove = 0;
4675
4676 // In Microsoft mode, a user-declared move only causes the deletion of the
4677 // corresponding copy operation, not both copy operations.
4678 if (RD->hasUserDeclaredMoveConstructor() &&
4679 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4680 if (!Diagnose) return true;
4681 UserDeclaredMove = RD->getMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00004682 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004683 } else if (RD->hasUserDeclaredMoveAssignment() &&
4684 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4685 if (!Diagnose) return true;
4686 UserDeclaredMove = RD->getMoveAssignmentOperator();
Richard Smith1c931be2012-04-02 18:40:40 +00004687 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004688 }
4689
4690 if (UserDeclaredMove) {
4691 Diag(UserDeclaredMove->getLocation(),
4692 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004693 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004694 << UserDeclaredMove->isMoveAssignmentOperator();
4695 return true;
4696 }
4697 }
Sean Hunte16da072011-10-10 06:18:57 +00004698
Richard Smith5bdaac52012-04-02 20:59:25 +00004699 // Do access control from the special member function
4700 ContextRAII MethodContext(*this, MD);
4701
Richard Smith9a561d52012-02-26 09:11:52 +00004702 // C++11 [class.dtor]p5:
4703 // -- for a virtual destructor, lookup of the non-array deallocation function
4704 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004705 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004706 FunctionDecl *OperatorDelete = 0;
4707 DeclarationName Name =
4708 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4709 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004710 OperatorDelete, false)) {
4711 if (Diagnose)
4712 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004713 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004714 }
Richard Smith9a561d52012-02-26 09:11:52 +00004715 }
4716
Richard Smith6c4c36c2012-03-30 20:53:28 +00004717 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004718
Sean Huntcdee3fe2011-05-11 22:34:38 +00004719 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004720 BE = RD->bases_end(); BI != BE; ++BI)
4721 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004722 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004723 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004724
4725 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004726 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004727 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004728 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004729
4730 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004731 FE = RD->field_end(); FI != FE; ++FI)
4732 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4733 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004734 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004735
Richard Smith7d5088a2012-02-18 02:02:13 +00004736 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004737 return true;
4738
4739 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004740}
4741
4742/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004743namespace {
4744 struct FindHiddenVirtualMethodData {
4745 Sema *S;
4746 CXXMethodDecl *Method;
4747 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004748 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004749 };
4750}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004751
4752/// \brief Member lookup function that determines whether a given C++
4753/// method overloads virtual methods in a base class without overriding any,
4754/// to be used with CXXRecordDecl::lookupInBases().
4755static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4756 CXXBasePath &Path,
4757 void *UserData) {
4758 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4759
4760 FindHiddenVirtualMethodData &Data
4761 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4762
4763 DeclarationName Name = Data.Method->getDeclName();
4764 assert(Name.getNameKind() == DeclarationName::Identifier);
4765
4766 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004767 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004768 for (Path.Decls = BaseRecord->lookup(Name);
4769 Path.Decls.first != Path.Decls.second;
4770 ++Path.Decls.first) {
4771 NamedDecl *D = *Path.Decls.first;
4772 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004773 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004774 foundSameNameMethod = true;
4775 // Interested only in hidden virtual methods.
4776 if (!MD->isVirtual())
4777 continue;
4778 // If the method we are checking overrides a method from its base
4779 // don't warn about the other overloaded methods.
4780 if (!Data.S->IsOverload(Data.Method, MD, false))
4781 return true;
4782 // Collect the overload only if its hidden.
4783 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4784 overloadedMethods.push_back(MD);
4785 }
4786 }
4787
4788 if (foundSameNameMethod)
4789 Data.OverloadedMethods.append(overloadedMethods.begin(),
4790 overloadedMethods.end());
4791 return foundSameNameMethod;
4792}
4793
4794/// \brief See if a method overloads virtual methods in a base class without
4795/// overriding any.
4796void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4797 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004798 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004799 return;
4800 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4801 return;
4802
4803 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4804 /*bool RecordPaths=*/false,
4805 /*bool DetectVirtual=*/false);
4806 FindHiddenVirtualMethodData Data;
4807 Data.Method = MD;
4808 Data.S = this;
4809
4810 // Keep the base methods that were overriden or introduced in the subclass
4811 // by 'using' in a set. A base method not in this set is hidden.
4812 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4813 res.first != res.second; ++res.first) {
4814 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4815 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4816 E = MD->end_overridden_methods();
4817 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004818 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004819 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4820 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004821 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004822 }
4823
4824 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4825 !Data.OverloadedMethods.empty()) {
4826 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4827 << MD << (Data.OverloadedMethods.size() > 1);
4828
4829 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4830 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4831 Diag(overloadedMD->getLocation(),
4832 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4833 }
4834 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004835}
4836
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004837void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004838 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004839 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004840 SourceLocation RBrac,
4841 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004842 if (!TagDecl)
4843 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004844
Douglas Gregor42af25f2009-05-11 19:58:34 +00004845 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004846
David Blaikie77b6de02011-09-22 02:58:26 +00004847 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004848 // strict aliasing violation!
4849 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004850 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004851
Douglas Gregor23c94db2010-07-02 17:43:08 +00004852 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004853 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004854}
4855
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004856/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4857/// special functions, such as the default constructor, copy
4858/// constructor, or destructor, to the given C++ class (C++
4859/// [special]p1). This routine can only be executed just before the
4860/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004861void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004862 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004863 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004864
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004865 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004866 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004867
David Blaikie4e4d0842012-03-11 07:00:24 +00004868 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
Richard Smithb701d3d2011-12-24 21:56:24 +00004869 ++ASTContext::NumImplicitMoveConstructors;
4870
Douglas Gregora376d102010-07-02 21:50:04 +00004871 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4872 ++ASTContext::NumImplicitCopyAssignmentOperators;
4873
4874 // If we have a dynamic class, then the copy assignment operator may be
4875 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4876 // it shows up in the right place in the vtable and that we diagnose
4877 // problems with the implicit exception specification.
4878 if (ClassDecl->isDynamicClass())
4879 DeclareImplicitCopyAssignment(ClassDecl);
4880 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004881
Richard Smith1c931be2012-04-02 18:40:40 +00004882 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00004883 ++ASTContext::NumImplicitMoveAssignmentOperators;
4884
4885 // Likewise for the move assignment operator.
4886 if (ClassDecl->isDynamicClass())
4887 DeclareImplicitMoveAssignment(ClassDecl);
4888 }
4889
Douglas Gregor4923aa22010-07-02 20:37:36 +00004890 if (!ClassDecl->hasUserDeclaredDestructor()) {
4891 ++ASTContext::NumImplicitDestructors;
4892
4893 // If we have a dynamic class, then the destructor may be virtual, so we
4894 // have to declare the destructor immediately. This ensures that, e.g., it
4895 // shows up in the right place in the vtable and that we diagnose problems
4896 // with the implicit exception specification.
4897 if (ClassDecl->isDynamicClass())
4898 DeclareImplicitDestructor(ClassDecl);
4899 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004900}
4901
Francois Pichet8387e2a2011-04-22 22:18:13 +00004902void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4903 if (!D)
4904 return;
4905
4906 int NumParamList = D->getNumTemplateParameterLists();
4907 for (int i = 0; i < NumParamList; i++) {
4908 TemplateParameterList* Params = D->getTemplateParameterList(i);
4909 for (TemplateParameterList::iterator Param = Params->begin(),
4910 ParamEnd = Params->end();
4911 Param != ParamEnd; ++Param) {
4912 NamedDecl *Named = cast<NamedDecl>(*Param);
4913 if (Named->getDeclName()) {
4914 S->AddDecl(Named);
4915 IdResolver.AddDecl(Named);
4916 }
4917 }
4918 }
4919}
4920
John McCalld226f652010-08-21 09:40:31 +00004921void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004922 if (!D)
4923 return;
4924
4925 TemplateParameterList *Params = 0;
4926 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4927 Params = Template->getTemplateParameters();
4928 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4929 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4930 Params = PartialSpec->getTemplateParameters();
4931 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004932 return;
4933
Douglas Gregor6569d682009-05-27 23:11:45 +00004934 for (TemplateParameterList::iterator Param = Params->begin(),
4935 ParamEnd = Params->end();
4936 Param != ParamEnd; ++Param) {
4937 NamedDecl *Named = cast<NamedDecl>(*Param);
4938 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004939 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004940 IdResolver.AddDecl(Named);
4941 }
4942 }
4943}
4944
John McCalld226f652010-08-21 09:40:31 +00004945void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004946 if (!RecordD) return;
4947 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004948 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004949 PushDeclContext(S, Record);
4950}
4951
John McCalld226f652010-08-21 09:40:31 +00004952void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004953 if (!RecordD) return;
4954 PopDeclContext();
4955}
4956
Douglas Gregor72b505b2008-12-16 21:30:33 +00004957/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4958/// parsing a top-level (non-nested) C++ class, and we are now
4959/// parsing those parts of the given Method declaration that could
4960/// not be parsed earlier (C++ [class.mem]p2), such as default
4961/// arguments. This action should enter the scope of the given
4962/// Method declaration as if we had just parsed the qualified method
4963/// name. However, it should not bring the parameters into scope;
4964/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004965void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004966}
4967
4968/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4969/// C++ method declaration. We're (re-)introducing the given
4970/// function parameter into scope for use in parsing later parts of
4971/// the method declaration. For example, we could see an
4972/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004973void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004974 if (!ParamD)
4975 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004976
John McCalld226f652010-08-21 09:40:31 +00004977 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004978
4979 // If this parameter has an unparsed default argument, clear it out
4980 // to make way for the parsed default argument.
4981 if (Param->hasUnparsedDefaultArg())
4982 Param->setDefaultArg(0);
4983
John McCalld226f652010-08-21 09:40:31 +00004984 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004985 if (Param->getDeclName())
4986 IdResolver.AddDecl(Param);
4987}
4988
4989/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4990/// processing the delayed method declaration for Method. The method
4991/// declaration is now considered finished. There may be a separate
4992/// ActOnStartOfFunctionDef action later (not necessarily
4993/// immediately!) for this method, if it was also defined inside the
4994/// class body.
John McCalld226f652010-08-21 09:40:31 +00004995void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004996 if (!MethodD)
4997 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004998
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004999 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005000
John McCalld226f652010-08-21 09:40:31 +00005001 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005002
5003 // Now that we have our default arguments, check the constructor
5004 // again. It could produce additional diagnostics or affect whether
5005 // the class has implicitly-declared destructors, among other
5006 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005007 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5008 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005009
5010 // Check the default arguments, which we may have added.
5011 if (!Method->isInvalidDecl())
5012 CheckCXXDefaultArguments(Method);
5013}
5014
Douglas Gregor42a552f2008-11-05 20:51:48 +00005015/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005016/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005017/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005018/// emit diagnostics and set the invalid bit to true. In any case, the type
5019/// will be updated to reflect a well-formed type for the constructor and
5020/// returned.
5021QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005022 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005023 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005024
5025 // C++ [class.ctor]p3:
5026 // A constructor shall not be virtual (10.3) or static (9.4). A
5027 // constructor can be invoked for a const, volatile or const
5028 // volatile object. A constructor shall not be declared const,
5029 // volatile, or const volatile (9.3.2).
5030 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005031 if (!D.isInvalidType())
5032 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5033 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5034 << SourceRange(D.getIdentifierLoc());
5035 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005036 }
John McCalld931b082010-08-26 03:08:43 +00005037 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005038 if (!D.isInvalidType())
5039 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5040 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5041 << SourceRange(D.getIdentifierLoc());
5042 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005043 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005044 }
Mike Stump1eb44332009-09-09 15:08:12 +00005045
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005046 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005047 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005048 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005049 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5050 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005051 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005052 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5053 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005054 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005055 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5056 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005057 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005058 }
Mike Stump1eb44332009-09-09 15:08:12 +00005059
Douglas Gregorc938c162011-01-26 05:01:58 +00005060 // C++0x [class.ctor]p4:
5061 // A constructor shall not be declared with a ref-qualifier.
5062 if (FTI.hasRefQualifier()) {
5063 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5064 << FTI.RefQualifierIsLValueRef
5065 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5066 D.setInvalidType();
5067 }
5068
Douglas Gregor42a552f2008-11-05 20:51:48 +00005069 // Rebuild the function type "R" without any type qualifiers (in
5070 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005071 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005072 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005073 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5074 return R;
5075
5076 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5077 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005078 EPI.RefQualifier = RQ_None;
5079
Chris Lattner65401802009-04-25 08:28:21 +00005080 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005081 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005082}
5083
Douglas Gregor72b505b2008-12-16 21:30:33 +00005084/// CheckConstructor - Checks a fully-formed constructor for
5085/// well-formedness, issuing any diagnostics required. Returns true if
5086/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005087void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005088 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005089 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5090 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005091 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005092
5093 // C++ [class.copy]p3:
5094 // A declaration of a constructor for a class X is ill-formed if
5095 // its first parameter is of type (optionally cv-qualified) X and
5096 // either there are no other parameters or else all other
5097 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005098 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005099 ((Constructor->getNumParams() == 1) ||
5100 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005101 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5102 Constructor->getTemplateSpecializationKind()
5103 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005104 QualType ParamType = Constructor->getParamDecl(0)->getType();
5105 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5106 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005107 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005108 const char *ConstRef
5109 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5110 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005111 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005112 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005113
5114 // FIXME: Rather that making the constructor invalid, we should endeavor
5115 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005116 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005117 }
5118 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005119}
5120
John McCall15442822010-08-04 01:04:25 +00005121/// CheckDestructor - Checks a fully-formed destructor definition for
5122/// well-formedness, issuing any diagnostics required. Returns true
5123/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005124bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005125 CXXRecordDecl *RD = Destructor->getParent();
5126
5127 if (Destructor->isVirtual()) {
5128 SourceLocation Loc;
5129
5130 if (!Destructor->isImplicit())
5131 Loc = Destructor->getLocation();
5132 else
5133 Loc = RD->getLocation();
5134
5135 // If we have a virtual destructor, look up the deallocation function
5136 FunctionDecl *OperatorDelete = 0;
5137 DeclarationName Name =
5138 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005139 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005140 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005141
Eli Friedman5f2987c2012-02-02 03:46:19 +00005142 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005143
5144 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005145 }
Anders Carlsson37909802009-11-30 21:24:50 +00005146
5147 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005148}
5149
Mike Stump1eb44332009-09-09 15:08:12 +00005150static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005151FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5152 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5153 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005154 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005155}
5156
Douglas Gregor42a552f2008-11-05 20:51:48 +00005157/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5158/// the well-formednes of the destructor declarator @p D with type @p
5159/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005160/// emit diagnostics and set the declarator to invalid. Even if this happens,
5161/// will be updated to reflect a well-formed type for the destructor and
5162/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005163QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005164 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005165 // C++ [class.dtor]p1:
5166 // [...] A typedef-name that names a class is a class-name
5167 // (7.1.3); however, a typedef-name that names a class shall not
5168 // be used as the identifier in the declarator for a destructor
5169 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005170 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005171 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005172 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005173 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005174 else if (const TemplateSpecializationType *TST =
5175 DeclaratorType->getAs<TemplateSpecializationType>())
5176 if (TST->isTypeAlias())
5177 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5178 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005179
5180 // C++ [class.dtor]p2:
5181 // A destructor is used to destroy objects of its class type. A
5182 // destructor takes no parameters, and no return type can be
5183 // specified for it (not even void). The address of a destructor
5184 // shall not be taken. A destructor shall not be static. A
5185 // destructor can be invoked for a const, volatile or const
5186 // volatile object. A destructor shall not be declared const,
5187 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005188 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005189 if (!D.isInvalidType())
5190 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5191 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005192 << SourceRange(D.getIdentifierLoc())
5193 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5194
John McCalld931b082010-08-26 03:08:43 +00005195 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005196 }
Chris Lattner65401802009-04-25 08:28:21 +00005197 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005198 // Destructors don't have return types, but the parser will
5199 // happily parse something like:
5200 //
5201 // class X {
5202 // float ~X();
5203 // };
5204 //
5205 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005206 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5207 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5208 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005209 }
Mike Stump1eb44332009-09-09 15:08:12 +00005210
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005211 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005212 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005213 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005214 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5215 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005216 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005217 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5218 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005219 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005220 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5221 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005222 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005223 }
5224
Douglas Gregorc938c162011-01-26 05:01:58 +00005225 // C++0x [class.dtor]p2:
5226 // A destructor shall not be declared with a ref-qualifier.
5227 if (FTI.hasRefQualifier()) {
5228 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5229 << FTI.RefQualifierIsLValueRef
5230 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5231 D.setInvalidType();
5232 }
5233
Douglas Gregor42a552f2008-11-05 20:51:48 +00005234 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005235 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005236 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5237
5238 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005239 FTI.freeArgs();
5240 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005241 }
5242
Mike Stump1eb44332009-09-09 15:08:12 +00005243 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005244 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005245 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005246 D.setInvalidType();
5247 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005248
5249 // Rebuild the function type "R" without any type qualifiers or
5250 // parameters (in case any of the errors above fired) and with
5251 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005252 // types.
John McCalle23cf432010-12-14 08:05:40 +00005253 if (!D.isInvalidType())
5254 return R;
5255
Douglas Gregord92ec472010-07-01 05:10:53 +00005256 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005257 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5258 EPI.Variadic = false;
5259 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005260 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005261 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005262}
5263
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005264/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5265/// well-formednes of the conversion function declarator @p D with
5266/// type @p R. If there are any errors in the declarator, this routine
5267/// will emit diagnostics and return true. Otherwise, it will return
5268/// false. Either way, the type @p R will be updated to reflect a
5269/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005270void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005271 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005272 // C++ [class.conv.fct]p1:
5273 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005274 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005275 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005276 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005277 if (!D.isInvalidType())
5278 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5279 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5280 << SourceRange(D.getIdentifierLoc());
5281 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005282 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005283 }
John McCalla3f81372010-04-13 00:04:31 +00005284
5285 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5286
Chris Lattner6e475012009-04-25 08:35:12 +00005287 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005288 // Conversion functions don't have return types, but the parser will
5289 // happily parse something like:
5290 //
5291 // class X {
5292 // float operator bool();
5293 // };
5294 //
5295 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005296 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5297 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5298 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005299 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005300 }
5301
John McCalla3f81372010-04-13 00:04:31 +00005302 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5303
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005304 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005305 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005306 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5307
5308 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005309 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005310 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005311 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005312 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005313 D.setInvalidType();
5314 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005315
John McCalla3f81372010-04-13 00:04:31 +00005316 // Diagnose "&operator bool()" and other such nonsense. This
5317 // is actually a gcc extension which we don't support.
5318 if (Proto->getResultType() != ConvType) {
5319 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5320 << Proto->getResultType();
5321 D.setInvalidType();
5322 ConvType = Proto->getResultType();
5323 }
5324
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005325 // C++ [class.conv.fct]p4:
5326 // The conversion-type-id shall not represent a function type nor
5327 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005328 if (ConvType->isArrayType()) {
5329 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5330 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005331 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005332 } else if (ConvType->isFunctionType()) {
5333 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5334 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005335 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005336 }
5337
5338 // Rebuild the function type "R" without any parameters (in case any
5339 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005340 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005341 if (D.isInvalidType())
5342 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005343
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005344 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005345 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005346 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005347 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005348 diag::warn_cxx98_compat_explicit_conversion_functions :
5349 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005350 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005351}
5352
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005353/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5354/// the declaration of the given C++ conversion function. This routine
5355/// is responsible for recording the conversion function in the C++
5356/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005357Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005358 assert(Conversion && "Expected to receive a conversion function declaration");
5359
Douglas Gregor9d350972008-12-12 08:25:50 +00005360 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005361
5362 // Make sure we aren't redeclaring the conversion function.
5363 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005364
5365 // C++ [class.conv.fct]p1:
5366 // [...] A conversion function is never used to convert a
5367 // (possibly cv-qualified) object to the (possibly cv-qualified)
5368 // same object type (or a reference to it), to a (possibly
5369 // cv-qualified) base class of that type (or a reference to it),
5370 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005371 // FIXME: Suppress this warning if the conversion function ends up being a
5372 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005373 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005374 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005375 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005376 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005377 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5378 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005379 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005380 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005381 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5382 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005383 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005384 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005385 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005386 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005387 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005388 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005389 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005390 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005391 }
5392
Douglas Gregore80622f2010-09-29 04:25:11 +00005393 if (FunctionTemplateDecl *ConversionTemplate
5394 = Conversion->getDescribedFunctionTemplate())
5395 return ConversionTemplate;
5396
John McCalld226f652010-08-21 09:40:31 +00005397 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005398}
5399
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005400//===----------------------------------------------------------------------===//
5401// Namespace Handling
5402//===----------------------------------------------------------------------===//
5403
John McCallea318642010-08-26 09:15:37 +00005404
5405
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005406/// ActOnStartNamespaceDef - This is called at the start of a namespace
5407/// definition.
John McCalld226f652010-08-21 09:40:31 +00005408Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005409 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005410 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005411 SourceLocation IdentLoc,
5412 IdentifierInfo *II,
5413 SourceLocation LBrace,
5414 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005415 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5416 // For anonymous namespace, take the location of the left brace.
5417 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005418 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005419 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005420 bool IsStd = false;
5421 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005422 Scope *DeclRegionScope = NamespcScope->getParent();
5423
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005424 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005425 if (II) {
5426 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005427 // The identifier in an original-namespace-definition shall not
5428 // have been previously defined in the declarative region in
5429 // which the original-namespace-definition appears. The
5430 // identifier in an original-namespace-definition is the name of
5431 // the namespace. Subsequently in that declarative region, it is
5432 // treated as an original-namespace-name.
5433 //
5434 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005435 // look through using directives, just look for any ordinary names.
5436
5437 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005438 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5439 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005440 NamedDecl *PrevDecl = 0;
5441 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005442 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005443 R.first != R.second; ++R.first) {
5444 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5445 PrevDecl = *R.first;
5446 break;
5447 }
5448 }
5449
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005450 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5451
5452 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005453 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005454 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005455 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005456 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005457 // The user probably just forgot the 'inline', so suggest that it
5458 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005459 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005460 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5461 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005462 Diag(Loc, diag::err_inline_namespace_mismatch)
5463 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005464 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005465 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5466
5467 IsInline = PrevNS->isInline();
5468 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005469 } else if (PrevDecl) {
5470 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005471 Diag(Loc, diag::err_redefinition_different_kind)
5472 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005473 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005474 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005475 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005476 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005477 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005478 // This is the first "real" definition of the namespace "std", so update
5479 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005480 PrevNS = getStdNamespace();
5481 IsStd = true;
5482 AddToKnown = !IsInline;
5483 } else {
5484 // We've seen this namespace for the first time.
5485 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005486 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005487 } else {
John McCall9aeed322009-10-01 00:25:31 +00005488 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005489
5490 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005491 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005492 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005493 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005494 } else {
5495 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005496 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005497 }
5498
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005499 if (PrevNS && IsInline != PrevNS->isInline()) {
5500 // inline-ness must match
5501 Diag(Loc, diag::err_inline_namespace_mismatch)
5502 << IsInline;
5503 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005504
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005505 // Recover by ignoring the new namespace's inline status.
5506 IsInline = PrevNS->isInline();
5507 }
5508 }
5509
5510 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5511 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005512 if (IsInvalid)
5513 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005514
5515 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005516
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005517 // FIXME: Should we be merging attributes?
5518 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005519 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005520
5521 if (IsStd)
5522 StdNamespace = Namespc;
5523 if (AddToKnown)
5524 KnownNamespaces[Namespc] = false;
5525
5526 if (II) {
5527 PushOnScopeChains(Namespc, DeclRegionScope);
5528 } else {
5529 // Link the anonymous namespace into its parent.
5530 DeclContext *Parent = CurContext->getRedeclContext();
5531 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5532 TU->setAnonymousNamespace(Namespc);
5533 } else {
5534 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005535 }
John McCall9aeed322009-10-01 00:25:31 +00005536
Douglas Gregora4181472010-03-24 00:46:35 +00005537 CurContext->addDecl(Namespc);
5538
John McCall9aeed322009-10-01 00:25:31 +00005539 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5540 // behaves as if it were replaced by
5541 // namespace unique { /* empty body */ }
5542 // using namespace unique;
5543 // namespace unique { namespace-body }
5544 // where all occurrences of 'unique' in a translation unit are
5545 // replaced by the same identifier and this identifier differs
5546 // from all other identifiers in the entire program.
5547
5548 // We just create the namespace with an empty name and then add an
5549 // implicit using declaration, just like the standard suggests.
5550 //
5551 // CodeGen enforces the "universally unique" aspect by giving all
5552 // declarations semantically contained within an anonymous
5553 // namespace internal linkage.
5554
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005555 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005556 UsingDirectiveDecl* UD
5557 = UsingDirectiveDecl::Create(Context, CurContext,
5558 /* 'using' */ LBrace,
5559 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005560 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005561 /* identifier */ SourceLocation(),
5562 Namespc,
5563 /* Ancestor */ CurContext);
5564 UD->setImplicit();
5565 CurContext->addDecl(UD);
5566 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005567 }
5568
5569 // Although we could have an invalid decl (i.e. the namespace name is a
5570 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005571 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5572 // for the namespace has the declarations that showed up in that particular
5573 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005574 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005575 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005576}
5577
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005578/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5579/// is a namespace alias, returns the namespace it points to.
5580static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5581 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5582 return AD->getNamespace();
5583 return dyn_cast_or_null<NamespaceDecl>(D);
5584}
5585
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005586/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5587/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005588void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005589 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5590 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005591 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005592 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005593 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005594 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005595}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005596
John McCall384aff82010-08-25 07:42:41 +00005597CXXRecordDecl *Sema::getStdBadAlloc() const {
5598 return cast_or_null<CXXRecordDecl>(
5599 StdBadAlloc.get(Context.getExternalSource()));
5600}
5601
5602NamespaceDecl *Sema::getStdNamespace() const {
5603 return cast_or_null<NamespaceDecl>(
5604 StdNamespace.get(Context.getExternalSource()));
5605}
5606
Douglas Gregor66992202010-06-29 17:53:46 +00005607/// \brief Retrieve the special "std" namespace, which may require us to
5608/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005609NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005610 if (!StdNamespace) {
5611 // The "std" namespace has not yet been defined, so build one implicitly.
5612 StdNamespace = NamespaceDecl::Create(Context,
5613 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005614 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005615 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005616 &PP.getIdentifierTable().get("std"),
5617 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005618 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005619 }
5620
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005621 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005622}
5623
Sebastian Redl395e04d2012-01-17 22:49:33 +00005624bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005625 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00005626 "Looking for std::initializer_list outside of C++.");
5627
5628 // We're looking for implicit instantiations of
5629 // template <typename E> class std::initializer_list.
5630
5631 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5632 return false;
5633
Sebastian Redl84760e32012-01-17 22:49:58 +00005634 ClassTemplateDecl *Template = 0;
5635 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005636
Sebastian Redl84760e32012-01-17 22:49:58 +00005637 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005638
Sebastian Redl84760e32012-01-17 22:49:58 +00005639 ClassTemplateSpecializationDecl *Specialization =
5640 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5641 if (!Specialization)
5642 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005643
Sebastian Redl84760e32012-01-17 22:49:58 +00005644 Template = Specialization->getSpecializedTemplate();
5645 Arguments = Specialization->getTemplateArgs().data();
5646 } else if (const TemplateSpecializationType *TST =
5647 Ty->getAs<TemplateSpecializationType>()) {
5648 Template = dyn_cast_or_null<ClassTemplateDecl>(
5649 TST->getTemplateName().getAsTemplateDecl());
5650 Arguments = TST->getArgs();
5651 }
5652 if (!Template)
5653 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005654
5655 if (!StdInitializerList) {
5656 // Haven't recognized std::initializer_list yet, maybe this is it.
5657 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5658 if (TemplateClass->getIdentifier() !=
5659 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005660 !getStdNamespace()->InEnclosingNamespaceSetOf(
5661 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005662 return false;
5663 // This is a template called std::initializer_list, but is it the right
5664 // template?
5665 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005666 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005667 return false;
5668 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5669 return false;
5670
5671 // It's the right template.
5672 StdInitializerList = Template;
5673 }
5674
5675 if (Template != StdInitializerList)
5676 return false;
5677
5678 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005679 if (Element)
5680 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005681 return true;
5682}
5683
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005684static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5685 NamespaceDecl *Std = S.getStdNamespace();
5686 if (!Std) {
5687 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5688 return 0;
5689 }
5690
5691 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5692 Loc, Sema::LookupOrdinaryName);
5693 if (!S.LookupQualifiedName(Result, Std)) {
5694 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5695 return 0;
5696 }
5697 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5698 if (!Template) {
5699 Result.suppressDiagnostics();
5700 // We found something weird. Complain about the first thing we found.
5701 NamedDecl *Found = *Result.begin();
5702 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5703 return 0;
5704 }
5705
5706 // We found some template called std::initializer_list. Now verify that it's
5707 // correct.
5708 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005709 if (Params->getMinRequiredArguments() != 1 ||
5710 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005711 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5712 return 0;
5713 }
5714
5715 return Template;
5716}
5717
5718QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5719 if (!StdInitializerList) {
5720 StdInitializerList = LookupStdInitializerList(*this, Loc);
5721 if (!StdInitializerList)
5722 return QualType();
5723 }
5724
5725 TemplateArgumentListInfo Args(Loc, Loc);
5726 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5727 Context.getTrivialTypeSourceInfo(Element,
5728 Loc)));
5729 return Context.getCanonicalType(
5730 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5731}
5732
Sebastian Redl98d36062012-01-17 22:50:14 +00005733bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5734 // C++ [dcl.init.list]p2:
5735 // A constructor is an initializer-list constructor if its first parameter
5736 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5737 // std::initializer_list<E> for some type E, and either there are no other
5738 // parameters or else all other parameters have default arguments.
5739 if (Ctor->getNumParams() < 1 ||
5740 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5741 return false;
5742
5743 QualType ArgType = Ctor->getParamDecl(0)->getType();
5744 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5745 ArgType = RT->getPointeeType().getUnqualifiedType();
5746
5747 return isStdInitializerList(ArgType, 0);
5748}
5749
Douglas Gregor9172aa62011-03-26 22:25:30 +00005750/// \brief Determine whether a using statement is in a context where it will be
5751/// apply in all contexts.
5752static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5753 switch (CurContext->getDeclKind()) {
5754 case Decl::TranslationUnit:
5755 return true;
5756 case Decl::LinkageSpec:
5757 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5758 default:
5759 return false;
5760 }
5761}
5762
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005763namespace {
5764
5765// Callback to only accept typo corrections that are namespaces.
5766class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5767 public:
5768 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5769 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5770 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5771 }
5772 return false;
5773 }
5774};
5775
5776}
5777
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005778static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5779 CXXScopeSpec &SS,
5780 SourceLocation IdentLoc,
5781 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005782 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005783 R.clear();
5784 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005785 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005786 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005787 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5788 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005789 if (DeclContext *DC = S.computeDeclContext(SS, false))
5790 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5791 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5792 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5793 else
5794 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5795 << Ident << CorrectedQuotedStr
5796 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005797
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005798 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5799 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005800
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005801 R.addDecl(Corrected.getCorrectionDecl());
5802 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005803 }
5804 return false;
5805}
5806
John McCalld226f652010-08-21 09:40:31 +00005807Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005808 SourceLocation UsingLoc,
5809 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005810 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005811 SourceLocation IdentLoc,
5812 IdentifierInfo *NamespcName,
5813 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005814 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5815 assert(NamespcName && "Invalid NamespcName.");
5816 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005817
5818 // This can only happen along a recovery path.
5819 while (S->getFlags() & Scope::TemplateParamScope)
5820 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005821 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005822
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005823 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005824 NestedNameSpecifier *Qualifier = 0;
5825 if (SS.isSet())
5826 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5827
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005828 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005829 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5830 LookupParsedName(R, S, &SS);
5831 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005832 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005833
Douglas Gregor66992202010-06-29 17:53:46 +00005834 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005835 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005836 // Allow "using namespace std;" or "using namespace ::std;" even if
5837 // "std" hasn't been defined yet, for GCC compatibility.
5838 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5839 NamespcName->isStr("std")) {
5840 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005841 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005842 R.resolveKind();
5843 }
5844 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005845 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005846 }
5847
John McCallf36e02d2009-10-09 21:13:30 +00005848 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005849 NamedDecl *Named = R.getFoundDecl();
5850 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5851 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005852 // C++ [namespace.udir]p1:
5853 // A using-directive specifies that the names in the nominated
5854 // namespace can be used in the scope in which the
5855 // using-directive appears after the using-directive. During
5856 // unqualified name lookup (3.4.1), the names appear as if they
5857 // were declared in the nearest enclosing namespace which
5858 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005859 // namespace. [Note: in this context, "contains" means "contains
5860 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005861
5862 // Find enclosing context containing both using-directive and
5863 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005864 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005865 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5866 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5867 CommonAncestor = CommonAncestor->getParent();
5868
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005869 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005870 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005871 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005872
Douglas Gregor9172aa62011-03-26 22:25:30 +00005873 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005874 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005875 Diag(IdentLoc, diag::warn_using_directive_in_header);
5876 }
5877
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005878 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005879 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005880 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005881 }
5882
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005883 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005884 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005885}
5886
5887void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005888 // If the scope has an associated entity and the using directive is at
5889 // namespace or translation unit scope, add the UsingDirectiveDecl into
5890 // its lookup structure so qualified name lookup can find it.
5891 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5892 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005893 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005894 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005895 // Otherwise, it is at block sope. The using-directives will affect lookup
5896 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00005897 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005898}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005899
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005900
John McCalld226f652010-08-21 09:40:31 +00005901Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005902 AccessSpecifier AS,
5903 bool HasUsingKeyword,
5904 SourceLocation UsingLoc,
5905 CXXScopeSpec &SS,
5906 UnqualifiedId &Name,
5907 AttributeList *AttrList,
5908 bool IsTypeName,
5909 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005910 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005911
Douglas Gregor12c118a2009-11-04 16:30:06 +00005912 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005913 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005914 case UnqualifiedId::IK_Identifier:
5915 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005916 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005917 case UnqualifiedId::IK_ConversionFunctionId:
5918 break;
5919
5920 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005921 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005922 // C++0x inherited constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00005923 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005924 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005925 diag::warn_cxx98_compat_using_decl_constructor :
5926 diag::err_using_decl_constructor)
5927 << SS.getRange();
5928
David Blaikie4e4d0842012-03-11 07:00:24 +00005929 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00005930
John McCalld226f652010-08-21 09:40:31 +00005931 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005932
5933 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005934 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005935 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005936 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005937
5938 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005939 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005940 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005941 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005942 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005943
5944 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5945 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005946 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005947 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005948
John McCall60fa3cf2009-12-11 02:10:03 +00005949 // Warn about using declarations.
5950 // TODO: store that the declaration was written without 'using' and
5951 // talk about access decls instead of using decls in the
5952 // diagnostics.
5953 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005954 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00005955
5956 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005957 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005958 }
5959
Douglas Gregor56c04582010-12-16 00:46:58 +00005960 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5961 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5962 return 0;
5963
John McCall9488ea12009-11-17 05:59:44 +00005964 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005965 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005966 /* IsInstantiation */ false,
5967 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005968 if (UD)
5969 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005970
John McCalld226f652010-08-21 09:40:31 +00005971 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005972}
5973
Douglas Gregor09acc982010-07-07 23:08:52 +00005974/// \brief Determine whether a using declaration considers the given
5975/// declarations as "equivalent", e.g., if they are redeclarations of
5976/// the same entity or are both typedefs of the same type.
5977static bool
5978IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5979 bool &SuppressRedeclaration) {
5980 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5981 SuppressRedeclaration = false;
5982 return true;
5983 }
5984
Richard Smith162e1c12011-04-15 14:24:37 +00005985 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5986 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005987 SuppressRedeclaration = true;
5988 return Context.hasSameType(TD1->getUnderlyingType(),
5989 TD2->getUnderlyingType());
5990 }
5991
5992 return false;
5993}
5994
5995
John McCall9f54ad42009-12-10 09:41:52 +00005996/// Determines whether to create a using shadow decl for a particular
5997/// decl, given the set of decls existing prior to this using lookup.
5998bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5999 const LookupResult &Previous) {
6000 // Diagnose finding a decl which is not from a base class of the
6001 // current class. We do this now because there are cases where this
6002 // function will silently decide not to build a shadow decl, which
6003 // will pre-empt further diagnostics.
6004 //
6005 // We don't need to do this in C++0x because we do the check once on
6006 // the qualifier.
6007 //
6008 // FIXME: diagnose the following if we care enough:
6009 // struct A { int foo; };
6010 // struct B : A { using A::foo; };
6011 // template <class T> struct C : A {};
6012 // template <class T> struct D : C<T> { using B::foo; } // <---
6013 // This is invalid (during instantiation) in C++03 because B::foo
6014 // resolves to the using decl in B, which is not a base class of D<T>.
6015 // We can't diagnose it immediately because C<T> is an unknown
6016 // specialization. The UsingShadowDecl in D<T> then points directly
6017 // to A::foo, which will look well-formed when we instantiate.
6018 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00006019 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006020 DeclContext *OrigDC = Orig->getDeclContext();
6021
6022 // Handle enums and anonymous structs.
6023 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6024 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6025 while (OrigRec->isAnonymousStructOrUnion())
6026 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6027
6028 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6029 if (OrigDC == CurContext) {
6030 Diag(Using->getLocation(),
6031 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006032 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006033 Diag(Orig->getLocation(), diag::note_using_decl_target);
6034 return true;
6035 }
6036
Douglas Gregordc355712011-02-25 00:36:19 +00006037 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006038 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006039 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006040 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006041 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006042 Diag(Orig->getLocation(), diag::note_using_decl_target);
6043 return true;
6044 }
6045 }
6046
6047 if (Previous.empty()) return false;
6048
6049 NamedDecl *Target = Orig;
6050 if (isa<UsingShadowDecl>(Target))
6051 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6052
John McCalld7533ec2009-12-11 02:33:26 +00006053 // If the target happens to be one of the previous declarations, we
6054 // don't have a conflict.
6055 //
6056 // FIXME: but we might be increasing its access, in which case we
6057 // should redeclare it.
6058 NamedDecl *NonTag = 0, *Tag = 0;
6059 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6060 I != E; ++I) {
6061 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006062 bool Result;
6063 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6064 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006065
6066 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6067 }
6068
John McCall9f54ad42009-12-10 09:41:52 +00006069 if (Target->isFunctionOrFunctionTemplate()) {
6070 FunctionDecl *FD;
6071 if (isa<FunctionTemplateDecl>(Target))
6072 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6073 else
6074 FD = cast<FunctionDecl>(Target);
6075
6076 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006077 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006078 case Ovl_Overload:
6079 return false;
6080
6081 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006082 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006083 break;
6084
6085 // We found a decl with the exact signature.
6086 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006087 // If we're in a record, we want to hide the target, so we
6088 // return true (without a diagnostic) to tell the caller not to
6089 // build a shadow decl.
6090 if (CurContext->isRecord())
6091 return true;
6092
6093 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006094 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006095 break;
6096 }
6097
6098 Diag(Target->getLocation(), diag::note_using_decl_target);
6099 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6100 return true;
6101 }
6102
6103 // Target is not a function.
6104
John McCall9f54ad42009-12-10 09:41:52 +00006105 if (isa<TagDecl>(Target)) {
6106 // No conflict between a tag and a non-tag.
6107 if (!Tag) return false;
6108
John McCall41ce66f2009-12-10 19:51:03 +00006109 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006110 Diag(Target->getLocation(), diag::note_using_decl_target);
6111 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6112 return true;
6113 }
6114
6115 // No conflict between a tag and a non-tag.
6116 if (!NonTag) return false;
6117
John McCall41ce66f2009-12-10 19:51:03 +00006118 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006119 Diag(Target->getLocation(), diag::note_using_decl_target);
6120 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6121 return true;
6122}
6123
John McCall9488ea12009-11-17 05:59:44 +00006124/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006125UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006126 UsingDecl *UD,
6127 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006128
6129 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006130 NamedDecl *Target = Orig;
6131 if (isa<UsingShadowDecl>(Target)) {
6132 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6133 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006134 }
6135
6136 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006137 = UsingShadowDecl::Create(Context, CurContext,
6138 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006139 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006140
6141 Shadow->setAccess(UD->getAccess());
6142 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6143 Shadow->setInvalidDecl();
6144
John McCall9488ea12009-11-17 05:59:44 +00006145 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006146 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006147 else
John McCall604e7f12009-12-08 07:46:18 +00006148 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006149
John McCall604e7f12009-12-08 07:46:18 +00006150
John McCall9f54ad42009-12-10 09:41:52 +00006151 return Shadow;
6152}
John McCall604e7f12009-12-08 07:46:18 +00006153
John McCall9f54ad42009-12-10 09:41:52 +00006154/// Hides a using shadow declaration. This is required by the current
6155/// using-decl implementation when a resolvable using declaration in a
6156/// class is followed by a declaration which would hide or override
6157/// one or more of the using decl's targets; for example:
6158///
6159/// struct Base { void foo(int); };
6160/// struct Derived : Base {
6161/// using Base::foo;
6162/// void foo(int);
6163/// };
6164///
6165/// The governing language is C++03 [namespace.udecl]p12:
6166///
6167/// When a using-declaration brings names from a base class into a
6168/// derived class scope, member functions in the derived class
6169/// override and/or hide member functions with the same name and
6170/// parameter types in a base class (rather than conflicting).
6171///
6172/// There are two ways to implement this:
6173/// (1) optimistically create shadow decls when they're not hidden
6174/// by existing declarations, or
6175/// (2) don't create any shadow decls (or at least don't make them
6176/// visible) until we've fully parsed/instantiated the class.
6177/// The problem with (1) is that we might have to retroactively remove
6178/// a shadow decl, which requires several O(n) operations because the
6179/// decl structures are (very reasonably) not designed for removal.
6180/// (2) avoids this but is very fiddly and phase-dependent.
6181void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006182 if (Shadow->getDeclName().getNameKind() ==
6183 DeclarationName::CXXConversionFunctionName)
6184 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6185
John McCall9f54ad42009-12-10 09:41:52 +00006186 // Remove it from the DeclContext...
6187 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006188
John McCall9f54ad42009-12-10 09:41:52 +00006189 // ...and the scope, if applicable...
6190 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006191 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006192 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006193 }
6194
John McCall9f54ad42009-12-10 09:41:52 +00006195 // ...and the using decl.
6196 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6197
6198 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006199 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006200}
6201
John McCall7ba107a2009-11-18 02:36:19 +00006202/// Builds a using declaration.
6203///
6204/// \param IsInstantiation - Whether this call arises from an
6205/// instantiation of an unresolved using declaration. We treat
6206/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006207NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6208 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006209 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006210 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006211 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006212 bool IsInstantiation,
6213 bool IsTypeName,
6214 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006215 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006216 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006217 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006218
Anders Carlsson550b14b2009-08-28 05:49:21 +00006219 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006220
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006221 if (SS.isEmpty()) {
6222 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006223 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006224 }
Mike Stump1eb44332009-09-09 15:08:12 +00006225
John McCall9f54ad42009-12-10 09:41:52 +00006226 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006227 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006228 ForRedeclaration);
6229 Previous.setHideTags(false);
6230 if (S) {
6231 LookupName(Previous, S);
6232
6233 // It is really dumb that we have to do this.
6234 LookupResult::Filter F = Previous.makeFilter();
6235 while (F.hasNext()) {
6236 NamedDecl *D = F.next();
6237 if (!isDeclInScope(D, CurContext, S))
6238 F.erase();
6239 }
6240 F.done();
6241 } else {
6242 assert(IsInstantiation && "no scope in non-instantiation");
6243 assert(CurContext->isRecord() && "scope not record in instantiation");
6244 LookupQualifiedName(Previous, CurContext);
6245 }
6246
John McCall9f54ad42009-12-10 09:41:52 +00006247 // Check for invalid redeclarations.
6248 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6249 return 0;
6250
6251 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006252 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6253 return 0;
6254
John McCallaf8e6ed2009-11-12 03:15:40 +00006255 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006256 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006257 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006258 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006259 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006260 // FIXME: not all declaration name kinds are legal here
6261 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6262 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006263 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006264 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006265 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006266 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6267 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006268 }
John McCalled976492009-12-04 22:46:56 +00006269 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006270 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6271 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006272 }
John McCalled976492009-12-04 22:46:56 +00006273 D->setAccess(AS);
6274 CurContext->addDecl(D);
6275
6276 if (!LookupContext) return D;
6277 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006278
John McCall77bb1aa2010-05-01 00:40:08 +00006279 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006280 UD->setInvalidDecl();
6281 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006282 }
6283
Richard Smithc5a89a12012-04-02 01:30:27 +00006284 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006285 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006286 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006287 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006288 return UD;
6289 }
6290
6291 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006292
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006293 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006294
John McCall604e7f12009-12-08 07:46:18 +00006295 // Unlike most lookups, we don't always want to hide tag
6296 // declarations: tag names are visible through the using declaration
6297 // even if hidden by ordinary names, *except* in a dependent context
6298 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006299 if (!IsInstantiation)
6300 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006301
John McCallb9abd8722012-04-07 03:04:20 +00006302 // For the purposes of this lookup, we have a base object type
6303 // equal to that of the current context.
6304 if (CurContext->isRecord()) {
6305 R.setBaseObjectType(
6306 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6307 }
6308
John McCalla24dc2e2009-11-17 02:14:36 +00006309 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006310
John McCallf36e02d2009-10-09 21:13:30 +00006311 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006312 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006313 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006314 UD->setInvalidDecl();
6315 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006316 }
6317
John McCalled976492009-12-04 22:46:56 +00006318 if (R.isAmbiguous()) {
6319 UD->setInvalidDecl();
6320 return UD;
6321 }
Mike Stump1eb44332009-09-09 15:08:12 +00006322
John McCall7ba107a2009-11-18 02:36:19 +00006323 if (IsTypeName) {
6324 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006325 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006326 Diag(IdentLoc, diag::err_using_typename_non_type);
6327 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6328 Diag((*I)->getUnderlyingDecl()->getLocation(),
6329 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006330 UD->setInvalidDecl();
6331 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006332 }
6333 } else {
6334 // If we asked for a non-typename and we got a type, error out,
6335 // but only if this is an instantiation of an unresolved using
6336 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006337 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006338 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6339 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006340 UD->setInvalidDecl();
6341 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006342 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006343 }
6344
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006345 // C++0x N2914 [namespace.udecl]p6:
6346 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006347 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006348 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6349 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006350 UD->setInvalidDecl();
6351 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006352 }
Mike Stump1eb44332009-09-09 15:08:12 +00006353
John McCall9f54ad42009-12-10 09:41:52 +00006354 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6355 if (!CheckUsingShadowDecl(UD, *I, Previous))
6356 BuildUsingShadowDecl(S, UD, *I);
6357 }
John McCall9488ea12009-11-17 05:59:44 +00006358
6359 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006360}
6361
Sebastian Redlf677ea32011-02-05 19:23:19 +00006362/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006363bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6364 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006365
Douglas Gregordc355712011-02-25 00:36:19 +00006366 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006367 assert(SourceType &&
6368 "Using decl naming constructor doesn't have type in scope spec.");
6369 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6370
6371 // Check whether the named type is a direct base class.
6372 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6373 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6374 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6375 BaseIt != BaseE; ++BaseIt) {
6376 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6377 if (CanonicalSourceType == BaseType)
6378 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006379 if (BaseIt->getType()->isDependentType())
6380 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006381 }
6382
6383 if (BaseIt == BaseE) {
6384 // Did not find SourceType in the bases.
6385 Diag(UD->getUsingLocation(),
6386 diag::err_using_decl_constructor_not_in_direct_base)
6387 << UD->getNameInfo().getSourceRange()
6388 << QualType(SourceType, 0) << TargetClass;
6389 return true;
6390 }
6391
Richard Smithc5a89a12012-04-02 01:30:27 +00006392 if (!CurContext->isDependentContext())
6393 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006394
6395 return false;
6396}
6397
John McCall9f54ad42009-12-10 09:41:52 +00006398/// Checks that the given using declaration is not an invalid
6399/// redeclaration. Note that this is checking only for the using decl
6400/// itself, not for any ill-formedness among the UsingShadowDecls.
6401bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6402 bool isTypeName,
6403 const CXXScopeSpec &SS,
6404 SourceLocation NameLoc,
6405 const LookupResult &Prev) {
6406 // C++03 [namespace.udecl]p8:
6407 // C++0x [namespace.udecl]p10:
6408 // A using-declaration is a declaration and can therefore be used
6409 // repeatedly where (and only where) multiple declarations are
6410 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006411 //
John McCall8a726212010-11-29 18:01:58 +00006412 // That's in non-member contexts.
6413 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006414 return false;
6415
6416 NestedNameSpecifier *Qual
6417 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6418
6419 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6420 NamedDecl *D = *I;
6421
6422 bool DTypename;
6423 NestedNameSpecifier *DQual;
6424 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6425 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006426 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006427 } else if (UnresolvedUsingValueDecl *UD
6428 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6429 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006430 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006431 } else if (UnresolvedUsingTypenameDecl *UD
6432 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6433 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006434 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006435 } else continue;
6436
6437 // using decls differ if one says 'typename' and the other doesn't.
6438 // FIXME: non-dependent using decls?
6439 if (isTypeName != DTypename) continue;
6440
6441 // using decls differ if they name different scopes (but note that
6442 // template instantiation can cause this check to trigger when it
6443 // didn't before instantiation).
6444 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6445 Context.getCanonicalNestedNameSpecifier(DQual))
6446 continue;
6447
6448 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006449 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006450 return true;
6451 }
6452
6453 return false;
6454}
6455
John McCall604e7f12009-12-08 07:46:18 +00006456
John McCalled976492009-12-04 22:46:56 +00006457/// Checks that the given nested-name qualifier used in a using decl
6458/// in the current context is appropriately related to the current
6459/// scope. If an error is found, diagnoses it and returns true.
6460bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6461 const CXXScopeSpec &SS,
6462 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006463 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006464
John McCall604e7f12009-12-08 07:46:18 +00006465 if (!CurContext->isRecord()) {
6466 // C++03 [namespace.udecl]p3:
6467 // C++0x [namespace.udecl]p8:
6468 // A using-declaration for a class member shall be a member-declaration.
6469
6470 // If we weren't able to compute a valid scope, it must be a
6471 // dependent class scope.
6472 if (!NamedContext || NamedContext->isRecord()) {
6473 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6474 << SS.getRange();
6475 return true;
6476 }
6477
6478 // Otherwise, everything is known to be fine.
6479 return false;
6480 }
6481
6482 // The current scope is a record.
6483
6484 // If the named context is dependent, we can't decide much.
6485 if (!NamedContext) {
6486 // FIXME: in C++0x, we can diagnose if we can prove that the
6487 // nested-name-specifier does not refer to a base class, which is
6488 // still possible in some cases.
6489
6490 // Otherwise we have to conservatively report that things might be
6491 // okay.
6492 return false;
6493 }
6494
6495 if (!NamedContext->isRecord()) {
6496 // Ideally this would point at the last name in the specifier,
6497 // but we don't have that level of source info.
6498 Diag(SS.getRange().getBegin(),
6499 diag::err_using_decl_nested_name_specifier_is_not_class)
6500 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6501 return true;
6502 }
6503
Douglas Gregor6fb07292010-12-21 07:41:49 +00006504 if (!NamedContext->isDependentContext() &&
6505 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6506 return true;
6507
David Blaikie4e4d0842012-03-11 07:00:24 +00006508 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00006509 // C++0x [namespace.udecl]p3:
6510 // In a using-declaration used as a member-declaration, the
6511 // nested-name-specifier shall name a base class of the class
6512 // being defined.
6513
6514 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6515 cast<CXXRecordDecl>(NamedContext))) {
6516 if (CurContext == NamedContext) {
6517 Diag(NameLoc,
6518 diag::err_using_decl_nested_name_specifier_is_current_class)
6519 << SS.getRange();
6520 return true;
6521 }
6522
6523 Diag(SS.getRange().getBegin(),
6524 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6525 << (NestedNameSpecifier*) SS.getScopeRep()
6526 << cast<CXXRecordDecl>(CurContext)
6527 << SS.getRange();
6528 return true;
6529 }
6530
6531 return false;
6532 }
6533
6534 // C++03 [namespace.udecl]p4:
6535 // A using-declaration used as a member-declaration shall refer
6536 // to a member of a base class of the class being defined [etc.].
6537
6538 // Salient point: SS doesn't have to name a base class as long as
6539 // lookup only finds members from base classes. Therefore we can
6540 // diagnose here only if we can prove that that can't happen,
6541 // i.e. if the class hierarchies provably don't intersect.
6542
6543 // TODO: it would be nice if "definitely valid" results were cached
6544 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6545 // need to be repeated.
6546
6547 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00006548 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00006549
6550 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6551 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6552 Data->Bases.insert(Base);
6553 return true;
6554 }
6555
6556 bool hasDependentBases(const CXXRecordDecl *Class) {
6557 return !Class->forallBases(collect, this);
6558 }
6559
6560 /// Returns true if the base is dependent or is one of the
6561 /// accumulated base classes.
6562 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6563 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6564 return !Data->Bases.count(Base);
6565 }
6566
6567 bool mightShareBases(const CXXRecordDecl *Class) {
6568 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6569 }
6570 };
6571
6572 UserData Data;
6573
6574 // Returns false if we find a dependent base.
6575 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6576 return false;
6577
6578 // Returns false if the class has a dependent base or if it or one
6579 // of its bases is present in the base set of the current context.
6580 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6581 return false;
6582
6583 Diag(SS.getRange().getBegin(),
6584 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6585 << (NestedNameSpecifier*) SS.getScopeRep()
6586 << cast<CXXRecordDecl>(CurContext)
6587 << SS.getRange();
6588
6589 return true;
John McCalled976492009-12-04 22:46:56 +00006590}
6591
Richard Smith162e1c12011-04-15 14:24:37 +00006592Decl *Sema::ActOnAliasDeclaration(Scope *S,
6593 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006594 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006595 SourceLocation UsingLoc,
6596 UnqualifiedId &Name,
6597 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006598 // Skip up to the relevant declaration scope.
6599 while (S->getFlags() & Scope::TemplateParamScope)
6600 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006601 assert((S->getFlags() & Scope::DeclScope) &&
6602 "got alias-declaration outside of declaration scope");
6603
6604 if (Type.isInvalid())
6605 return 0;
6606
6607 bool Invalid = false;
6608 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6609 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006610 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006611
6612 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6613 return 0;
6614
6615 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006616 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006617 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006618 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6619 TInfo->getTypeLoc().getBeginLoc());
6620 }
Richard Smith162e1c12011-04-15 14:24:37 +00006621
6622 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6623 LookupName(Previous, S);
6624
6625 // Warn about shadowing the name of a template parameter.
6626 if (Previous.isSingleResult() &&
6627 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006628 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006629 Previous.clear();
6630 }
6631
6632 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6633 "name in alias declaration must be an identifier");
6634 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6635 Name.StartLocation,
6636 Name.Identifier, TInfo);
6637
6638 NewTD->setAccess(AS);
6639
6640 if (Invalid)
6641 NewTD->setInvalidDecl();
6642
Richard Smith3e4c6c42011-05-05 21:57:07 +00006643 CheckTypedefForVariablyModifiedType(S, NewTD);
6644 Invalid |= NewTD->isInvalidDecl();
6645
Richard Smith162e1c12011-04-15 14:24:37 +00006646 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006647
6648 NamedDecl *NewND;
6649 if (TemplateParamLists.size()) {
6650 TypeAliasTemplateDecl *OldDecl = 0;
6651 TemplateParameterList *OldTemplateParams = 0;
6652
6653 if (TemplateParamLists.size() != 1) {
6654 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6655 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6656 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6657 }
6658 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6659
6660 // Only consider previous declarations in the same scope.
6661 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6662 /*ExplicitInstantiationOrSpecialization*/false);
6663 if (!Previous.empty()) {
6664 Redeclaration = true;
6665
6666 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6667 if (!OldDecl && !Invalid) {
6668 Diag(UsingLoc, diag::err_redefinition_different_kind)
6669 << Name.Identifier;
6670
6671 NamedDecl *OldD = Previous.getRepresentativeDecl();
6672 if (OldD->getLocation().isValid())
6673 Diag(OldD->getLocation(), diag::note_previous_definition);
6674
6675 Invalid = true;
6676 }
6677
6678 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6679 if (TemplateParameterListsAreEqual(TemplateParams,
6680 OldDecl->getTemplateParameters(),
6681 /*Complain=*/true,
6682 TPL_TemplateMatch))
6683 OldTemplateParams = OldDecl->getTemplateParameters();
6684 else
6685 Invalid = true;
6686
6687 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6688 if (!Invalid &&
6689 !Context.hasSameType(OldTD->getUnderlyingType(),
6690 NewTD->getUnderlyingType())) {
6691 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6692 // but we can't reasonably accept it.
6693 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6694 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6695 if (OldTD->getLocation().isValid())
6696 Diag(OldTD->getLocation(), diag::note_previous_definition);
6697 Invalid = true;
6698 }
6699 }
6700 }
6701
6702 // Merge any previous default template arguments into our parameters,
6703 // and check the parameter list.
6704 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6705 TPC_TypeAliasTemplate))
6706 return 0;
6707
6708 TypeAliasTemplateDecl *NewDecl =
6709 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6710 Name.Identifier, TemplateParams,
6711 NewTD);
6712
6713 NewDecl->setAccess(AS);
6714
6715 if (Invalid)
6716 NewDecl->setInvalidDecl();
6717 else if (OldDecl)
6718 NewDecl->setPreviousDeclaration(OldDecl);
6719
6720 NewND = NewDecl;
6721 } else {
6722 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6723 NewND = NewTD;
6724 }
Richard Smith162e1c12011-04-15 14:24:37 +00006725
6726 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006727 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006728
Richard Smith3e4c6c42011-05-05 21:57:07 +00006729 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006730}
6731
John McCalld226f652010-08-21 09:40:31 +00006732Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006733 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006734 SourceLocation AliasLoc,
6735 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006736 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006737 SourceLocation IdentLoc,
6738 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006739
Anders Carlsson81c85c42009-03-28 23:53:49 +00006740 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006741 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6742 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006743
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006744 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006745 NamedDecl *PrevDecl
6746 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6747 ForRedeclaration);
6748 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6749 PrevDecl = 0;
6750
6751 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006752 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006753 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006754 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006755 // FIXME: At some point, we'll want to create the (redundant)
6756 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006757 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006758 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006759 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006760 }
Mike Stump1eb44332009-09-09 15:08:12 +00006761
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006762 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6763 diag::err_redefinition_different_kind;
6764 Diag(AliasLoc, DiagID) << Alias;
6765 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006766 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006767 }
6768
John McCalla24dc2e2009-11-17 02:14:36 +00006769 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006770 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006771
John McCallf36e02d2009-10-09 21:13:30 +00006772 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006773 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00006774 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006775 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006776 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006777 }
Mike Stump1eb44332009-09-09 15:08:12 +00006778
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006779 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006780 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006781 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006782 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006783
John McCall3dbd3d52010-02-16 06:53:13 +00006784 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006785 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006786}
6787
Douglas Gregor39957dc2010-05-01 15:04:51 +00006788namespace {
6789 /// \brief Scoped object used to handle the state changes required in Sema
6790 /// to implicitly define the body of a C++ member function;
6791 class ImplicitlyDefinedFunctionScope {
6792 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006793 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006794
6795 public:
6796 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006797 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006798 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006799 S.PushFunctionScope();
6800 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6801 }
6802
6803 ~ImplicitlyDefinedFunctionScope() {
6804 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006805 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006806 }
6807 };
6808}
6809
Sean Hunt001cad92011-05-10 00:49:42 +00006810Sema::ImplicitExceptionSpecification
6811Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006812 // C++ [except.spec]p14:
6813 // An implicitly declared special member function (Clause 12) shall have an
6814 // exception-specification. [...]
6815 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006816 if (ClassDecl->isInvalidDecl())
6817 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006818
Sebastian Redl60618fa2011-03-12 11:50:43 +00006819 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006820 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6821 BEnd = ClassDecl->bases_end();
6822 B != BEnd; ++B) {
6823 if (B->isVirtual()) // Handled below.
6824 continue;
6825
Douglas Gregor18274032010-07-03 00:47:00 +00006826 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6827 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006828 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6829 // If this is a deleted function, add it anyway. This might be conformant
6830 // with the standard. This might not. I'm not sure. It might not matter.
6831 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006832 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006833 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006834 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006835
6836 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006837 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6838 BEnd = ClassDecl->vbases_end();
6839 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006840 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6841 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006842 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6843 // If this is a deleted function, add it anyway. This might be conformant
6844 // with the standard. This might not. I'm not sure. It might not matter.
6845 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006846 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006847 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006848 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006849
6850 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006851 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6852 FEnd = ClassDecl->field_end();
6853 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006854 if (F->hasInClassInitializer()) {
6855 if (Expr *E = F->getInClassInitializer())
6856 ExceptSpec.CalledExpr(E);
6857 else if (!F->isInvalidDecl())
6858 ExceptSpec.SetDelayed();
6859 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006860 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006861 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6862 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6863 // If this is a deleted function, add it anyway. This might be conformant
6864 // with the standard. This might not. I'm not sure. It might not matter.
6865 // In particular, the problem is that this function never gets called. It
6866 // might just be ill-formed because this function attempts to refer to
6867 // a deleted function here.
6868 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006869 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006870 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006871 }
John McCalle23cf432010-12-14 08:05:40 +00006872
Sean Hunt001cad92011-05-10 00:49:42 +00006873 return ExceptSpec;
6874}
6875
6876CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6877 CXXRecordDecl *ClassDecl) {
6878 // C++ [class.ctor]p5:
6879 // A default constructor for a class X is a constructor of class X
6880 // that can be called without an argument. If there is no
6881 // user-declared constructor for class X, a default constructor is
6882 // implicitly declared. An implicitly-declared default constructor
6883 // is an inline public member of its class.
6884 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6885 "Should not build implicit default constructor!");
6886
6887 ImplicitExceptionSpecification Spec =
6888 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6889 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006890
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006891 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006892 CanQualType ClassType
6893 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006894 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006895 DeclarationName Name
6896 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006897 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006898 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6899 Context, ClassDecl, ClassLoc, NameInfo,
6900 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
6901 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6902 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006903 getLangOpts().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006904 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006905 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006906 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006907 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006908
6909 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006910 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6911
Douglas Gregor23c94db2010-07-02 17:43:08 +00006912 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006913 PushOnScopeChains(DefaultCon, S, false);
6914 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006915
Sean Hunte16da072011-10-10 06:18:57 +00006916 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006917 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006918
Douglas Gregor32df23e2010-07-01 22:02:46 +00006919 return DefaultCon;
6920}
6921
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006922void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6923 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006924 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006925 !Constructor->doesThisDeclarationHaveABody() &&
6926 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006927 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006928
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006929 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006930 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006931
Douglas Gregor39957dc2010-05-01 15:04:51 +00006932 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006933 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006934 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006935 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006936 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006937 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006938 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006939 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006940 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006941
6942 SourceLocation Loc = Constructor->getLocation();
6943 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6944
6945 Constructor->setUsed();
6946 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006947
6948 if (ASTMutationListener *L = getASTMutationListener()) {
6949 L->CompletedImplicitDefinition(Constructor);
6950 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006951}
6952
Richard Smith7a614d82011-06-11 17:19:42 +00006953/// Get any existing defaulted default constructor for the given class. Do not
6954/// implicitly define one if it does not exist.
6955static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6956 CXXRecordDecl *D) {
6957 ASTContext &Context = Self.Context;
6958 QualType ClassType = Context.getTypeDeclType(D);
6959 DeclarationName ConstructorName
6960 = Context.DeclarationNames.getCXXConstructorName(
6961 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6962
6963 DeclContext::lookup_const_iterator Con, ConEnd;
6964 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6965 Con != ConEnd; ++Con) {
6966 // A function template cannot be defaulted.
6967 if (isa<FunctionTemplateDecl>(*Con))
6968 continue;
6969
6970 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6971 if (Constructor->isDefaultConstructor())
6972 return Constructor->isDefaulted() ? Constructor : 0;
6973 }
6974 return 0;
6975}
6976
6977void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6978 if (!D) return;
6979 AdjustDeclIfTemplate(D);
6980
6981 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6982 CXXConstructorDecl *CtorDecl
6983 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6984
6985 if (!CtorDecl) return;
6986
6987 // Compute the exception specification for the default constructor.
6988 const FunctionProtoType *CtorTy =
6989 CtorDecl->getType()->castAs<FunctionProtoType>();
6990 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6991 ImplicitExceptionSpecification Spec =
6992 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6993 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6994 assert(EPI.ExceptionSpecType != EST_Delayed);
6995
6996 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6997 }
6998
6999 // If the default constructor is explicitly defaulted, checking the exception
7000 // specification is deferred until now.
7001 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7002 !ClassDecl->isDependentType())
7003 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7004}
7005
Sebastian Redlf677ea32011-02-05 19:23:19 +00007006void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7007 // We start with an initial pass over the base classes to collect those that
7008 // inherit constructors from. If there are none, we can forgo all further
7009 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007010 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007011 BasesVector BasesToInheritFrom;
7012 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7013 BaseE = ClassDecl->bases_end();
7014 BaseIt != BaseE; ++BaseIt) {
7015 if (BaseIt->getInheritConstructors()) {
7016 QualType Base = BaseIt->getType();
7017 if (Base->isDependentType()) {
7018 // If we inherit constructors from anything that is dependent, just
7019 // abort processing altogether. We'll get another chance for the
7020 // instantiations.
7021 return;
7022 }
7023 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7024 }
7025 }
7026 if (BasesToInheritFrom.empty())
7027 return;
7028
7029 // Now collect the constructors that we already have in the current class.
7030 // Those take precedence over inherited constructors.
7031 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7032 // unless there is a user-declared constructor with the same signature in
7033 // the class where the using-declaration appears.
7034 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7035 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7036 CtorE = ClassDecl->ctor_end();
7037 CtorIt != CtorE; ++CtorIt) {
7038 ExistingConstructors.insert(
7039 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7040 }
7041
Sebastian Redlf677ea32011-02-05 19:23:19 +00007042 DeclarationName CreatedCtorName =
7043 Context.DeclarationNames.getCXXConstructorName(
7044 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7045
7046 // Now comes the true work.
7047 // First, we keep a map from constructor types to the base that introduced
7048 // them. Needed for finding conflicting constructors. We also keep the
7049 // actually inserted declarations in there, for pretty diagnostics.
7050 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7051 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7052 ConstructorToSourceMap InheritedConstructors;
7053 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7054 BaseE = BasesToInheritFrom.end();
7055 BaseIt != BaseE; ++BaseIt) {
7056 const RecordType *Base = *BaseIt;
7057 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7058 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7059 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7060 CtorE = BaseDecl->ctor_end();
7061 CtorIt != CtorE; ++CtorIt) {
7062 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007063 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007064 DeclarationName Name =
7065 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007066 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7067 LookupQualifiedName(Result, CurContext);
7068 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007069 SourceLocation UsingLoc = UD ? UD->getLocation() :
7070 ClassDecl->getLocation();
7071
7072 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7073 // from the class X named in the using-declaration consists of actual
7074 // constructors and notional constructors that result from the
7075 // transformation of defaulted parameters as follows:
7076 // - all non-template default constructors of X, and
7077 // - for each non-template constructor of X that has at least one
7078 // parameter with a default argument, the set of constructors that
7079 // results from omitting any ellipsis parameter specification and
7080 // successively omitting parameters with a default argument from the
7081 // end of the parameter-type-list.
7082 CXXConstructorDecl *BaseCtor = *CtorIt;
7083 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7084 const FunctionProtoType *BaseCtorType =
7085 BaseCtor->getType()->getAs<FunctionProtoType>();
7086
7087 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7088 maxParams = BaseCtor->getNumParams();
7089 params <= maxParams; ++params) {
7090 // Skip default constructors. They're never inherited.
7091 if (params == 0)
7092 continue;
7093 // Skip copy and move constructors for the same reason.
7094 if (CanBeCopyOrMove && params == 1)
7095 continue;
7096
7097 // Build up a function type for this particular constructor.
7098 // FIXME: The working paper does not consider that the exception spec
7099 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007100 // source. This code doesn't yet, either. When it does, this code will
7101 // need to be delayed until after exception specifications and in-class
7102 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007103 const Type *NewCtorType;
7104 if (params == maxParams)
7105 NewCtorType = BaseCtorType;
7106 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007107 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007108 for (unsigned i = 0; i < params; ++i) {
7109 Args.push_back(BaseCtorType->getArgType(i));
7110 }
7111 FunctionProtoType::ExtProtoInfo ExtInfo =
7112 BaseCtorType->getExtProtoInfo();
7113 ExtInfo.Variadic = false;
7114 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7115 Args.data(), params, ExtInfo)
7116 .getTypePtr();
7117 }
7118 const Type *CanonicalNewCtorType =
7119 Context.getCanonicalType(NewCtorType);
7120
7121 // Now that we have the type, first check if the class already has a
7122 // constructor with this signature.
7123 if (ExistingConstructors.count(CanonicalNewCtorType))
7124 continue;
7125
7126 // Then we check if we have already declared an inherited constructor
7127 // with this signature.
7128 std::pair<ConstructorToSourceMap::iterator, bool> result =
7129 InheritedConstructors.insert(std::make_pair(
7130 CanonicalNewCtorType,
7131 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7132 if (!result.second) {
7133 // Already in the map. If it came from a different class, that's an
7134 // error. Not if it's from the same.
7135 CanQualType PreviousBase = result.first->second.first;
7136 if (CanonicalBase != PreviousBase) {
7137 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7138 const CXXConstructorDecl *PrevBaseCtor =
7139 PrevCtor->getInheritedConstructor();
7140 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7141
7142 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7143 Diag(BaseCtor->getLocation(),
7144 diag::note_using_decl_constructor_conflict_current_ctor);
7145 Diag(PrevBaseCtor->getLocation(),
7146 diag::note_using_decl_constructor_conflict_previous_ctor);
7147 Diag(PrevCtor->getLocation(),
7148 diag::note_using_decl_constructor_conflict_previous_using);
7149 }
7150 continue;
7151 }
7152
7153 // OK, we're there, now add the constructor.
7154 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007155 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007156 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7157 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007158 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7159 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007160 /*ImplicitlyDeclared=*/true,
7161 // FIXME: Due to a defect in the standard, we treat inherited
7162 // constructors as constexpr even if that makes them ill-formed.
7163 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007164 NewCtor->setAccess(BaseCtor->getAccess());
7165
7166 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007167 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007168 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007169 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7170 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007171 /*IdentifierInfo=*/0,
7172 BaseCtorType->getArgType(i),
7173 /*TInfo=*/0, SC_None,
7174 SC_None, /*DefaultArg=*/0));
7175 }
David Blaikie4278c652011-09-21 18:16:56 +00007176 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007177 NewCtor->setInheritedConstructor(BaseCtor);
7178
Sebastian Redlf677ea32011-02-05 19:23:19 +00007179 ClassDecl->addDecl(NewCtor);
7180 result.first->second.second = NewCtor;
7181 }
7182 }
7183 }
7184}
7185
Sean Huntcb45a0f2011-05-12 22:46:25 +00007186Sema::ImplicitExceptionSpecification
7187Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007188 // C++ [except.spec]p14:
7189 // An implicitly declared special member function (Clause 12) shall have
7190 // an exception-specification.
7191 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007192 if (ClassDecl->isInvalidDecl())
7193 return ExceptSpec;
7194
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007195 // Direct base-class destructors.
7196 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7197 BEnd = ClassDecl->bases_end();
7198 B != BEnd; ++B) {
7199 if (B->isVirtual()) // Handled below.
7200 continue;
7201
7202 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7203 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007204 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007205 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007206
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007207 // Virtual base-class destructors.
7208 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7209 BEnd = ClassDecl->vbases_end();
7210 B != BEnd; ++B) {
7211 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7212 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007213 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007214 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007215
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007216 // Field destructors.
7217 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7218 FEnd = ClassDecl->field_end();
7219 F != FEnd; ++F) {
7220 if (const RecordType *RecordTy
7221 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7222 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007223 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007224 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007225
Sean Huntcb45a0f2011-05-12 22:46:25 +00007226 return ExceptSpec;
7227}
7228
7229CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7230 // C++ [class.dtor]p2:
7231 // If a class has no user-declared destructor, a destructor is
7232 // declared implicitly. An implicitly-declared destructor is an
7233 // inline public member of its class.
7234
7235 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007236 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007237 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7238
Douglas Gregor4923aa22010-07-02 20:37:36 +00007239 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007240 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007241
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007242 CanQualType ClassType
7243 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007244 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007245 DeclarationName Name
7246 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007247 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007248 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007249 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7250 /*isInline=*/true,
7251 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007252 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007253 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007254 Destructor->setImplicit();
7255 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007256
7257 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007258 ++ASTContext::NumImplicitDestructorsDeclared;
7259
7260 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007261 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007262 PushOnScopeChains(Destructor, S, false);
7263 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007264
7265 // This could be uniqued if it ever proves significant.
7266 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007267
Richard Smith9a561d52012-02-26 09:11:52 +00007268 AddOverriddenMethods(ClassDecl, Destructor);
7269
Richard Smith7d5088a2012-02-18 02:02:13 +00007270 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Sean Huntcb45a0f2011-05-12 22:46:25 +00007271 Destructor->setDeletedAsWritten();
Richard Smith9a561d52012-02-26 09:11:52 +00007272
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007273 return Destructor;
7274}
7275
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007276void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007277 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007278 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007279 !Destructor->doesThisDeclarationHaveABody() &&
7280 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007281 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007282 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007283 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007284
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007285 if (Destructor->isInvalidDecl())
7286 return;
7287
Douglas Gregor39957dc2010-05-01 15:04:51 +00007288 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007289
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007290 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007291 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7292 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007293
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007294 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007295 Diag(CurrentLocation, diag::note_member_synthesized_at)
7296 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7297
7298 Destructor->setInvalidDecl();
7299 return;
7300 }
7301
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007302 SourceLocation Loc = Destructor->getLocation();
7303 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007304 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007305 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007306 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007307
7308 if (ASTMutationListener *L = getASTMutationListener()) {
7309 L->CompletedImplicitDefinition(Destructor);
7310 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007311}
7312
Sebastian Redl0ee33912011-05-19 05:13:44 +00007313void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7314 CXXDestructorDecl *destructor) {
7315 // C++11 [class.dtor]p3:
7316 // A declaration of a destructor that does not have an exception-
7317 // specification is implicitly considered to have the same exception-
7318 // specification as an implicit declaration.
7319 const FunctionProtoType *dtorType = destructor->getType()->
7320 getAs<FunctionProtoType>();
7321 if (dtorType->hasExceptionSpec())
7322 return;
7323
7324 ImplicitExceptionSpecification exceptSpec =
7325 ComputeDefaultedDtorExceptionSpec(classDecl);
7326
Chandler Carruth3f224b22011-09-20 04:55:26 +00007327 // Replace the destructor's type, building off the existing one. Fortunately,
7328 // the only thing of interest in the destructor type is its extended info.
7329 // The return and arguments are fixed.
7330 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007331 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7332 epi.NumExceptions = exceptSpec.size();
7333 epi.Exceptions = exceptSpec.data();
7334 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7335
7336 destructor->setType(ty);
7337
7338 // FIXME: If the destructor has a body that could throw, and the newly created
7339 // spec doesn't allow exceptions, we should emit a warning, because this
7340 // change in behavior can break conforming C++03 programs at runtime.
7341 // However, we don't have a body yet, so it needs to be done somewhere else.
7342}
7343
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007344/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007345/// \c To.
7346///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007347/// This routine is used to copy/move the members of a class with an
7348/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007349/// copied are arrays, this routine builds for loops to copy them.
7350///
7351/// \param S The Sema object used for type-checking.
7352///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007353/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007354///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007355/// \param T The type of the expressions being copied/moved. Both expressions
7356/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007357///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007358/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007359///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007360/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007361///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007362/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007363/// Otherwise, it's a non-static member subobject.
7364///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007365/// \param Copying Whether we're copying or moving.
7366///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007367/// \param Depth Internal parameter recording the depth of the recursion.
7368///
7369/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007370static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007371BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007372 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007373 bool CopyingBaseSubobject, bool Copying,
7374 unsigned Depth = 0) {
7375 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007376 // Each subobject is assigned in the manner appropriate to its type:
7377 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007378 // - if the subobject is of class type, as if by a call to operator= with
7379 // the subobject as the object expression and the corresponding
7380 // subobject of x as a single function argument (as if by explicit
7381 // qualification; that is, ignoring any possible virtual overriding
7382 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007383 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7384 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7385
7386 // Look for operator=.
7387 DeclarationName Name
7388 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7389 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7390 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7391
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007392 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007393 LookupResult::Filter F = OpLookup.makeFilter();
7394 while (F.hasNext()) {
7395 NamedDecl *D = F.next();
7396 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Richard Smith1c931be2012-04-02 18:40:40 +00007397 if (Method->isCopyAssignmentOperator() ||
7398 (!Copying && Method->isMoveAssignmentOperator()))
Douglas Gregor06a9f362010-05-01 20:49:11 +00007399 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007400
Douglas Gregor06a9f362010-05-01 20:49:11 +00007401 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007402 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007403 F.done();
7404
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007405 // Suppress the protected check (C++ [class.protected]) for each of the
7406 // assignment operators we found. This strange dance is required when
7407 // we're assigning via a base classes's copy-assignment operator. To
7408 // ensure that we're getting the right base class subobject (without
7409 // ambiguities), we need to cast "this" to that subobject type; to
7410 // ensure that we don't go through the virtual call mechanism, we need
7411 // to qualify the operator= name with the base class (see below). However,
7412 // this means that if the base class has a protected copy assignment
7413 // operator, the protected member access check will fail. So, we
7414 // rewrite "protected" access to "public" access in this case, since we
7415 // know by construction that we're calling from a derived class.
7416 if (CopyingBaseSubobject) {
7417 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7418 L != LEnd; ++L) {
7419 if (L.getAccess() == AS_protected)
7420 L.setAccess(AS_public);
7421 }
7422 }
7423
Douglas Gregor06a9f362010-05-01 20:49:11 +00007424 // Create the nested-name-specifier that will be used to qualify the
7425 // reference to operator=; this is required to suppress the virtual
7426 // call mechanism.
7427 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007428 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007429 SS.MakeTrivial(S.Context,
7430 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007431 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007432 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007433
7434 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007435 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007436 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007437 /*TemplateKWLoc=*/SourceLocation(),
7438 /*FirstQualifierInScope=*/0,
7439 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007440 /*TemplateArgs=*/0,
7441 /*SuppressQualifierCheck=*/true);
7442 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007443 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007444
7445 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007446
John McCall60d7b3a2010-08-24 06:29:42 +00007447 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007448 OpEqualRef.takeAs<Expr>(),
7449 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007450 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007451 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007452
7453 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007454 }
John McCallb0207482010-03-16 06:11:48 +00007455
Douglas Gregor06a9f362010-05-01 20:49:11 +00007456 // - if the subobject is of scalar type, the built-in assignment
7457 // operator is used.
7458 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7459 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007460 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007461 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007462 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007463
7464 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007465 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007466
7467 // - if the subobject is an array, each element is assigned, in the
7468 // manner appropriate to the element type;
7469
7470 // Construct a loop over the array bounds, e.g.,
7471 //
7472 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7473 //
7474 // that will copy each of the array elements.
7475 QualType SizeType = S.Context.getSizeType();
7476
7477 // Create the iteration variable.
7478 IdentifierInfo *IterationVarName = 0;
7479 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007480 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007481 llvm::raw_svector_ostream OS(Str);
7482 OS << "__i" << Depth;
7483 IterationVarName = &S.Context.Idents.get(OS.str());
7484 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007485 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007486 IterationVarName, SizeType,
7487 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007488 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007489
7490 // Initialize the iteration variable to zero.
7491 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007492 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007493
7494 // Create a reference to the iteration variable; we'll use this several
7495 // times throughout.
7496 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007497 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007498 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007499 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7500 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7501
Douglas Gregor06a9f362010-05-01 20:49:11 +00007502 // Create the DeclStmt that holds the iteration variable.
7503 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7504
7505 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007506 llvm::APInt Upper
7507 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007508 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007509 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007510 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7511 BO_NE, S.Context.BoolTy,
7512 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007513
7514 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007515 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007516 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7517 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007518
7519 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007520 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007521 IterationVarRefRVal,
7522 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007523 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007524 IterationVarRefRVal,
7525 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007526 if (!Copying) // Cast to rvalue
7527 From = CastForMoving(S, From);
7528
7529 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007530 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7531 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007532 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007533 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007534 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007535
7536 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007537 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007538 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007539 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007540 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007541}
7542
Sean Hunt30de05c2011-05-14 05:23:20 +00007543std::pair<Sema::ImplicitExceptionSpecification, bool>
7544Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7545 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007546 if (ClassDecl->isInvalidDecl())
7547 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7548
Douglas Gregord3c35902010-07-01 16:36:15 +00007549 // C++ [class.copy]p10:
7550 // If the class definition does not explicitly declare a copy
7551 // assignment operator, one is declared implicitly.
7552 // The implicitly-defined copy assignment operator for a class X
7553 // will have the form
7554 //
7555 // X& X::operator=(const X&)
7556 //
7557 // if
7558 bool HasConstCopyAssignment = true;
7559
7560 // -- each direct base class B of X has a copy assignment operator
7561 // whose parameter is of type const B&, const volatile B& or B,
7562 // and
7563 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7564 BaseEnd = ClassDecl->bases_end();
7565 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007566 // We'll handle this below
7567 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7568 continue;
7569
Douglas Gregord3c35902010-07-01 16:36:15 +00007570 assert(!Base->getType()->isDependentType() &&
7571 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007572 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7573 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7574 &HasConstCopyAssignment);
7575 }
7576
Richard Smithebaf0e62011-10-18 20:49:44 +00007577 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007578 if (LangOpts.CPlusPlus0x) {
7579 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7580 BaseEnd = ClassDecl->vbases_end();
7581 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7582 assert(!Base->getType()->isDependentType() &&
7583 "Cannot generate implicit members for class with dependent bases.");
7584 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7585 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7586 &HasConstCopyAssignment);
7587 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007588 }
7589
7590 // -- for all the nonstatic data members of X that are of a class
7591 // type M (or array thereof), each such class type has a copy
7592 // assignment operator whose parameter is of type const M&,
7593 // const volatile M& or M.
7594 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7595 FieldEnd = ClassDecl->field_end();
7596 HasConstCopyAssignment && Field != FieldEnd;
7597 ++Field) {
7598 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007599 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7600 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7601 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007602 }
7603 }
7604
7605 // Otherwise, the implicitly declared copy assignment operator will
7606 // have the form
7607 //
7608 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007609
Douglas Gregorb87786f2010-07-01 17:48:08 +00007610 // C++ [except.spec]p14:
7611 // An implicitly declared special member function (Clause 12) shall have an
7612 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007613
7614 // It is unspecified whether or not an implicit copy assignment operator
7615 // attempts to deduplicate calls to assignment operators of virtual bases are
7616 // made. As such, this exception specification is effectively unspecified.
7617 // Based on a similar decision made for constness in C++0x, we're erring on
7618 // the side of assuming such calls to be made regardless of whether they
7619 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007620 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007621 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007622 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7623 BaseEnd = ClassDecl->bases_end();
7624 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007625 if (Base->isVirtual())
7626 continue;
7627
Douglas Gregora376d102010-07-02 21:50:04 +00007628 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007629 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007630 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7631 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007632 ExceptSpec.CalledDecl(CopyAssign);
7633 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007634
7635 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7636 BaseEnd = ClassDecl->vbases_end();
7637 Base != BaseEnd; ++Base) {
7638 CXXRecordDecl *BaseClassDecl
7639 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7640 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7641 ArgQuals, false, 0))
7642 ExceptSpec.CalledDecl(CopyAssign);
7643 }
7644
Douglas Gregorb87786f2010-07-01 17:48:08 +00007645 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7646 FieldEnd = ClassDecl->field_end();
7647 Field != FieldEnd;
7648 ++Field) {
7649 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007650 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7651 if (CXXMethodDecl *CopyAssign =
7652 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7653 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007654 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007655 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007656
Sean Hunt30de05c2011-05-14 05:23:20 +00007657 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7658}
7659
7660CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7661 // Note: The following rules are largely analoguous to the copy
7662 // constructor rules. Note that virtual bases are not taken into account
7663 // for determining the argument type of the operator. Note also that
7664 // operators taking an object instead of a reference are allowed.
7665
7666 ImplicitExceptionSpecification Spec(Context);
7667 bool Const;
7668 llvm::tie(Spec, Const) =
7669 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7670
7671 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7672 QualType RetType = Context.getLValueReferenceType(ArgType);
7673 if (Const)
7674 ArgType = ArgType.withConst();
7675 ArgType = Context.getLValueReferenceType(ArgType);
7676
Douglas Gregord3c35902010-07-01 16:36:15 +00007677 // An implicitly-declared copy assignment operator is an inline public
7678 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007679 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007680 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007681 SourceLocation ClassLoc = ClassDecl->getLocation();
7682 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007683 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007684 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007685 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007686 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007687 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007688 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007689 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007690 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007691 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007692 CopyAssignment->setImplicit();
7693 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007694
7695 // Add the parameter to the operator.
7696 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007697 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007698 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007699 SC_None,
7700 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007701 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007702
Douglas Gregora376d102010-07-02 21:50:04 +00007703 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007704 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007705
Douglas Gregor23c94db2010-07-02 17:43:08 +00007706 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007707 PushOnScopeChains(CopyAssignment, S, false);
7708 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007709
Nico Weberafcc96a2012-01-23 03:19:29 +00007710 // C++0x [class.copy]p19:
7711 // .... If the class definition does not explicitly declare a copy
7712 // assignment operator, there is no user-declared move constructor, and
7713 // there is no user-declared move assignment operator, a copy assignment
7714 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00007715 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007716 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00007717
Douglas Gregord3c35902010-07-01 16:36:15 +00007718 AddOverriddenMethods(ClassDecl, CopyAssignment);
7719 return CopyAssignment;
7720}
7721
Douglas Gregor06a9f362010-05-01 20:49:11 +00007722void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7723 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007724 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007725 CopyAssignOperator->isOverloadedOperator() &&
7726 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007727 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7728 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007729 "DefineImplicitCopyAssignment called for wrong function");
7730
7731 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7732
7733 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7734 CopyAssignOperator->setInvalidDecl();
7735 return;
7736 }
7737
7738 CopyAssignOperator->setUsed();
7739
7740 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007741 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007742
7743 // C++0x [class.copy]p30:
7744 // The implicitly-defined or explicitly-defaulted copy assignment operator
7745 // for a non-union class X performs memberwise copy assignment of its
7746 // subobjects. The direct base classes of X are assigned first, in the
7747 // order of their declaration in the base-specifier-list, and then the
7748 // immediate non-static data members of X are assigned, in the order in
7749 // which they were declared in the class definition.
7750
7751 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007752 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007753
7754 // The parameter for the "other" object, which we are copying from.
7755 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7756 Qualifiers OtherQuals = Other->getType().getQualifiers();
7757 QualType OtherRefType = Other->getType();
7758 if (const LValueReferenceType *OtherRef
7759 = OtherRefType->getAs<LValueReferenceType>()) {
7760 OtherRefType = OtherRef->getPointeeType();
7761 OtherQuals = OtherRefType.getQualifiers();
7762 }
7763
7764 // Our location for everything implicitly-generated.
7765 SourceLocation Loc = CopyAssignOperator->getLocation();
7766
7767 // Construct a reference to the "other" object. We'll be using this
7768 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007769 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007770 assert(OtherRef && "Reference to parameter cannot fail!");
7771
7772 // Construct the "this" pointer. We'll be using this throughout the generated
7773 // ASTs.
7774 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7775 assert(This && "Reference to this cannot fail!");
7776
7777 // Assign base classes.
7778 bool Invalid = false;
7779 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7780 E = ClassDecl->bases_end(); Base != E; ++Base) {
7781 // Form the assignment:
7782 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7783 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007784 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007785 Invalid = true;
7786 continue;
7787 }
7788
John McCallf871d0c2010-08-07 06:22:56 +00007789 CXXCastPath BasePath;
7790 BasePath.push_back(Base);
7791
Douglas Gregor06a9f362010-05-01 20:49:11 +00007792 // Construct the "from" expression, which is an implicit cast to the
7793 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007794 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007795 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7796 CK_UncheckedDerivedToBase,
7797 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007798
7799 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007800 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007801
7802 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007803 To = ImpCastExprToType(To.take(),
7804 Context.getCVRQualifiedType(BaseType,
7805 CopyAssignOperator->getTypeQualifiers()),
7806 CK_UncheckedDerivedToBase,
7807 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007808
7809 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007810 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007811 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007812 /*CopyingBaseSubobject=*/true,
7813 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007814 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007815 Diag(CurrentLocation, diag::note_member_synthesized_at)
7816 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7817 CopyAssignOperator->setInvalidDecl();
7818 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007819 }
7820
7821 // Success! Record the copy.
7822 Statements.push_back(Copy.takeAs<Expr>());
7823 }
7824
7825 // \brief Reference to the __builtin_memcpy function.
7826 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007827 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007828 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007829
7830 // Assign non-static members.
7831 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7832 FieldEnd = ClassDecl->field_end();
7833 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007834 if (Field->isUnnamedBitfield())
7835 continue;
7836
Douglas Gregor06a9f362010-05-01 20:49:11 +00007837 // Check for members of reference type; we can't copy those.
7838 if (Field->getType()->isReferenceType()) {
7839 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7840 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7841 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007842 Diag(CurrentLocation, diag::note_member_synthesized_at)
7843 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007844 Invalid = true;
7845 continue;
7846 }
7847
7848 // Check for members of const-qualified, non-class type.
7849 QualType BaseType = Context.getBaseElementType(Field->getType());
7850 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7851 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7852 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7853 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007854 Diag(CurrentLocation, diag::note_member_synthesized_at)
7855 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007856 Invalid = true;
7857 continue;
7858 }
John McCallb77115d2011-06-17 00:18:42 +00007859
7860 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007861 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7862 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007863
7864 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007865 if (FieldType->isIncompleteArrayType()) {
7866 assert(ClassDecl->hasFlexibleArrayMember() &&
7867 "Incomplete array type is not valid");
7868 continue;
7869 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007870
7871 // Build references to the field in the object we're copying from and to.
7872 CXXScopeSpec SS; // Intentionally empty
7873 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7874 LookupMemberName);
7875 MemberLookup.addDecl(*Field);
7876 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007877 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007878 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007879 SS, SourceLocation(), 0,
7880 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007881 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007882 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007883 SS, SourceLocation(), 0,
7884 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007885 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7886 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7887
7888 // If the field should be copied with __builtin_memcpy rather than via
7889 // explicit assignments, do so. This optimization only applies for arrays
7890 // of scalars and arrays of class type with trivial copy-assignment
7891 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007892 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007893 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007894 // Compute the size of the memory buffer to be copied.
7895 QualType SizeType = Context.getSizeType();
7896 llvm::APInt Size(Context.getTypeSize(SizeType),
7897 Context.getTypeSizeInChars(BaseType).getQuantity());
7898 for (const ConstantArrayType *Array
7899 = Context.getAsConstantArrayType(FieldType);
7900 Array;
7901 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007902 llvm::APInt ArraySize
7903 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007904 Size *= ArraySize;
7905 }
7906
7907 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007908 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7909 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007910
7911 bool NeedsCollectableMemCpy =
7912 (BaseType->isRecordType() &&
7913 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7914
7915 if (NeedsCollectableMemCpy) {
7916 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007917 // Create a reference to the __builtin_objc_memmove_collectable function.
7918 LookupResult R(*this,
7919 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007920 Loc, LookupOrdinaryName);
7921 LookupName(R, TUScope, true);
7922
7923 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7924 if (!CollectableMemCpy) {
7925 // Something went horribly wrong earlier, and we will have
7926 // complained about it.
7927 Invalid = true;
7928 continue;
7929 }
7930
7931 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7932 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007933 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007934 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7935 }
7936 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007937 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007938 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007939 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7940 LookupOrdinaryName);
7941 LookupName(R, TUScope, true);
7942
7943 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7944 if (!BuiltinMemCpy) {
7945 // Something went horribly wrong earlier, and we will have complained
7946 // about it.
7947 Invalid = true;
7948 continue;
7949 }
7950
7951 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7952 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007953 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007954 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7955 }
7956
John McCallca0408f2010-08-23 06:44:23 +00007957 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007958 CallArgs.push_back(To.takeAs<Expr>());
7959 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007960 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007961 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007962 if (NeedsCollectableMemCpy)
7963 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007964 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007965 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007966 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007967 else
7968 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007969 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007970 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007971 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007972
Douglas Gregor06a9f362010-05-01 20:49:11 +00007973 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7974 Statements.push_back(Call.takeAs<Expr>());
7975 continue;
7976 }
7977
7978 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007979 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007980 To.get(), From.get(),
7981 /*CopyingBaseSubobject=*/false,
7982 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007983 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007984 Diag(CurrentLocation, diag::note_member_synthesized_at)
7985 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7986 CopyAssignOperator->setInvalidDecl();
7987 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007988 }
7989
7990 // Success! Record the copy.
7991 Statements.push_back(Copy.takeAs<Stmt>());
7992 }
7993
7994 if (!Invalid) {
7995 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007996 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007997
John McCall60d7b3a2010-08-24 06:29:42 +00007998 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007999 if (Return.isInvalid())
8000 Invalid = true;
8001 else {
8002 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008003
8004 if (Trap.hasErrorOccurred()) {
8005 Diag(CurrentLocation, diag::note_member_synthesized_at)
8006 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8007 Invalid = true;
8008 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008009 }
8010 }
8011
8012 if (Invalid) {
8013 CopyAssignOperator->setInvalidDecl();
8014 return;
8015 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008016
8017 StmtResult Body;
8018 {
8019 CompoundScopeRAII CompoundScope(*this);
8020 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8021 /*isStmtExpr=*/false);
8022 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8023 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008024 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008025
8026 if (ASTMutationListener *L = getASTMutationListener()) {
8027 L->CompletedImplicitDefinition(CopyAssignOperator);
8028 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008029}
8030
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008031Sema::ImplicitExceptionSpecification
8032Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8033 ImplicitExceptionSpecification ExceptSpec(Context);
8034
8035 if (ClassDecl->isInvalidDecl())
8036 return ExceptSpec;
8037
8038 // C++0x [except.spec]p14:
8039 // An implicitly declared special member function (Clause 12) shall have an
8040 // exception-specification. [...]
8041
8042 // It is unspecified whether or not an implicit move assignment operator
8043 // attempts to deduplicate calls to assignment operators of virtual bases are
8044 // made. As such, this exception specification is effectively unspecified.
8045 // Based on a similar decision made for constness in C++0x, we're erring on
8046 // the side of assuming such calls to be made regardless of whether they
8047 // actually happen.
8048 // Note that a move constructor is not implicitly declared when there are
8049 // virtual bases, but it can still be user-declared and explicitly defaulted.
8050 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8051 BaseEnd = ClassDecl->bases_end();
8052 Base != BaseEnd; ++Base) {
8053 if (Base->isVirtual())
8054 continue;
8055
8056 CXXRecordDecl *BaseClassDecl
8057 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8058 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8059 false, 0))
8060 ExceptSpec.CalledDecl(MoveAssign);
8061 }
8062
8063 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8064 BaseEnd = ClassDecl->vbases_end();
8065 Base != BaseEnd; ++Base) {
8066 CXXRecordDecl *BaseClassDecl
8067 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8068 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8069 false, 0))
8070 ExceptSpec.CalledDecl(MoveAssign);
8071 }
8072
8073 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8074 FieldEnd = ClassDecl->field_end();
8075 Field != FieldEnd;
8076 ++Field) {
8077 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8078 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8079 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8080 false, 0))
8081 ExceptSpec.CalledDecl(MoveAssign);
8082 }
8083 }
8084
8085 return ExceptSpec;
8086}
8087
Richard Smith1c931be2012-04-02 18:40:40 +00008088/// Determine whether the class type has any direct or indirect virtual base
8089/// classes which have a non-trivial move assignment operator.
8090static bool
8091hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8092 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8093 BaseEnd = ClassDecl->vbases_end();
8094 Base != BaseEnd; ++Base) {
8095 CXXRecordDecl *BaseClass =
8096 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8097
8098 // Try to declare the move assignment. If it would be deleted, then the
8099 // class does not have a non-trivial move assignment.
8100 if (BaseClass->needsImplicitMoveAssignment())
8101 S.DeclareImplicitMoveAssignment(BaseClass);
8102
8103 // If the class has both a trivial move assignment and a non-trivial move
8104 // assignment, hasTrivialMoveAssignment() is false.
8105 if (BaseClass->hasDeclaredMoveAssignment() &&
8106 !BaseClass->hasTrivialMoveAssignment())
8107 return true;
8108 }
8109
8110 return false;
8111}
8112
8113/// Determine whether the given type either has a move constructor or is
8114/// trivially copyable.
8115static bool
8116hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8117 Type = S.Context.getBaseElementType(Type);
8118
8119 // FIXME: Technically, non-trivially-copyable non-class types, such as
8120 // reference types, are supposed to return false here, but that appears
8121 // to be a standard defect.
8122 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
8123 if (!ClassDecl)
8124 return true;
8125
8126 if (Type.isTriviallyCopyableType(S.Context))
8127 return true;
8128
8129 if (IsConstructor) {
8130 if (ClassDecl->needsImplicitMoveConstructor())
8131 S.DeclareImplicitMoveConstructor(ClassDecl);
8132 return ClassDecl->hasDeclaredMoveConstructor();
8133 }
8134
8135 if (ClassDecl->needsImplicitMoveAssignment())
8136 S.DeclareImplicitMoveAssignment(ClassDecl);
8137 return ClassDecl->hasDeclaredMoveAssignment();
8138}
8139
8140/// Determine whether all non-static data members and direct or virtual bases
8141/// of class \p ClassDecl have either a move operation, or are trivially
8142/// copyable.
8143static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8144 bool IsConstructor) {
8145 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8146 BaseEnd = ClassDecl->bases_end();
8147 Base != BaseEnd; ++Base) {
8148 if (Base->isVirtual())
8149 continue;
8150
8151 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8152 return false;
8153 }
8154
8155 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8156 BaseEnd = ClassDecl->vbases_end();
8157 Base != BaseEnd; ++Base) {
8158 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8159 return false;
8160 }
8161
8162 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8163 FieldEnd = ClassDecl->field_end();
8164 Field != FieldEnd; ++Field) {
8165 if (!hasMoveOrIsTriviallyCopyable(S, (*Field)->getType(), IsConstructor))
8166 return false;
8167 }
8168
8169 return true;
8170}
8171
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008172CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008173 // C++11 [class.copy]p20:
8174 // If the definition of a class X does not explicitly declare a move
8175 // assignment operator, one will be implicitly declared as defaulted
8176 // if and only if:
8177 //
8178 // - [first 4 bullets]
8179 assert(ClassDecl->needsImplicitMoveAssignment());
8180
8181 // [Checked after we build the declaration]
8182 // - the move assignment operator would not be implicitly defined as
8183 // deleted,
8184
8185 // [DR1402]:
8186 // - X has no direct or indirect virtual base class with a non-trivial
8187 // move assignment operator, and
8188 // - each of X's non-static data members and direct or virtual base classes
8189 // has a type that either has a move assignment operator or is trivially
8190 // copyable.
8191 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8192 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8193 ClassDecl->setFailedImplicitMoveAssignment();
8194 return 0;
8195 }
8196
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008197 // Note: The following rules are largely analoguous to the move
8198 // constructor rules.
8199
8200 ImplicitExceptionSpecification Spec(
8201 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8202
8203 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8204 QualType RetType = Context.getLValueReferenceType(ArgType);
8205 ArgType = Context.getRValueReferenceType(ArgType);
8206
8207 // An implicitly-declared move assignment operator is an inline public
8208 // member of its class.
8209 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8210 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8211 SourceLocation ClassLoc = ClassDecl->getLocation();
8212 DeclarationNameInfo NameInfo(Name, ClassLoc);
8213 CXXMethodDecl *MoveAssignment
8214 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8215 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8216 /*TInfo=*/0, /*isStatic=*/false,
8217 /*StorageClassAsWritten=*/SC_None,
8218 /*isInline=*/true,
8219 /*isConstexpr=*/false,
8220 SourceLocation());
8221 MoveAssignment->setAccess(AS_public);
8222 MoveAssignment->setDefaulted();
8223 MoveAssignment->setImplicit();
8224 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8225
8226 // Add the parameter to the operator.
8227 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8228 ClassLoc, ClassLoc, /*Id=*/0,
8229 ArgType, /*TInfo=*/0,
8230 SC_None,
8231 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008232 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008233
8234 // Note that we have added this copy-assignment operator.
8235 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8236
8237 // C++0x [class.copy]p9:
8238 // If the definition of a class X does not explicitly declare a move
8239 // assignment operator, one will be implicitly declared as defaulted if and
8240 // only if:
8241 // [...]
8242 // - the move assignment operator would not be implicitly defined as
8243 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008244 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008245 // Cache this result so that we don't try to generate this over and over
8246 // on every lookup, leaking memory and wasting time.
8247 ClassDecl->setFailedImplicitMoveAssignment();
8248 return 0;
8249 }
8250
8251 if (Scope *S = getScopeForContext(ClassDecl))
8252 PushOnScopeChains(MoveAssignment, S, false);
8253 ClassDecl->addDecl(MoveAssignment);
8254
8255 AddOverriddenMethods(ClassDecl, MoveAssignment);
8256 return MoveAssignment;
8257}
8258
8259void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8260 CXXMethodDecl *MoveAssignOperator) {
8261 assert((MoveAssignOperator->isDefaulted() &&
8262 MoveAssignOperator->isOverloadedOperator() &&
8263 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008264 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8265 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008266 "DefineImplicitMoveAssignment called for wrong function");
8267
8268 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8269
8270 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8271 MoveAssignOperator->setInvalidDecl();
8272 return;
8273 }
8274
8275 MoveAssignOperator->setUsed();
8276
8277 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8278 DiagnosticErrorTrap Trap(Diags);
8279
8280 // C++0x [class.copy]p28:
8281 // The implicitly-defined or move assignment operator for a non-union class
8282 // X performs memberwise move assignment of its subobjects. The direct base
8283 // classes of X are assigned first, in the order of their declaration in the
8284 // base-specifier-list, and then the immediate non-static data members of X
8285 // are assigned, in the order in which they were declared in the class
8286 // definition.
8287
8288 // The statements that form the synthesized function body.
8289 ASTOwningVector<Stmt*> Statements(*this);
8290
8291 // The parameter for the "other" object, which we are move from.
8292 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8293 QualType OtherRefType = Other->getType()->
8294 getAs<RValueReferenceType>()->getPointeeType();
8295 assert(OtherRefType.getQualifiers() == 0 &&
8296 "Bad argument type of defaulted move assignment");
8297
8298 // Our location for everything implicitly-generated.
8299 SourceLocation Loc = MoveAssignOperator->getLocation();
8300
8301 // Construct a reference to the "other" object. We'll be using this
8302 // throughout the generated ASTs.
8303 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8304 assert(OtherRef && "Reference to parameter cannot fail!");
8305 // Cast to rvalue.
8306 OtherRef = CastForMoving(*this, OtherRef);
8307
8308 // Construct the "this" pointer. We'll be using this throughout the generated
8309 // ASTs.
8310 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8311 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008312
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008313 // Assign base classes.
8314 bool Invalid = false;
8315 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8316 E = ClassDecl->bases_end(); Base != E; ++Base) {
8317 // Form the assignment:
8318 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8319 QualType BaseType = Base->getType().getUnqualifiedType();
8320 if (!BaseType->isRecordType()) {
8321 Invalid = true;
8322 continue;
8323 }
8324
8325 CXXCastPath BasePath;
8326 BasePath.push_back(Base);
8327
8328 // Construct the "from" expression, which is an implicit cast to the
8329 // appropriately-qualified base type.
8330 Expr *From = OtherRef;
8331 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008332 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008333
8334 // Dereference "this".
8335 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8336
8337 // Implicitly cast "this" to the appropriately-qualified base type.
8338 To = ImpCastExprToType(To.take(),
8339 Context.getCVRQualifiedType(BaseType,
8340 MoveAssignOperator->getTypeQualifiers()),
8341 CK_UncheckedDerivedToBase,
8342 VK_LValue, &BasePath);
8343
8344 // Build the move.
8345 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8346 To.get(), From,
8347 /*CopyingBaseSubobject=*/true,
8348 /*Copying=*/false);
8349 if (Move.isInvalid()) {
8350 Diag(CurrentLocation, diag::note_member_synthesized_at)
8351 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8352 MoveAssignOperator->setInvalidDecl();
8353 return;
8354 }
8355
8356 // Success! Record the move.
8357 Statements.push_back(Move.takeAs<Expr>());
8358 }
8359
8360 // \brief Reference to the __builtin_memcpy function.
8361 Expr *BuiltinMemCpyRef = 0;
8362 // \brief Reference to the __builtin_objc_memmove_collectable function.
8363 Expr *CollectableMemCpyRef = 0;
8364
8365 // Assign non-static members.
8366 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8367 FieldEnd = ClassDecl->field_end();
8368 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008369 if (Field->isUnnamedBitfield())
8370 continue;
8371
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008372 // Check for members of reference type; we can't move those.
8373 if (Field->getType()->isReferenceType()) {
8374 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8375 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8376 Diag(Field->getLocation(), diag::note_declared_at);
8377 Diag(CurrentLocation, diag::note_member_synthesized_at)
8378 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8379 Invalid = true;
8380 continue;
8381 }
8382
8383 // Check for members of const-qualified, non-class type.
8384 QualType BaseType = Context.getBaseElementType(Field->getType());
8385 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8386 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8387 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8388 Diag(Field->getLocation(), diag::note_declared_at);
8389 Diag(CurrentLocation, diag::note_member_synthesized_at)
8390 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8391 Invalid = true;
8392 continue;
8393 }
8394
8395 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008396 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8397 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008398
8399 QualType FieldType = Field->getType().getNonReferenceType();
8400 if (FieldType->isIncompleteArrayType()) {
8401 assert(ClassDecl->hasFlexibleArrayMember() &&
8402 "Incomplete array type is not valid");
8403 continue;
8404 }
8405
8406 // Build references to the field in the object we're copying from and to.
8407 CXXScopeSpec SS; // Intentionally empty
8408 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8409 LookupMemberName);
8410 MemberLookup.addDecl(*Field);
8411 MemberLookup.resolveKind();
8412 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8413 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008414 SS, SourceLocation(), 0,
8415 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008416 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8417 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008418 SS, SourceLocation(), 0,
8419 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008420 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8421 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8422
8423 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8424 "Member reference with rvalue base must be rvalue except for reference "
8425 "members, which aren't allowed for move assignment.");
8426
8427 // If the field should be copied with __builtin_memcpy rather than via
8428 // explicit assignments, do so. This optimization only applies for arrays
8429 // of scalars and arrays of class type with trivial move-assignment
8430 // operators.
8431 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8432 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8433 // Compute the size of the memory buffer to be copied.
8434 QualType SizeType = Context.getSizeType();
8435 llvm::APInt Size(Context.getTypeSize(SizeType),
8436 Context.getTypeSizeInChars(BaseType).getQuantity());
8437 for (const ConstantArrayType *Array
8438 = Context.getAsConstantArrayType(FieldType);
8439 Array;
8440 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8441 llvm::APInt ArraySize
8442 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8443 Size *= ArraySize;
8444 }
8445
Douglas Gregor45d3d712011-09-01 02:09:07 +00008446 // Take the address of the field references for "from" and "to". We
8447 // directly construct UnaryOperators here because semantic analysis
8448 // does not permit us to take the address of an xvalue.
8449 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8450 Context.getPointerType(From.get()->getType()),
8451 VK_RValue, OK_Ordinary, Loc);
8452 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8453 Context.getPointerType(To.get()->getType()),
8454 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008455
8456 bool NeedsCollectableMemCpy =
8457 (BaseType->isRecordType() &&
8458 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8459
8460 if (NeedsCollectableMemCpy) {
8461 if (!CollectableMemCpyRef) {
8462 // Create a reference to the __builtin_objc_memmove_collectable function.
8463 LookupResult R(*this,
8464 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8465 Loc, LookupOrdinaryName);
8466 LookupName(R, TUScope, true);
8467
8468 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8469 if (!CollectableMemCpy) {
8470 // Something went horribly wrong earlier, and we will have
8471 // complained about it.
8472 Invalid = true;
8473 continue;
8474 }
8475
8476 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8477 CollectableMemCpy->getType(),
8478 VK_LValue, Loc, 0).take();
8479 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8480 }
8481 }
8482 // Create a reference to the __builtin_memcpy builtin function.
8483 else if (!BuiltinMemCpyRef) {
8484 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8485 LookupOrdinaryName);
8486 LookupName(R, TUScope, true);
8487
8488 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8489 if (!BuiltinMemCpy) {
8490 // Something went horribly wrong earlier, and we will have complained
8491 // about it.
8492 Invalid = true;
8493 continue;
8494 }
8495
8496 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8497 BuiltinMemCpy->getType(),
8498 VK_LValue, Loc, 0).take();
8499 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8500 }
8501
8502 ASTOwningVector<Expr*> CallArgs(*this);
8503 CallArgs.push_back(To.takeAs<Expr>());
8504 CallArgs.push_back(From.takeAs<Expr>());
8505 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8506 ExprResult Call = ExprError();
8507 if (NeedsCollectableMemCpy)
8508 Call = ActOnCallExpr(/*Scope=*/0,
8509 CollectableMemCpyRef,
8510 Loc, move_arg(CallArgs),
8511 Loc);
8512 else
8513 Call = ActOnCallExpr(/*Scope=*/0,
8514 BuiltinMemCpyRef,
8515 Loc, move_arg(CallArgs),
8516 Loc);
8517
8518 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8519 Statements.push_back(Call.takeAs<Expr>());
8520 continue;
8521 }
8522
8523 // Build the move of this field.
8524 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8525 To.get(), From.get(),
8526 /*CopyingBaseSubobject=*/false,
8527 /*Copying=*/false);
8528 if (Move.isInvalid()) {
8529 Diag(CurrentLocation, diag::note_member_synthesized_at)
8530 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8531 MoveAssignOperator->setInvalidDecl();
8532 return;
8533 }
8534
8535 // Success! Record the copy.
8536 Statements.push_back(Move.takeAs<Stmt>());
8537 }
8538
8539 if (!Invalid) {
8540 // Add a "return *this;"
8541 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8542
8543 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8544 if (Return.isInvalid())
8545 Invalid = true;
8546 else {
8547 Statements.push_back(Return.takeAs<Stmt>());
8548
8549 if (Trap.hasErrorOccurred()) {
8550 Diag(CurrentLocation, diag::note_member_synthesized_at)
8551 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8552 Invalid = true;
8553 }
8554 }
8555 }
8556
8557 if (Invalid) {
8558 MoveAssignOperator->setInvalidDecl();
8559 return;
8560 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008561
8562 StmtResult Body;
8563 {
8564 CompoundScopeRAII CompoundScope(*this);
8565 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8566 /*isStmtExpr=*/false);
8567 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8568 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008569 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8570
8571 if (ASTMutationListener *L = getASTMutationListener()) {
8572 L->CompletedImplicitDefinition(MoveAssignOperator);
8573 }
8574}
8575
Sean Hunt49634cf2011-05-13 06:10:58 +00008576std::pair<Sema::ImplicitExceptionSpecification, bool>
8577Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008578 if (ClassDecl->isInvalidDecl())
8579 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8580
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008581 // C++ [class.copy]p5:
8582 // The implicitly-declared copy constructor for a class X will
8583 // have the form
8584 //
8585 // X::X(const X&)
8586 //
8587 // if
Sean Huntc530d172011-06-10 04:44:37 +00008588 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008589 bool HasConstCopyConstructor = true;
8590
8591 // -- each direct or virtual base class B of X has a copy
8592 // constructor whose first parameter is of type const B& or
8593 // const volatile B&, and
8594 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8595 BaseEnd = ClassDecl->bases_end();
8596 HasConstCopyConstructor && Base != BaseEnd;
8597 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008598 // Virtual bases are handled below.
8599 if (Base->isVirtual())
8600 continue;
8601
Douglas Gregor22584312010-07-02 23:41:54 +00008602 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008603 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008604 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8605 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008606 }
8607
8608 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8609 BaseEnd = ClassDecl->vbases_end();
8610 HasConstCopyConstructor && Base != BaseEnd;
8611 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008612 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008613 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008614 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8615 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008616 }
8617
8618 // -- for all the nonstatic data members of X that are of a
8619 // class type M (or array thereof), each such class type
8620 // has a copy constructor whose first parameter is of type
8621 // const M& or const volatile M&.
8622 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8623 FieldEnd = ClassDecl->field_end();
8624 HasConstCopyConstructor && Field != FieldEnd;
8625 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008626 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008627 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008628 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8629 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008630 }
8631 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008632 // Otherwise, the implicitly declared copy constructor will have
8633 // the form
8634 //
8635 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008636
Douglas Gregor0d405db2010-07-01 20:59:04 +00008637 // C++ [except.spec]p14:
8638 // An implicitly declared special member function (Clause 12) shall have an
8639 // exception-specification. [...]
8640 ImplicitExceptionSpecification ExceptSpec(Context);
8641 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8642 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8643 BaseEnd = ClassDecl->bases_end();
8644 Base != BaseEnd;
8645 ++Base) {
8646 // Virtual bases are handled below.
8647 if (Base->isVirtual())
8648 continue;
8649
Douglas Gregor22584312010-07-02 23:41:54 +00008650 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008651 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008652 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008653 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008654 ExceptSpec.CalledDecl(CopyConstructor);
8655 }
8656 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8657 BaseEnd = ClassDecl->vbases_end();
8658 Base != BaseEnd;
8659 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008660 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008661 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008662 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008663 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008664 ExceptSpec.CalledDecl(CopyConstructor);
8665 }
8666 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8667 FieldEnd = ClassDecl->field_end();
8668 Field != FieldEnd;
8669 ++Field) {
8670 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008671 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8672 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008673 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008674 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008675 }
8676 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008677
Sean Hunt49634cf2011-05-13 06:10:58 +00008678 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8679}
8680
8681CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8682 CXXRecordDecl *ClassDecl) {
8683 // C++ [class.copy]p4:
8684 // If the class definition does not explicitly declare a copy
8685 // constructor, one is declared implicitly.
8686
8687 ImplicitExceptionSpecification Spec(Context);
8688 bool Const;
8689 llvm::tie(Spec, Const) =
8690 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8691
8692 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8693 QualType ArgType = ClassType;
8694 if (Const)
8695 ArgType = ArgType.withConst();
8696 ArgType = Context.getLValueReferenceType(ArgType);
8697
8698 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8699
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008700 DeclarationName Name
8701 = Context.DeclarationNames.getCXXConstructorName(
8702 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008703 SourceLocation ClassLoc = ClassDecl->getLocation();
8704 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008705
8706 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008707 // member of its class.
8708 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8709 Context, ClassDecl, ClassLoc, NameInfo,
8710 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8711 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8712 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008713 getLangOpts().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008714 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008715 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008716 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008717
Douglas Gregor22584312010-07-02 23:41:54 +00008718 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008719 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8720
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008721 // Add the parameter to the constructor.
8722 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008723 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008724 /*IdentifierInfo=*/0,
8725 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008726 SC_None,
8727 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008728 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008729
Douglas Gregor23c94db2010-07-02 17:43:08 +00008730 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008731 PushOnScopeChains(CopyConstructor, S, false);
8732 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008733
Nico Weberafcc96a2012-01-23 03:19:29 +00008734 // C++11 [class.copy]p8:
8735 // ... If the class definition does not explicitly declare a copy
8736 // constructor, there is no user-declared move constructor, and there is no
8737 // user-declared move assignment operator, a copy constructor is implicitly
8738 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008739 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008740 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008741
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008742 return CopyConstructor;
8743}
8744
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008745void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008746 CXXConstructorDecl *CopyConstructor) {
8747 assert((CopyConstructor->isDefaulted() &&
8748 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008749 !CopyConstructor->doesThisDeclarationHaveABody() &&
8750 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008751 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008752
Anders Carlsson63010a72010-04-23 16:24:12 +00008753 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008754 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008755
Douglas Gregor39957dc2010-05-01 15:04:51 +00008756 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008757 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008758
Sean Huntcbb67482011-01-08 20:30:50 +00008759 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008760 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008761 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008762 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008763 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008764 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008765 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008766 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8767 CopyConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008768 MultiStmtArg(*this, 0, 0),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008769 /*isStmtExpr=*/false)
8770 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008771 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008772 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008773
8774 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008775 if (ASTMutationListener *L = getASTMutationListener()) {
8776 L->CompletedImplicitDefinition(CopyConstructor);
8777 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008778}
8779
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008780Sema::ImplicitExceptionSpecification
8781Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8782 // C++ [except.spec]p14:
8783 // An implicitly declared special member function (Clause 12) shall have an
8784 // exception-specification. [...]
8785 ImplicitExceptionSpecification ExceptSpec(Context);
8786 if (ClassDecl->isInvalidDecl())
8787 return ExceptSpec;
8788
8789 // Direct base-class constructors.
8790 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8791 BEnd = ClassDecl->bases_end();
8792 B != BEnd; ++B) {
8793 if (B->isVirtual()) // Handled below.
8794 continue;
8795
8796 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8797 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8798 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8799 // If this is a deleted function, add it anyway. This might be conformant
8800 // with the standard. This might not. I'm not sure. It might not matter.
8801 if (Constructor)
8802 ExceptSpec.CalledDecl(Constructor);
8803 }
8804 }
8805
8806 // Virtual base-class constructors.
8807 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8808 BEnd = ClassDecl->vbases_end();
8809 B != BEnd; ++B) {
8810 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8811 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8812 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8813 // If this is a deleted function, add it anyway. This might be conformant
8814 // with the standard. This might not. I'm not sure. It might not matter.
8815 if (Constructor)
8816 ExceptSpec.CalledDecl(Constructor);
8817 }
8818 }
8819
8820 // Field constructors.
8821 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8822 FEnd = ClassDecl->field_end();
8823 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008824 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008825 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8826 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8827 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8828 // If this is a deleted function, add it anyway. This might be conformant
8829 // with the standard. This might not. I'm not sure. It might not matter.
8830 // In particular, the problem is that this function never gets called. It
8831 // might just be ill-formed because this function attempts to refer to
8832 // a deleted function here.
8833 if (Constructor)
8834 ExceptSpec.CalledDecl(Constructor);
8835 }
8836 }
8837
8838 return ExceptSpec;
8839}
8840
8841CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8842 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008843 // C++11 [class.copy]p9:
8844 // If the definition of a class X does not explicitly declare a move
8845 // constructor, one will be implicitly declared as defaulted if and only if:
8846 //
8847 // - [first 4 bullets]
8848 assert(ClassDecl->needsImplicitMoveConstructor());
8849
8850 // [Checked after we build the declaration]
8851 // - the move assignment operator would not be implicitly defined as
8852 // deleted,
8853
8854 // [DR1402]:
8855 // - each of X's non-static data members and direct or virtual base classes
8856 // has a type that either has a move constructor or is trivially copyable.
8857 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8858 ClassDecl->setFailedImplicitMoveConstructor();
8859 return 0;
8860 }
8861
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008862 ImplicitExceptionSpecification Spec(
8863 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8864
8865 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8866 QualType ArgType = Context.getRValueReferenceType(ClassType);
8867
8868 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8869
8870 DeclarationName Name
8871 = Context.DeclarationNames.getCXXConstructorName(
8872 Context.getCanonicalType(ClassType));
8873 SourceLocation ClassLoc = ClassDecl->getLocation();
8874 DeclarationNameInfo NameInfo(Name, ClassLoc);
8875
8876 // C++0x [class.copy]p11:
8877 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008878 // member of its class.
8879 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8880 Context, ClassDecl, ClassLoc, NameInfo,
8881 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8882 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8883 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008884 getLangOpts().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008885 MoveConstructor->setAccess(AS_public);
8886 MoveConstructor->setDefaulted();
8887 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008888
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008889 // Add the parameter to the constructor.
8890 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8891 ClassLoc, ClassLoc,
8892 /*IdentifierInfo=*/0,
8893 ArgType, /*TInfo=*/0,
8894 SC_None,
8895 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008896 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008897
8898 // C++0x [class.copy]p9:
8899 // If the definition of a class X does not explicitly declare a move
8900 // constructor, one will be implicitly declared as defaulted if and only if:
8901 // [...]
8902 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008903 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008904 // Cache this result so that we don't try to generate this over and over
8905 // on every lookup, leaking memory and wasting time.
8906 ClassDecl->setFailedImplicitMoveConstructor();
8907 return 0;
8908 }
8909
8910 // Note that we have declared this constructor.
8911 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8912
8913 if (Scope *S = getScopeForContext(ClassDecl))
8914 PushOnScopeChains(MoveConstructor, S, false);
8915 ClassDecl->addDecl(MoveConstructor);
8916
8917 return MoveConstructor;
8918}
8919
8920void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8921 CXXConstructorDecl *MoveConstructor) {
8922 assert((MoveConstructor->isDefaulted() &&
8923 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008924 !MoveConstructor->doesThisDeclarationHaveABody() &&
8925 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008926 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8927
8928 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8929 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8930
8931 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8932 DiagnosticErrorTrap Trap(Diags);
8933
8934 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8935 Trap.hasErrorOccurred()) {
8936 Diag(CurrentLocation, diag::note_member_synthesized_at)
8937 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8938 MoveConstructor->setInvalidDecl();
8939 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008940 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008941 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8942 MoveConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008943 MultiStmtArg(*this, 0, 0),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008944 /*isStmtExpr=*/false)
8945 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008946 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008947 }
8948
8949 MoveConstructor->setUsed();
8950
8951 if (ASTMutationListener *L = getASTMutationListener()) {
8952 L->CompletedImplicitDefinition(MoveConstructor);
8953 }
8954}
8955
Douglas Gregore4e68d42012-02-15 19:33:52 +00008956bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8957 return FD->isDeleted() &&
8958 (FD->isDefaulted() || FD->isImplicit()) &&
8959 isa<CXXMethodDecl>(FD);
8960}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008961
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008962/// \brief Mark the call operator of the given lambda closure type as "used".
8963static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8964 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00008965 = cast<CXXMethodDecl>(
8966 *Lambda->lookup(
8967 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008968 CallOperator->setReferenced();
8969 CallOperator->setUsed();
8970}
8971
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008972void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8973 SourceLocation CurrentLocation,
8974 CXXConversionDecl *Conv)
8975{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008976 CXXRecordDecl *Lambda = Conv->getParent();
8977
8978 // Make sure that the lambda call operator is marked used.
8979 markLambdaCallOperatorUsed(*this, Lambda);
8980
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008981 Conv->setUsed();
8982
8983 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8984 DiagnosticErrorTrap Trap(Diags);
8985
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008986 // Return the address of the __invoke function.
8987 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8988 CXXMethodDecl *Invoke
8989 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8990 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8991 VK_LValue, Conv->getLocation()).take();
8992 assert(FunctionRef && "Can't refer to __invoke function?");
8993 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8994 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8995 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008996 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008997
8998 // Fill in the __invoke function with a dummy implementation. IR generation
8999 // will fill in the actual details.
9000 Invoke->setUsed();
9001 Invoke->setReferenced();
9002 Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
9003 Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009004
9005 if (ASTMutationListener *L = getASTMutationListener()) {
9006 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009007 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009008 }
9009}
9010
9011void Sema::DefineImplicitLambdaToBlockPointerConversion(
9012 SourceLocation CurrentLocation,
9013 CXXConversionDecl *Conv)
9014{
9015 Conv->setUsed();
9016
9017 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
9018 DiagnosticErrorTrap Trap(Diags);
9019
Douglas Gregorac1303e2012-02-22 05:02:47 +00009020 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009021 Expr *This = ActOnCXXThis(CurrentLocation).take();
9022 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009023
Eli Friedman23f02672012-03-01 04:01:32 +00009024 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9025 Conv->getLocation(),
9026 Conv, DerefThis);
9027
9028 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9029 // behavior. Note that only the general conversion function does this
9030 // (since it's unusable otherwise); in the case where we inline the
9031 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009032 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009033 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9034 CK_CopyAndAutoreleaseBlockObject,
9035 BuildBlock.get(), 0, VK_RValue);
9036
9037 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009038 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009039 Conv->setInvalidDecl();
9040 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009041 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009042
Douglas Gregorac1303e2012-02-22 05:02:47 +00009043 // Create the return statement that returns the block from the conversion
9044 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009045 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009046 if (Return.isInvalid()) {
9047 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9048 Conv->setInvalidDecl();
9049 return;
9050 }
9051
9052 // Set the body of the conversion function.
9053 Stmt *ReturnS = Return.take();
9054 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9055 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009056 Conv->getLocation()));
9057
Douglas Gregorac1303e2012-02-22 05:02:47 +00009058 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009059 if (ASTMutationListener *L = getASTMutationListener()) {
9060 L->CompletedImplicitDefinition(Conv);
9061 }
9062}
9063
Douglas Gregorf52757d2012-03-10 06:53:13 +00009064/// \brief Determine whether the given list arguments contains exactly one
9065/// "real" (non-default) argument.
9066static bool hasOneRealArgument(MultiExprArg Args) {
9067 switch (Args.size()) {
9068 case 0:
9069 return false;
9070
9071 default:
9072 if (!Args.get()[1]->isDefaultArgument())
9073 return false;
9074
9075 // fall through
9076 case 1:
9077 return !Args.get()[0]->isDefaultArgument();
9078 }
9079
9080 return false;
9081}
9082
John McCall60d7b3a2010-08-24 06:29:42 +00009083ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009084Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009085 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009086 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009087 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009088 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009089 unsigned ConstructKind,
9090 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009091 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009092
Douglas Gregor2f599792010-04-02 18:24:57 +00009093 // C++0x [class.copy]p34:
9094 // When certain criteria are met, an implementation is allowed to
9095 // omit the copy/move construction of a class object, even if the
9096 // copy/move constructor and/or destructor for the object have
9097 // side effects. [...]
9098 // - when a temporary class object that has not been bound to a
9099 // reference (12.2) would be copied/moved to a class object
9100 // with the same cv-unqualified type, the copy/move operation
9101 // can be omitted by constructing the temporary object
9102 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009103 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009104 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009105 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009106 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009107 }
Mike Stump1eb44332009-09-09 15:08:12 +00009108
9109 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009110 Elidable, move(ExprArgs), HadMultipleCandidates,
9111 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009112}
9113
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009114/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9115/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009116ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009117Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9118 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009119 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009120 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009121 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009122 unsigned ConstructKind,
9123 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009124 unsigned NumExprs = ExprArgs.size();
9125 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009126
Nick Lewycky909a70d2011-03-25 01:44:32 +00009127 for (specific_attr_iterator<NonNullAttr>
9128 i = Constructor->specific_attr_begin<NonNullAttr>(),
9129 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9130 const NonNullAttr *NonNull = *i;
9131 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9132 }
9133
Eli Friedman5f2987c2012-02-02 03:46:19 +00009134 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009135 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009136 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009137 HadMultipleCandidates, /*FIXME*/false,
9138 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009139 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9140 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009141}
9142
Mike Stump1eb44332009-09-09 15:08:12 +00009143bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009144 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009145 MultiExprArg Exprs,
9146 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009147 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009148 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009149 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009150 move(Exprs), HadMultipleCandidates, false,
9151 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009152 if (TempResult.isInvalid())
9153 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009154
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009155 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009156 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009157 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009158 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009159 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009160
Anders Carlssonfe2de492009-08-25 05:18:00 +00009161 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009162}
9163
John McCall68c6c9a2010-02-02 09:10:11 +00009164void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009165 if (VD->isInvalidDecl()) return;
9166
John McCall68c6c9a2010-02-02 09:10:11 +00009167 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009168 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009169 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009170 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009171
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009172 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009173 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009174 CheckDestructorAccess(VD->getLocation(), Destructor,
9175 PDiag(diag::err_access_dtor_var)
9176 << VD->getDeclName()
9177 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009178 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009179
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009180 if (!VD->hasGlobalStorage()) return;
9181
9182 // Emit warning for non-trivial dtor in global scope (a real global,
9183 // class-static, function-static).
9184 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9185
9186 // TODO: this should be re-enabled for static locals by !CXAAtExit
9187 if (!VD->isStaticLocal())
9188 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009189}
9190
Douglas Gregor39da0b82009-09-09 23:08:42 +00009191/// \brief Given a constructor and the set of arguments provided for the
9192/// constructor, convert the arguments and add any required default arguments
9193/// to form a proper call to this constructor.
9194///
9195/// \returns true if an error occurred, false otherwise.
9196bool
9197Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9198 MultiExprArg ArgsPtr,
9199 SourceLocation Loc,
Douglas Gregored878af2012-02-24 23:56:31 +00009200 ASTOwningVector<Expr*> &ConvertedArgs,
9201 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009202 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9203 unsigned NumArgs = ArgsPtr.size();
9204 Expr **Args = (Expr **)ArgsPtr.get();
9205
9206 const FunctionProtoType *Proto
9207 = Constructor->getType()->getAs<FunctionProtoType>();
9208 assert(Proto && "Constructor without a prototype?");
9209 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009210
9211 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009212 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009213 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009214 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009215 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009216
9217 VariadicCallType CallType =
9218 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009219 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009220 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9221 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009222 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009223 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009224
9225 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9226
9227 // FIXME: Missing call to CheckFunctionCall or equivalent
9228
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009229 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009230}
9231
Anders Carlsson20d45d22009-12-12 00:32:00 +00009232static inline bool
9233CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9234 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009235 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009236 if (isa<NamespaceDecl>(DC)) {
9237 return SemaRef.Diag(FnDecl->getLocation(),
9238 diag::err_operator_new_delete_declared_in_namespace)
9239 << FnDecl->getDeclName();
9240 }
9241
9242 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009243 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009244 return SemaRef.Diag(FnDecl->getLocation(),
9245 diag::err_operator_new_delete_declared_static)
9246 << FnDecl->getDeclName();
9247 }
9248
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009249 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009250}
9251
Anders Carlsson156c78e2009-12-13 17:53:43 +00009252static inline bool
9253CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9254 CanQualType ExpectedResultType,
9255 CanQualType ExpectedFirstParamType,
9256 unsigned DependentParamTypeDiag,
9257 unsigned InvalidParamTypeDiag) {
9258 QualType ResultType =
9259 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9260
9261 // Check that the result type is not dependent.
9262 if (ResultType->isDependentType())
9263 return SemaRef.Diag(FnDecl->getLocation(),
9264 diag::err_operator_new_delete_dependent_result_type)
9265 << FnDecl->getDeclName() << ExpectedResultType;
9266
9267 // Check that the result type is what we expect.
9268 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9269 return SemaRef.Diag(FnDecl->getLocation(),
9270 diag::err_operator_new_delete_invalid_result_type)
9271 << FnDecl->getDeclName() << ExpectedResultType;
9272
9273 // A function template must have at least 2 parameters.
9274 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9275 return SemaRef.Diag(FnDecl->getLocation(),
9276 diag::err_operator_new_delete_template_too_few_parameters)
9277 << FnDecl->getDeclName();
9278
9279 // The function decl must have at least 1 parameter.
9280 if (FnDecl->getNumParams() == 0)
9281 return SemaRef.Diag(FnDecl->getLocation(),
9282 diag::err_operator_new_delete_too_few_parameters)
9283 << FnDecl->getDeclName();
9284
9285 // Check the the first parameter type is not dependent.
9286 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9287 if (FirstParamType->isDependentType())
9288 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9289 << FnDecl->getDeclName() << ExpectedFirstParamType;
9290
9291 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009292 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009293 ExpectedFirstParamType)
9294 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9295 << FnDecl->getDeclName() << ExpectedFirstParamType;
9296
9297 return false;
9298}
9299
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009300static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009301CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009302 // C++ [basic.stc.dynamic.allocation]p1:
9303 // A program is ill-formed if an allocation function is declared in a
9304 // namespace scope other than global scope or declared static in global
9305 // scope.
9306 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9307 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009308
9309 CanQualType SizeTy =
9310 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9311
9312 // C++ [basic.stc.dynamic.allocation]p1:
9313 // The return type shall be void*. The first parameter shall have type
9314 // std::size_t.
9315 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9316 SizeTy,
9317 diag::err_operator_new_dependent_param_type,
9318 diag::err_operator_new_param_type))
9319 return true;
9320
9321 // C++ [basic.stc.dynamic.allocation]p1:
9322 // The first parameter shall not have an associated default argument.
9323 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009324 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009325 diag::err_operator_new_default_arg)
9326 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9327
9328 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009329}
9330
9331static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009332CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9333 // C++ [basic.stc.dynamic.deallocation]p1:
9334 // A program is ill-formed if deallocation functions are declared in a
9335 // namespace scope other than global scope or declared static in global
9336 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009337 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9338 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009339
9340 // C++ [basic.stc.dynamic.deallocation]p2:
9341 // Each deallocation function shall return void and its first parameter
9342 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009343 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9344 SemaRef.Context.VoidPtrTy,
9345 diag::err_operator_delete_dependent_param_type,
9346 diag::err_operator_delete_param_type))
9347 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009348
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009349 return false;
9350}
9351
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009352/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9353/// of this overloaded operator is well-formed. If so, returns false;
9354/// otherwise, emits appropriate diagnostics and returns true.
9355bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009356 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009357 "Expected an overloaded operator declaration");
9358
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009359 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9360
Mike Stump1eb44332009-09-09 15:08:12 +00009361 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009362 // The allocation and deallocation functions, operator new,
9363 // operator new[], operator delete and operator delete[], are
9364 // described completely in 3.7.3. The attributes and restrictions
9365 // found in the rest of this subclause do not apply to them unless
9366 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009367 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009368 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009369
Anders Carlssona3ccda52009-12-12 00:26:23 +00009370 if (Op == OO_New || Op == OO_Array_New)
9371 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009372
9373 // C++ [over.oper]p6:
9374 // An operator function shall either be a non-static member
9375 // function or be a non-member function and have at least one
9376 // parameter whose type is a class, a reference to a class, an
9377 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009378 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9379 if (MethodDecl->isStatic())
9380 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009381 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009382 } else {
9383 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009384 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9385 ParamEnd = FnDecl->param_end();
9386 Param != ParamEnd; ++Param) {
9387 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009388 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9389 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009390 ClassOrEnumParam = true;
9391 break;
9392 }
9393 }
9394
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009395 if (!ClassOrEnumParam)
9396 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009397 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009398 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009399 }
9400
9401 // C++ [over.oper]p8:
9402 // An operator function cannot have default arguments (8.3.6),
9403 // except where explicitly stated below.
9404 //
Mike Stump1eb44332009-09-09 15:08:12 +00009405 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009406 // (C++ [over.call]p1).
9407 if (Op != OO_Call) {
9408 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9409 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009410 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009411 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009412 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009413 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009414 }
9415 }
9416
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009417 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9418 { false, false, false }
9419#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9420 , { Unary, Binary, MemberOnly }
9421#include "clang/Basic/OperatorKinds.def"
9422 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009423
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009424 bool CanBeUnaryOperator = OperatorUses[Op][0];
9425 bool CanBeBinaryOperator = OperatorUses[Op][1];
9426 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009427
9428 // C++ [over.oper]p8:
9429 // [...] Operator functions cannot have more or fewer parameters
9430 // than the number required for the corresponding operator, as
9431 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009432 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009433 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009434 if (Op != OO_Call &&
9435 ((NumParams == 1 && !CanBeUnaryOperator) ||
9436 (NumParams == 2 && !CanBeBinaryOperator) ||
9437 (NumParams < 1) || (NumParams > 2))) {
9438 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009439 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009440 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009441 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009442 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009443 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009444 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009445 assert(CanBeBinaryOperator &&
9446 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009447 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009448 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009449
Chris Lattner416e46f2008-11-21 07:57:12 +00009450 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009451 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009452 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009453
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009454 // Overloaded operators other than operator() cannot be variadic.
9455 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009456 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009457 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009458 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009459 }
9460
9461 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009462 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9463 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009464 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009465 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009466 }
9467
9468 // C++ [over.inc]p1:
9469 // The user-defined function called operator++ implements the
9470 // prefix and postfix ++ operator. If this function is a member
9471 // function with no parameters, or a non-member function with one
9472 // parameter of class or enumeration type, it defines the prefix
9473 // increment operator ++ for objects of that type. If the function
9474 // is a member function with one parameter (which shall be of type
9475 // int) or a non-member function with two parameters (the second
9476 // of which shall be of type int), it defines the postfix
9477 // increment operator ++ for objects of that type.
9478 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9479 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9480 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009481 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009482 ParamIsInt = BT->getKind() == BuiltinType::Int;
9483
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009484 if (!ParamIsInt)
9485 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009486 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009487 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009488 }
9489
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009490 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009491}
Chris Lattner5a003a42008-12-17 07:09:26 +00009492
Sean Hunta6c058d2010-01-13 09:01:02 +00009493/// CheckLiteralOperatorDeclaration - Check whether the declaration
9494/// of this literal operator function is well-formed. If so, returns
9495/// false; otherwise, emits appropriate diagnostics and returns true.
9496bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009497 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009498 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9499 << FnDecl->getDeclName();
9500 return true;
9501 }
9502
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009503 if (FnDecl->isExternC()) {
9504 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9505 return true;
9506 }
9507
Sean Hunta6c058d2010-01-13 09:01:02 +00009508 bool Valid = false;
9509
Richard Smith36f5cfe2012-03-09 08:00:36 +00009510 // This might be the definition of a literal operator template.
9511 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9512 // This might be a specialization of a literal operator template.
9513 if (!TpDecl)
9514 TpDecl = FnDecl->getPrimaryTemplate();
9515
Sean Hunt216c2782010-04-07 23:11:06 +00009516 // template <char...> type operator "" name() is the only valid template
9517 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009518 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009519 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009520 // Must have only one template parameter
9521 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9522 if (Params->size() == 1) {
9523 NonTypeTemplateParmDecl *PmDecl =
9524 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009525
Sean Hunt216c2782010-04-07 23:11:06 +00009526 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009527 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9528 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9529 Valid = true;
9530 }
9531 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009532 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009533 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009534 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9535
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009536 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009537
Sean Hunt30019c02010-04-07 22:57:35 +00009538 // unsigned long long int, long double, and any character type are allowed
9539 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009540 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9541 Context.hasSameType(T, Context.LongDoubleTy) ||
9542 Context.hasSameType(T, Context.CharTy) ||
9543 Context.hasSameType(T, Context.WCharTy) ||
9544 Context.hasSameType(T, Context.Char16Ty) ||
9545 Context.hasSameType(T, Context.Char32Ty)) {
9546 if (++Param == FnDecl->param_end())
9547 Valid = true;
9548 goto FinishedParams;
9549 }
9550
Sean Hunt30019c02010-04-07 22:57:35 +00009551 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009552 const PointerType *PT = T->getAs<PointerType>();
9553 if (!PT)
9554 goto FinishedParams;
9555 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009556 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009557 goto FinishedParams;
9558 T = T.getUnqualifiedType();
9559
9560 // Move on to the second parameter;
9561 ++Param;
9562
9563 // If there is no second parameter, the first must be a const char *
9564 if (Param == FnDecl->param_end()) {
9565 if (Context.hasSameType(T, Context.CharTy))
9566 Valid = true;
9567 goto FinishedParams;
9568 }
9569
9570 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9571 // are allowed as the first parameter to a two-parameter function
9572 if (!(Context.hasSameType(T, Context.CharTy) ||
9573 Context.hasSameType(T, Context.WCharTy) ||
9574 Context.hasSameType(T, Context.Char16Ty) ||
9575 Context.hasSameType(T, Context.Char32Ty)))
9576 goto FinishedParams;
9577
9578 // The second and final parameter must be an std::size_t
9579 T = (*Param)->getType().getUnqualifiedType();
9580 if (Context.hasSameType(T, Context.getSizeType()) &&
9581 ++Param == FnDecl->param_end())
9582 Valid = true;
9583 }
9584
9585 // FIXME: This diagnostic is absolutely terrible.
9586FinishedParams:
9587 if (!Valid) {
9588 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9589 << FnDecl->getDeclName();
9590 return true;
9591 }
9592
Richard Smitha9e88b22012-03-09 08:16:22 +00009593 // A parameter-declaration-clause containing a default argument is not
9594 // equivalent to any of the permitted forms.
9595 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9596 ParamEnd = FnDecl->param_end();
9597 Param != ParamEnd; ++Param) {
9598 if ((*Param)->hasDefaultArg()) {
9599 Diag((*Param)->getDefaultArgRange().getBegin(),
9600 diag::err_literal_operator_default_argument)
9601 << (*Param)->getDefaultArgRange();
9602 break;
9603 }
9604 }
9605
Richard Smith2fb4ae32012-03-08 02:39:21 +00009606 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009607 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9608 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009609 // C++11 [usrlit.suffix]p1:
9610 // Literal suffix identifiers that do not start with an underscore
9611 // are reserved for future standardization.
9612 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009613 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009614
Sean Hunta6c058d2010-01-13 09:01:02 +00009615 return false;
9616}
9617
Douglas Gregor074149e2009-01-05 19:45:36 +00009618/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9619/// linkage specification, including the language and (if present)
9620/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9621/// the location of the language string literal, which is provided
9622/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9623/// the '{' brace. Otherwise, this linkage specification does not
9624/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009625Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9626 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009627 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009628 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009629 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009630 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009631 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009632 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009633 Language = LinkageSpecDecl::lang_cxx;
9634 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009635 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009636 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009637 }
Mike Stump1eb44332009-09-09 15:08:12 +00009638
Chris Lattnercc98eac2008-12-17 07:13:27 +00009639 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009640
Douglas Gregor074149e2009-01-05 19:45:36 +00009641 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009642 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009643 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009644 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009645 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009646}
9647
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009648/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009649/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9650/// valid, it's the position of the closing '}' brace in a linkage
9651/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009652Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009653 Decl *LinkageSpec,
9654 SourceLocation RBraceLoc) {
9655 if (LinkageSpec) {
9656 if (RBraceLoc.isValid()) {
9657 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9658 LSDecl->setRBraceLoc(RBraceLoc);
9659 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009660 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009661 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009662 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009663}
9664
Douglas Gregord308e622009-05-18 20:51:54 +00009665/// \brief Perform semantic analysis for the variable declaration that
9666/// occurs within a C++ catch clause, returning the newly-created
9667/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009668VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009669 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009670 SourceLocation StartLoc,
9671 SourceLocation Loc,
9672 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009673 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009674 QualType ExDeclType = TInfo->getType();
9675
Sebastian Redl4b07b292008-12-22 19:15:10 +00009676 // Arrays and functions decay.
9677 if (ExDeclType->isArrayType())
9678 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9679 else if (ExDeclType->isFunctionType())
9680 ExDeclType = Context.getPointerType(ExDeclType);
9681
9682 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9683 // The exception-declaration shall not denote a pointer or reference to an
9684 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009685 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009686 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009687 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009688 Invalid = true;
9689 }
Douglas Gregord308e622009-05-18 20:51:54 +00009690
Sebastian Redl4b07b292008-12-22 19:15:10 +00009691 QualType BaseType = ExDeclType;
9692 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009693 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009694 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009695 BaseType = Ptr->getPointeeType();
9696 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009697 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009698 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009699 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009700 BaseType = Ref->getPointeeType();
9701 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009702 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009703 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009704 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009705 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009706 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009707
Mike Stump1eb44332009-09-09 15:08:12 +00009708 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009709 RequireNonAbstractType(Loc, ExDeclType,
9710 diag::err_abstract_type_in_decl,
9711 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009712 Invalid = true;
9713
John McCall5a180392010-07-24 00:37:23 +00009714 // Only the non-fragile NeXT runtime currently supports C++ catches
9715 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +00009716 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +00009717 QualType T = ExDeclType;
9718 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9719 T = RT->getPointeeType();
9720
9721 if (T->isObjCObjectType()) {
9722 Diag(Loc, diag::err_objc_object_catch);
9723 Invalid = true;
9724 } else if (T->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009725 if (!getLangOpts().ObjCNonFragileABI)
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009726 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009727 }
9728 }
9729
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009730 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9731 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009732 ExDecl->setExceptionVariable(true);
9733
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009734 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009735 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009736 Invalid = true;
9737
Douglas Gregorc41b8782011-07-06 18:14:43 +00009738 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009739 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009740 // C++ [except.handle]p16:
9741 // The object declared in an exception-declaration or, if the
9742 // exception-declaration does not specify a name, a temporary (12.2) is
9743 // copy-initialized (8.5) from the exception object. [...]
9744 // The object is destroyed when the handler exits, after the destruction
9745 // of any automatic objects initialized within the handler.
9746 //
9747 // We just pretend to initialize the object with itself, then make sure
9748 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009749 QualType initType = ExDeclType;
9750
9751 InitializedEntity entity =
9752 InitializedEntity::InitializeVariable(ExDecl);
9753 InitializationKind initKind =
9754 InitializationKind::CreateCopy(Loc, SourceLocation());
9755
9756 Expr *opaqueValue =
9757 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9758 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9759 ExprResult result = sequence.Perform(*this, entity, initKind,
9760 MultiExprArg(&opaqueValue, 1));
9761 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009762 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009763 else {
9764 // If the constructor used was non-trivial, set this as the
9765 // "initializer".
9766 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9767 if (!construct->getConstructor()->isTrivial()) {
9768 Expr *init = MaybeCreateExprWithCleanups(construct);
9769 ExDecl->setInit(init);
9770 }
9771
9772 // And make sure it's destructable.
9773 FinalizeVarWithDestructor(ExDecl, recordType);
9774 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009775 }
9776 }
9777
Douglas Gregord308e622009-05-18 20:51:54 +00009778 if (Invalid)
9779 ExDecl->setInvalidDecl();
9780
9781 return ExDecl;
9782}
9783
9784/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9785/// handler.
John McCalld226f652010-08-21 09:40:31 +00009786Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009787 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009788 bool Invalid = D.isInvalidType();
9789
9790 // Check for unexpanded parameter packs.
9791 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9792 UPPC_ExceptionType)) {
9793 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9794 D.getIdentifierLoc());
9795 Invalid = true;
9796 }
9797
Sebastian Redl4b07b292008-12-22 19:15:10 +00009798 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009799 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009800 LookupOrdinaryName,
9801 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009802 // The scope should be freshly made just for us. There is just no way
9803 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009804 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009805 if (PrevDecl->isTemplateParameter()) {
9806 // Maybe we will complain about the shadowed template parameter.
9807 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009808 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009809 }
9810 }
9811
Chris Lattnereaaebc72009-04-25 08:06:05 +00009812 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009813 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9814 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009815 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009816 }
9817
Douglas Gregor83cb9422010-09-09 17:09:21 +00009818 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009819 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009820 D.getIdentifierLoc(),
9821 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009822 if (Invalid)
9823 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009824
Sebastian Redl4b07b292008-12-22 19:15:10 +00009825 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009826 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009827 PushOnScopeChains(ExDecl, S);
9828 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009829 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009830
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009831 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009832 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009833}
Anders Carlssonfb311762009-03-14 00:25:26 +00009834
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009835Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009836 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009837 Expr *AssertMessageExpr_,
9838 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009839 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009840
Anders Carlssonc3082412009-03-14 00:33:21 +00009841 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009842 // In a static_assert-declaration, the constant-expression shall be a
9843 // constant expression that can be contextually converted to bool.
9844 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9845 if (Converted.isInvalid())
9846 return 0;
9847
Richard Smithdaaefc52011-12-14 23:32:26 +00009848 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009849 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9850 PDiag(diag::err_static_assert_expression_is_not_constant),
9851 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009852 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009853
Richard Smith0cc323c2012-03-05 23:20:05 +00009854 if (!Cond) {
9855 llvm::SmallString<256> MsgBuffer;
9856 llvm::raw_svector_ostream Msg(MsgBuffer);
9857 AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009858 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +00009859 << Msg.str() << AssertExpr->getSourceRange();
9860 }
Anders Carlssonc3082412009-03-14 00:33:21 +00009861 }
Mike Stump1eb44332009-09-09 15:08:12 +00009862
Douglas Gregor399ad972010-12-15 23:55:21 +00009863 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9864 return 0;
9865
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009866 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9867 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009868
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009869 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009870 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009871}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009872
Douglas Gregor1d869352010-04-07 16:53:43 +00009873/// \brief Perform semantic analysis of the given friend type declaration.
9874///
9875/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009876FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9877 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009878 TypeSourceInfo *TSInfo) {
9879 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9880
9881 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009882 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009883
Richard Smith6b130222011-10-18 21:39:00 +00009884 // C++03 [class.friend]p2:
9885 // An elaborated-type-specifier shall be used in a friend declaration
9886 // for a class.*
9887 //
9888 // * The class-key of the elaborated-type-specifier is required.
9889 if (!ActiveTemplateInstantiations.empty()) {
9890 // Do not complain about the form of friend template types during
9891 // template instantiation; we will already have complained when the
9892 // template was declared.
9893 } else if (!T->isElaboratedTypeSpecifier()) {
9894 // If we evaluated the type to a record type, suggest putting
9895 // a tag in front.
9896 if (const RecordType *RT = T->getAs<RecordType>()) {
9897 RecordDecl *RD = RT->getDecl();
9898
9899 std::string InsertionText = std::string(" ") + RD->getKindName();
9900
9901 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00009902 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009903 diag::warn_cxx98_compat_unelaborated_friend_type :
9904 diag::ext_unelaborated_friend_type)
9905 << (unsigned) RD->getTagKind()
9906 << T
9907 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9908 InsertionText);
9909 } else {
9910 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009911 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009912 diag::warn_cxx98_compat_nonclass_type_friend :
9913 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009914 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009915 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009916 }
Richard Smith6b130222011-10-18 21:39:00 +00009917 } else if (T->getAs<EnumType>()) {
9918 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009919 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009920 diag::warn_cxx98_compat_enum_friend :
9921 diag::ext_enum_friend)
9922 << T
9923 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009924 }
9925
Douglas Gregor06245bf2010-04-07 17:57:12 +00009926 // C++0x [class.friend]p3:
9927 // If the type specifier in a friend declaration designates a (possibly
9928 // cv-qualified) class type, that class is declared as a friend; otherwise,
9929 // the friend declaration is ignored.
9930
9931 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9932 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009933
Abramo Bagnara0216df82011-10-29 20:52:52 +00009934 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009935}
9936
John McCall9a34edb2010-10-19 01:40:49 +00009937/// Handle a friend tag declaration where the scope specifier was
9938/// templated.
9939Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9940 unsigned TagSpec, SourceLocation TagLoc,
9941 CXXScopeSpec &SS,
9942 IdentifierInfo *Name, SourceLocation NameLoc,
9943 AttributeList *Attr,
9944 MultiTemplateParamsArg TempParamLists) {
9945 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9946
9947 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009948 bool Invalid = false;
9949
9950 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009951 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009952 TempParamLists.get(),
9953 TempParamLists.size(),
9954 /*friend*/ true,
9955 isExplicitSpecialization,
9956 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009957 if (TemplateParams->size() > 0) {
9958 // This is a declaration of a class template.
9959 if (Invalid)
9960 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009961
Eric Christopher4110e132011-07-21 05:34:24 +00009962 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9963 SS, Name, NameLoc, Attr,
9964 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009965 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009966 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009967 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009968 } else {
9969 // The "template<>" header is extraneous.
9970 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9971 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9972 isExplicitSpecialization = true;
9973 }
9974 }
9975
9976 if (Invalid) return 0;
9977
John McCall9a34edb2010-10-19 01:40:49 +00009978 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009979 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009980 if (TempParamLists.get()[I]->size()) {
9981 isAllExplicitSpecializations = false;
9982 break;
9983 }
9984 }
9985
9986 // FIXME: don't ignore attributes.
9987
9988 // If it's explicit specializations all the way down, just forget
9989 // about the template header and build an appropriate non-templated
9990 // friend. TODO: for source fidelity, remember the headers.
9991 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009992 if (SS.isEmpty()) {
9993 bool Owned = false;
9994 bool IsDependent = false;
9995 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9996 Attr, AS_public,
9997 /*ModulePrivateLoc=*/SourceLocation(),
9998 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009999 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010000 /*ScopedEnumUsesClassTag=*/false,
10001 /*UnderlyingType=*/TypeResult());
10002 }
10003
Douglas Gregor2494dd02011-03-01 01:34:45 +000010004 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010005 ElaboratedTypeKeyword Keyword
10006 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010007 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010008 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010009 if (T.isNull())
10010 return 0;
10011
10012 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10013 if (isa<DependentNameType>(T)) {
10014 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010015 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010016 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010017 TL.setNameLoc(NameLoc);
10018 } else {
10019 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010020 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010021 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010022 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10023 }
10024
10025 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10026 TSI, FriendLoc);
10027 Friend->setAccess(AS_public);
10028 CurContext->addDecl(Friend);
10029 return Friend;
10030 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010031
10032 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10033
10034
John McCall9a34edb2010-10-19 01:40:49 +000010035
10036 // Handle the case of a templated-scope friend class. e.g.
10037 // template <class T> class A<T>::B;
10038 // FIXME: we don't support these right now.
10039 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10040 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10041 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10042 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010043 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010044 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010045 TL.setNameLoc(NameLoc);
10046
10047 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10048 TSI, FriendLoc);
10049 Friend->setAccess(AS_public);
10050 Friend->setUnsupportedFriend(true);
10051 CurContext->addDecl(Friend);
10052 return Friend;
10053}
10054
10055
John McCalldd4a3b02009-09-16 22:47:08 +000010056/// Handle a friend type declaration. This works in tandem with
10057/// ActOnTag.
10058///
10059/// Notes on friend class templates:
10060///
10061/// We generally treat friend class declarations as if they were
10062/// declaring a class. So, for example, the elaborated type specifier
10063/// in a friend declaration is required to obey the restrictions of a
10064/// class-head (i.e. no typedefs in the scope chain), template
10065/// parameters are required to match up with simple template-ids, &c.
10066/// However, unlike when declaring a template specialization, it's
10067/// okay to refer to a template specialization without an empty
10068/// template parameter declaration, e.g.
10069/// friend class A<T>::B<unsigned>;
10070/// We permit this as a special case; if there are any template
10071/// parameters present at all, require proper matching, i.e.
10072/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010073Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010074 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010075 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010076
10077 assert(DS.isFriendSpecified());
10078 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10079
John McCalldd4a3b02009-09-16 22:47:08 +000010080 // Try to convert the decl specifier to a type. This works for
10081 // friend templates because ActOnTag never produces a ClassTemplateDecl
10082 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010083 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010084 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10085 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010086 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010087 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010088
Douglas Gregor6ccab972010-12-16 01:14:37 +000010089 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10090 return 0;
10091
John McCalldd4a3b02009-09-16 22:47:08 +000010092 // This is definitely an error in C++98. It's probably meant to
10093 // be forbidden in C++0x, too, but the specification is just
10094 // poorly written.
10095 //
10096 // The problem is with declarations like the following:
10097 // template <T> friend A<T>::foo;
10098 // where deciding whether a class C is a friend or not now hinges
10099 // on whether there exists an instantiation of A that causes
10100 // 'foo' to equal C. There are restrictions on class-heads
10101 // (which we declare (by fiat) elaborated friend declarations to
10102 // be) that makes this tractable.
10103 //
10104 // FIXME: handle "template <> friend class A<T>;", which
10105 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010106 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010107 Diag(Loc, diag::err_tagless_friend_type_template)
10108 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010109 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010110 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010111
John McCall02cace72009-08-28 07:59:38 +000010112 // C++98 [class.friend]p1: A friend of a class is a function
10113 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010114 // This is fixed in DR77, which just barely didn't make the C++03
10115 // deadline. It's also a very silly restriction that seriously
10116 // affects inner classes and which nobody else seems to implement;
10117 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010118 //
10119 // But note that we could warn about it: it's always useless to
10120 // friend one of your own members (it's not, however, worthless to
10121 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010122
John McCalldd4a3b02009-09-16 22:47:08 +000010123 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010124 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010125 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010126 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010127 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010128 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010129 DS.getFriendSpecLoc());
10130 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010131 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010132
10133 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010134 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010135
John McCalldd4a3b02009-09-16 22:47:08 +000010136 D->setAccess(AS_public);
10137 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010138
John McCalld226f652010-08-21 09:40:31 +000010139 return D;
John McCall02cace72009-08-28 07:59:38 +000010140}
10141
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010142Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010143 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010144 const DeclSpec &DS = D.getDeclSpec();
10145
10146 assert(DS.isFriendSpecified());
10147 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10148
10149 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010150 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010151
10152 // C++ [class.friend]p1
10153 // A friend of a class is a function or class....
10154 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010155 // It *doesn't* see through dependent types, which is correct
10156 // according to [temp.arg.type]p3:
10157 // If a declaration acquires a function type through a
10158 // type dependent on a template-parameter and this causes
10159 // a declaration that does not use the syntactic form of a
10160 // function declarator to have a function type, the program
10161 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010162 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010163 Diag(Loc, diag::err_unexpected_friend);
10164
10165 // It might be worthwhile to try to recover by creating an
10166 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010167 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010168 }
10169
10170 // C++ [namespace.memdef]p3
10171 // - If a friend declaration in a non-local class first declares a
10172 // class or function, the friend class or function is a member
10173 // of the innermost enclosing namespace.
10174 // - The name of the friend is not found by simple name lookup
10175 // until a matching declaration is provided in that namespace
10176 // scope (either before or after the class declaration granting
10177 // friendship).
10178 // - If a friend function is called, its name may be found by the
10179 // name lookup that considers functions from namespaces and
10180 // classes associated with the types of the function arguments.
10181 // - When looking for a prior declaration of a class or a function
10182 // declared as a friend, scopes outside the innermost enclosing
10183 // namespace scope are not considered.
10184
John McCall337ec3d2010-10-12 23:13:28 +000010185 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010186 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10187 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010188 assert(Name);
10189
Douglas Gregor6ccab972010-12-16 01:14:37 +000010190 // Check for unexpanded parameter packs.
10191 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10192 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10193 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10194 return 0;
10195
John McCall67d1a672009-08-06 02:15:43 +000010196 // The context we found the declaration in, or in which we should
10197 // create the declaration.
10198 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010199 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010200 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010201 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010202
John McCall337ec3d2010-10-12 23:13:28 +000010203 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010204
John McCall337ec3d2010-10-12 23:13:28 +000010205 // There are four cases here.
10206 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010207 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010208 // there as appropriate.
10209 // Recover from invalid scope qualifiers as if they just weren't there.
10210 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010211 // C++0x [namespace.memdef]p3:
10212 // If the name in a friend declaration is neither qualified nor
10213 // a template-id and the declaration is a function or an
10214 // elaborated-type-specifier, the lookup to determine whether
10215 // the entity has been previously declared shall not consider
10216 // any scopes outside the innermost enclosing namespace.
10217 // C++0x [class.friend]p11:
10218 // If a friend declaration appears in a local class and the name
10219 // specified is an unqualified name, a prior declaration is
10220 // looked up without considering scopes that are outside the
10221 // innermost enclosing non-class scope. For a friend function
10222 // declaration, if there is no prior declaration, the program is
10223 // ill-formed.
10224 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010225 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010226
John McCall29ae6e52010-10-13 05:45:15 +000010227 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010228 DC = CurContext;
10229 while (true) {
10230 // Skip class contexts. If someone can cite chapter and verse
10231 // for this behavior, that would be nice --- it's what GCC and
10232 // EDG do, and it seems like a reasonable intent, but the spec
10233 // really only says that checks for unqualified existing
10234 // declarations should stop at the nearest enclosing namespace,
10235 // not that they should only consider the nearest enclosing
10236 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010237 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010238 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010239
John McCall68263142009-11-18 22:49:29 +000010240 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010241
10242 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010243 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010244 break;
John McCall29ae6e52010-10-13 05:45:15 +000010245
John McCall8a407372010-10-14 22:22:28 +000010246 if (isTemplateId) {
10247 if (isa<TranslationUnitDecl>(DC)) break;
10248 } else {
10249 if (DC->isFileContext()) break;
10250 }
John McCall67d1a672009-08-06 02:15:43 +000010251 DC = DC->getParent();
10252 }
10253
10254 // C++ [class.friend]p1: A friend of a class is a function or
10255 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010256 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010257 // Most C++ 98 compilers do seem to give an error here, so
10258 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010259 if (!Previous.empty() && DC->Equals(CurContext))
10260 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010261 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010262 diag::warn_cxx98_compat_friend_is_member :
10263 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010264
John McCall380aaa42010-10-13 06:22:15 +000010265 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010266
Douglas Gregor883af832011-10-10 01:11:59 +000010267 // C++ [class.friend]p6:
10268 // A function can be defined in a friend declaration of a class if and
10269 // only if the class is a non-local class (9.8), the function name is
10270 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010271 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010272 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10273 }
10274
John McCall337ec3d2010-10-12 23:13:28 +000010275 // - There's a non-dependent scope specifier, in which case we
10276 // compute it and do a previous lookup there for a function
10277 // or function template.
10278 } else if (!SS.getScopeRep()->isDependent()) {
10279 DC = computeDeclContext(SS);
10280 if (!DC) return 0;
10281
10282 if (RequireCompleteDeclContext(SS, DC)) return 0;
10283
10284 LookupQualifiedName(Previous, DC);
10285
10286 // Ignore things found implicitly in the wrong scope.
10287 // TODO: better diagnostics for this case. Suggesting the right
10288 // qualified scope would be nice...
10289 LookupResult::Filter F = Previous.makeFilter();
10290 while (F.hasNext()) {
10291 NamedDecl *D = F.next();
10292 if (!DC->InEnclosingNamespaceSetOf(
10293 D->getDeclContext()->getRedeclContext()))
10294 F.erase();
10295 }
10296 F.done();
10297
10298 if (Previous.empty()) {
10299 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010300 Diag(Loc, diag::err_qualified_friend_not_found)
10301 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010302 return 0;
10303 }
10304
10305 // C++ [class.friend]p1: A friend of a class is a function or
10306 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010307 if (DC->Equals(CurContext))
10308 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010309 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010310 diag::warn_cxx98_compat_friend_is_member :
10311 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010312
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010313 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010314 // C++ [class.friend]p6:
10315 // A function can be defined in a friend declaration of a class if and
10316 // only if the class is a non-local class (9.8), the function name is
10317 // unqualified, and the function has namespace scope.
10318 SemaDiagnosticBuilder DB
10319 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10320
10321 DB << SS.getScopeRep();
10322 if (DC->isFileContext())
10323 DB << FixItHint::CreateRemoval(SS.getRange());
10324 SS.clear();
10325 }
John McCall337ec3d2010-10-12 23:13:28 +000010326
10327 // - There's a scope specifier that does not match any template
10328 // parameter lists, in which case we use some arbitrary context,
10329 // create a method or method template, and wait for instantiation.
10330 // - There's a scope specifier that does match some template
10331 // parameter lists, which we don't handle right now.
10332 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010333 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010334 // C++ [class.friend]p6:
10335 // A function can be defined in a friend declaration of a class if and
10336 // only if the class is a non-local class (9.8), the function name is
10337 // unqualified, and the function has namespace scope.
10338 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10339 << SS.getScopeRep();
10340 }
10341
John McCall337ec3d2010-10-12 23:13:28 +000010342 DC = CurContext;
10343 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010344 }
Douglas Gregor883af832011-10-10 01:11:59 +000010345
John McCall29ae6e52010-10-13 05:45:15 +000010346 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010347 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010348 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10349 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10350 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010351 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010352 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10353 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010354 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010355 }
John McCall67d1a672009-08-06 02:15:43 +000010356 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010357
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010358 // FIXME: This is an egregious hack to cope with cases where the scope stack
10359 // does not contain the declaration context, i.e., in an out-of-line
10360 // definition of a class.
10361 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10362 if (!DCScope) {
10363 FakeDCScope.setEntity(DC);
10364 DCScope = &FakeDCScope;
10365 }
10366
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010367 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010368 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10369 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010370 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010371
Douglas Gregor182ddf02009-09-28 00:08:27 +000010372 assert(ND->getDeclContext() == DC);
10373 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010374
John McCallab88d972009-08-31 22:39:49 +000010375 // Add the function declaration to the appropriate lookup tables,
10376 // adjusting the redeclarations list as necessary. We don't
10377 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010378 //
John McCallab88d972009-08-31 22:39:49 +000010379 // Also update the scope-based lookup if the target context's
10380 // lookup context is in lexical scope.
10381 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010382 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010383 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010384 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010385 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010386 }
John McCall02cace72009-08-28 07:59:38 +000010387
10388 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010389 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010390 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010391 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010392 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010393
John McCall337ec3d2010-10-12 23:13:28 +000010394 if (ND->isInvalidDecl())
10395 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010396 else {
10397 FunctionDecl *FD;
10398 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10399 FD = FTD->getTemplatedDecl();
10400 else
10401 FD = cast<FunctionDecl>(ND);
10402
10403 // Mark templated-scope function declarations as unsupported.
10404 if (FD->getNumTemplateParameterLists())
10405 FrD->setUnsupportedFriend(true);
10406 }
John McCall337ec3d2010-10-12 23:13:28 +000010407
John McCalld226f652010-08-21 09:40:31 +000010408 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010409}
10410
John McCalld226f652010-08-21 09:40:31 +000010411void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10412 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010413
Sebastian Redl50de12f2009-03-24 22:27:57 +000010414 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10415 if (!Fn) {
10416 Diag(DelLoc, diag::err_deleted_non_function);
10417 return;
10418 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010419 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010420 Diag(DelLoc, diag::err_deleted_decl_not_first);
10421 Diag(Prev->getLocation(), diag::note_previous_declaration);
10422 // If the declaration wasn't the first, we delete the function anyway for
10423 // recovery.
10424 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010425 Fn->setDeletedAsWritten();
Richard Smithe653ba22012-02-26 00:31:33 +000010426
10427 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10428 if (!MD)
10429 return;
10430
10431 // A deleted special member function is trivial if the corresponding
10432 // implicitly-declared function would have been.
10433 switch (getSpecialMember(MD)) {
10434 case CXXInvalid:
10435 break;
10436 case CXXDefaultConstructor:
10437 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10438 break;
10439 case CXXCopyConstructor:
10440 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10441 break;
10442 case CXXMoveConstructor:
10443 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10444 break;
10445 case CXXCopyAssignment:
10446 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10447 break;
10448 case CXXMoveAssignment:
10449 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10450 break;
10451 case CXXDestructor:
10452 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10453 break;
10454 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010455}
Sebastian Redl13e88542009-04-27 21:33:24 +000010456
Sean Hunte4246a62011-05-12 06:15:49 +000010457void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10458 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10459
10460 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010461 if (MD->getParent()->isDependentType()) {
10462 MD->setDefaulted();
10463 MD->setExplicitlyDefaulted();
10464 return;
10465 }
10466
Sean Hunte4246a62011-05-12 06:15:49 +000010467 CXXSpecialMember Member = getSpecialMember(MD);
10468 if (Member == CXXInvalid) {
10469 Diag(DefaultLoc, diag::err_default_special_members);
10470 return;
10471 }
10472
10473 MD->setDefaulted();
10474 MD->setExplicitlyDefaulted();
10475
Sean Huntcd10dec2011-05-23 23:14:04 +000010476 // If this definition appears within the record, do the checking when
10477 // the record is complete.
10478 const FunctionDecl *Primary = MD;
10479 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10480 // Find the uninstantiated declaration that actually had the '= default'
10481 // on it.
10482 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10483
10484 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010485 return;
10486
10487 switch (Member) {
10488 case CXXDefaultConstructor: {
10489 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10490 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010491 if (!CD->isInvalidDecl())
10492 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10493 break;
10494 }
10495
10496 case CXXCopyConstructor: {
10497 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10498 CheckExplicitlyDefaultedCopyConstructor(CD);
10499 if (!CD->isInvalidDecl())
10500 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010501 break;
10502 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010503
Sean Hunt2b188082011-05-14 05:23:28 +000010504 case CXXCopyAssignment: {
10505 CheckExplicitlyDefaultedCopyAssignment(MD);
10506 if (!MD->isInvalidDecl())
10507 DefineImplicitCopyAssignment(DefaultLoc, MD);
10508 break;
10509 }
10510
Sean Huntcb45a0f2011-05-12 22:46:25 +000010511 case CXXDestructor: {
10512 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10513 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010514 if (!DD->isInvalidDecl())
10515 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010516 break;
10517 }
10518
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010519 case CXXMoveConstructor: {
10520 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10521 CheckExplicitlyDefaultedMoveConstructor(CD);
10522 if (!CD->isInvalidDecl())
10523 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010524 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010525 }
Sean Hunt82713172011-05-25 23:16:36 +000010526
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010527 case CXXMoveAssignment: {
10528 CheckExplicitlyDefaultedMoveAssignment(MD);
10529 if (!MD->isInvalidDecl())
10530 DefineImplicitMoveAssignment(DefaultLoc, MD);
10531 break;
10532 }
10533
10534 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010535 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010536 }
10537 } else {
10538 Diag(DefaultLoc, diag::err_default_special_members);
10539 }
10540}
10541
Sebastian Redl13e88542009-04-27 21:33:24 +000010542static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010543 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010544 Stmt *SubStmt = *CI;
10545 if (!SubStmt)
10546 continue;
10547 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010548 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010549 diag::err_return_in_constructor_handler);
10550 if (!isa<Expr>(SubStmt))
10551 SearchForReturnInStmt(Self, SubStmt);
10552 }
10553}
10554
10555void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10556 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10557 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10558 SearchForReturnInStmt(*this, Handler);
10559 }
10560}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010561
Mike Stump1eb44332009-09-09 15:08:12 +000010562bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010563 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010564 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10565 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010566
Chandler Carruth73857792010-02-15 11:53:20 +000010567 if (Context.hasSameType(NewTy, OldTy) ||
10568 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010569 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010570
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010571 // Check if the return types are covariant
10572 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010573
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010574 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010575 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10576 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010577 NewClassTy = NewPT->getPointeeType();
10578 OldClassTy = OldPT->getPointeeType();
10579 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010580 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10581 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10582 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10583 NewClassTy = NewRT->getPointeeType();
10584 OldClassTy = OldRT->getPointeeType();
10585 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010586 }
10587 }
Mike Stump1eb44332009-09-09 15:08:12 +000010588
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010589 // The return types aren't either both pointers or references to a class type.
10590 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010591 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010592 diag::err_different_return_type_for_overriding_virtual_function)
10593 << New->getDeclName() << NewTy << OldTy;
10594 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010595
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010596 return true;
10597 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010598
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010599 // C++ [class.virtual]p6:
10600 // If the return type of D::f differs from the return type of B::f, the
10601 // class type in the return type of D::f shall be complete at the point of
10602 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010603 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10604 if (!RT->isBeingDefined() &&
10605 RequireCompleteType(New->getLocation(), NewClassTy,
10606 PDiag(diag::err_covariant_return_incomplete)
10607 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010608 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010609 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010610
Douglas Gregora4923eb2009-11-16 21:35:15 +000010611 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010612 // Check if the new class derives from the old class.
10613 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10614 Diag(New->getLocation(),
10615 diag::err_covariant_return_not_derived)
10616 << New->getDeclName() << NewTy << OldTy;
10617 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10618 return true;
10619 }
Mike Stump1eb44332009-09-09 15:08:12 +000010620
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010621 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010622 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010623 diag::err_covariant_return_inaccessible_base,
10624 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10625 // FIXME: Should this point to the return type?
10626 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010627 // FIXME: this note won't trigger for delayed access control
10628 // diagnostics, and it's impossible to get an undelayed error
10629 // here from access control during the original parse because
10630 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010631 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10632 return true;
10633 }
10634 }
Mike Stump1eb44332009-09-09 15:08:12 +000010635
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010636 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010637 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010638 Diag(New->getLocation(),
10639 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010640 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010641 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10642 return true;
10643 };
Mike Stump1eb44332009-09-09 15:08:12 +000010644
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010645
10646 // The new class type must have the same or less qualifiers as the old type.
10647 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10648 Diag(New->getLocation(),
10649 diag::err_covariant_return_type_class_type_more_qualified)
10650 << New->getDeclName() << NewTy << OldTy;
10651 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10652 return true;
10653 };
Mike Stump1eb44332009-09-09 15:08:12 +000010654
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010655 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010656}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010657
Douglas Gregor4ba31362009-12-01 17:24:26 +000010658/// \brief Mark the given method pure.
10659///
10660/// \param Method the method to be marked pure.
10661///
10662/// \param InitRange the source range that covers the "0" initializer.
10663bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010664 SourceLocation EndLoc = InitRange.getEnd();
10665 if (EndLoc.isValid())
10666 Method->setRangeEnd(EndLoc);
10667
Douglas Gregor4ba31362009-12-01 17:24:26 +000010668 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10669 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010670 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010671 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010672
10673 if (!Method->isInvalidDecl())
10674 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10675 << Method->getDeclName() << InitRange;
10676 return true;
10677}
10678
Douglas Gregor552e2992012-02-21 02:22:07 +000010679/// \brief Determine whether the given declaration is a static data member.
10680static bool isStaticDataMember(Decl *D) {
10681 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10682 if (!Var)
10683 return false;
10684
10685 return Var->isStaticDataMember();
10686}
John McCall731ad842009-12-19 09:28:58 +000010687/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10688/// an initializer for the out-of-line declaration 'Dcl'. The scope
10689/// is a fresh scope pushed for just this purpose.
10690///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010691/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10692/// static data member of class X, names should be looked up in the scope of
10693/// class X.
John McCalld226f652010-08-21 09:40:31 +000010694void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010695 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010696 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010697
John McCall731ad842009-12-19 09:28:58 +000010698 // We should only get called for declarations with scope specifiers, like:
10699 // int foo::bar;
10700 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010701 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000010702
10703 // If we are parsing the initializer for a static data member, push a
10704 // new expression evaluation context that is associated with this static
10705 // data member.
10706 if (isStaticDataMember(D))
10707 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010708}
10709
10710/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010711/// initializer for the out-of-line declaration 'D'.
10712void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010713 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010714 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010715
Douglas Gregor552e2992012-02-21 02:22:07 +000010716 if (isStaticDataMember(D))
10717 PopExpressionEvaluationContext();
10718
John McCall731ad842009-12-19 09:28:58 +000010719 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010720 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010721}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010722
10723/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10724/// C++ if/switch/while/for statement.
10725/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010726DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010727 // C++ 6.4p2:
10728 // The declarator shall not specify a function or an array.
10729 // The type-specifier-seq shall not contain typedef and shall not declare a
10730 // new class or enumeration.
10731 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10732 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010733
10734 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010735 if (!Dcl)
10736 return true;
10737
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010738 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10739 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010740 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010741 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010742 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010743
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010744 return Dcl;
10745}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010746
Douglas Gregordfe65432011-07-28 19:11:31 +000010747void Sema::LoadExternalVTableUses() {
10748 if (!ExternalSource)
10749 return;
10750
10751 SmallVector<ExternalVTableUse, 4> VTables;
10752 ExternalSource->ReadUsedVTables(VTables);
10753 SmallVector<VTableUse, 4> NewUses;
10754 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10755 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10756 = VTablesUsed.find(VTables[I].Record);
10757 // Even if a definition wasn't required before, it may be required now.
10758 if (Pos != VTablesUsed.end()) {
10759 if (!Pos->second && VTables[I].DefinitionRequired)
10760 Pos->second = true;
10761 continue;
10762 }
10763
10764 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10765 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10766 }
10767
10768 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10769}
10770
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010771void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10772 bool DefinitionRequired) {
10773 // Ignore any vtable uses in unevaluated operands or for classes that do
10774 // not have a vtable.
10775 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10776 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010777 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010778 return;
10779
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010780 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010781 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010782 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10783 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10784 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10785 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010786 // If we already had an entry, check to see if we are promoting this vtable
10787 // to required a definition. If so, we need to reappend to the VTableUses
10788 // list, since we may have already processed the first entry.
10789 if (DefinitionRequired && !Pos.first->second) {
10790 Pos.first->second = true;
10791 } else {
10792 // Otherwise, we can early exit.
10793 return;
10794 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010795 }
10796
10797 // Local classes need to have their virtual members marked
10798 // immediately. For all other classes, we mark their virtual members
10799 // at the end of the translation unit.
10800 if (Class->isLocalClass())
10801 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010802 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010803 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010804}
10805
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010806bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010807 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010808 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010809 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010810
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010811 // Note: The VTableUses vector could grow as a result of marking
10812 // the members of a class as "used", so we check the size each
10813 // time through the loop and prefer indices (with are stable) to
10814 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010815 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010816 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010817 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010818 if (!Class)
10819 continue;
10820
10821 SourceLocation Loc = VTableUses[I].second;
10822
10823 // If this class has a key function, but that key function is
10824 // defined in another translation unit, we don't need to emit the
10825 // vtable even though we're using it.
10826 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010827 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010828 switch (KeyFunction->getTemplateSpecializationKind()) {
10829 case TSK_Undeclared:
10830 case TSK_ExplicitSpecialization:
10831 case TSK_ExplicitInstantiationDeclaration:
10832 // The key function is in another translation unit.
10833 continue;
10834
10835 case TSK_ExplicitInstantiationDefinition:
10836 case TSK_ImplicitInstantiation:
10837 // We will be instantiating the key function.
10838 break;
10839 }
10840 } else if (!KeyFunction) {
10841 // If we have a class with no key function that is the subject
10842 // of an explicit instantiation declaration, suppress the
10843 // vtable; it will live with the explicit instantiation
10844 // definition.
10845 bool IsExplicitInstantiationDeclaration
10846 = Class->getTemplateSpecializationKind()
10847 == TSK_ExplicitInstantiationDeclaration;
10848 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10849 REnd = Class->redecls_end();
10850 R != REnd; ++R) {
10851 TemplateSpecializationKind TSK
10852 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10853 if (TSK == TSK_ExplicitInstantiationDeclaration)
10854 IsExplicitInstantiationDeclaration = true;
10855 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10856 IsExplicitInstantiationDeclaration = false;
10857 break;
10858 }
10859 }
10860
10861 if (IsExplicitInstantiationDeclaration)
10862 continue;
10863 }
10864
10865 // Mark all of the virtual members of this class as referenced, so
10866 // that we can build a vtable. Then, tell the AST consumer that a
10867 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010868 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010869 MarkVirtualMembersReferenced(Loc, Class);
10870 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10871 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10872
10873 // Optionally warn if we're emitting a weak vtable.
10874 if (Class->getLinkage() == ExternalLinkage &&
10875 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010876 const FunctionDecl *KeyFunctionDef = 0;
10877 if (!KeyFunction ||
10878 (KeyFunction->hasBody(KeyFunctionDef) &&
10879 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010880 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10881 TSK_ExplicitInstantiationDefinition
10882 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10883 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010884 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010885 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010886 VTableUses.clear();
10887
Douglas Gregor78844032011-04-22 22:25:37 +000010888 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010889}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010890
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010891void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10892 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010893 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10894 e = RD->method_end(); i != e; ++i) {
10895 CXXMethodDecl *MD = *i;
10896
10897 // C++ [basic.def.odr]p2:
10898 // [...] A virtual member function is used if it is not pure. [...]
10899 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010900 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010901 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010902
10903 // Only classes that have virtual bases need a VTT.
10904 if (RD->getNumVBases() == 0)
10905 return;
10906
10907 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10908 e = RD->bases_end(); i != e; ++i) {
10909 const CXXRecordDecl *Base =
10910 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010911 if (Base->getNumVBases() == 0)
10912 continue;
10913 MarkVirtualMembersReferenced(Loc, Base);
10914 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010915}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010916
10917/// SetIvarInitializers - This routine builds initialization ASTs for the
10918/// Objective-C implementation whose ivars need be initialized.
10919void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000010920 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010921 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010922 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010923 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010924 CollectIvarsToConstructOrDestruct(OID, ivars);
10925 if (ivars.empty())
10926 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010927 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010928 for (unsigned i = 0; i < ivars.size(); i++) {
10929 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010930 if (Field->isInvalidDecl())
10931 continue;
10932
Sean Huntcbb67482011-01-08 20:30:50 +000010933 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010934 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10935 InitializationKind InitKind =
10936 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10937
10938 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010939 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010940 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010941 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010942 // Note, MemberInit could actually come back empty if no initialization
10943 // is required (e.g., because it would call a trivial default constructor)
10944 if (!MemberInit.get() || MemberInit.isInvalid())
10945 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010946
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010947 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010948 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10949 SourceLocation(),
10950 MemberInit.takeAs<Expr>(),
10951 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010952 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010953
10954 // Be sure that the destructor is accessible and is marked as referenced.
10955 if (const RecordType *RecordTy
10956 = Context.getBaseElementType(Field->getType())
10957 ->getAs<RecordType>()) {
10958 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010959 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010960 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010961 CheckDestructorAccess(Field->getLocation(), Destructor,
10962 PDiag(diag::err_access_dtor_ivar)
10963 << Context.getBaseElementType(Field->getType()));
10964 }
10965 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010966 }
10967 ObjCImplementation->setIvarInitializers(Context,
10968 AllToInit.data(), AllToInit.size());
10969 }
10970}
Sean Huntfe57eef2011-05-04 05:57:24 +000010971
Sean Huntebcbe1d2011-05-04 23:29:54 +000010972static
10973void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10974 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10975 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10976 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10977 Sema &S) {
10978 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10979 CE = Current.end();
10980 if (Ctor->isInvalidDecl())
10981 return;
10982
10983 const FunctionDecl *FNTarget = 0;
10984 CXXConstructorDecl *Target;
10985
10986 // We ignore the result here since if we don't have a body, Target will be
10987 // null below.
10988 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10989 Target
10990= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10991
10992 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10993 // Avoid dereferencing a null pointer here.
10994 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10995
10996 if (!Current.insert(Canonical))
10997 return;
10998
10999 // We know that beyond here, we aren't chaining into a cycle.
11000 if (!Target || !Target->isDelegatingConstructor() ||
11001 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11002 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11003 Valid.insert(*CI);
11004 Current.clear();
11005 // We've hit a cycle.
11006 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11007 Current.count(TCanonical)) {
11008 // If we haven't diagnosed this cycle yet, do so now.
11009 if (!Invalid.count(TCanonical)) {
11010 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011011 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011012 << Ctor;
11013
11014 // Don't add a note for a function delegating directo to itself.
11015 if (TCanonical != Canonical)
11016 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11017
11018 CXXConstructorDecl *C = Target;
11019 while (C->getCanonicalDecl() != Canonical) {
11020 (void)C->getTargetConstructor()->hasBody(FNTarget);
11021 assert(FNTarget && "Ctor cycle through bodiless function");
11022
11023 C
11024 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11025 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11026 }
11027 }
11028
11029 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11030 Invalid.insert(*CI);
11031 Current.clear();
11032 } else {
11033 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11034 }
11035}
11036
11037
Sean Huntfe57eef2011-05-04 05:57:24 +000011038void Sema::CheckDelegatingCtorCycles() {
11039 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11040
Sean Huntebcbe1d2011-05-04 23:29:54 +000011041 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11042 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011043
Douglas Gregor0129b562011-07-27 21:57:17 +000011044 for (DelegatingCtorDeclsType::iterator
11045 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011046 E = DelegatingCtorDecls.end();
11047 I != E; ++I) {
11048 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000011049 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011050
11051 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11052 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011053}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011054
11055/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11056Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11057 // Implicitly declared functions (e.g. copy constructors) are
11058 // __host__ __device__
11059 if (D->isImplicit())
11060 return CFT_HostDevice;
11061
11062 if (D->hasAttr<CUDAGlobalAttr>())
11063 return CFT_Global;
11064
11065 if (D->hasAttr<CUDADeviceAttr>()) {
11066 if (D->hasAttr<CUDAHostAttr>())
11067 return CFT_HostDevice;
11068 else
11069 return CFT_Device;
11070 }
11071
11072 return CFT_Host;
11073}
11074
11075bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11076 CUDAFunctionTarget CalleeTarget) {
11077 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11078 // Callable from the device only."
11079 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11080 return true;
11081
11082 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11083 // Callable from the host only."
11084 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11085 // Callable from the host only."
11086 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11087 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11088 return true;
11089
11090 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11091 return true;
11092
11093 return false;
11094}