blob: 467cf43797ed8093e49cb2dbf8f6880b4a1a0870 [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"
John McCall50df6ae2010-08-25 07:03:20 +000035#include "llvm/ADT/DenseSet.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000036#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000037#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000038#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000039#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000040
41using namespace clang;
42
Chris Lattner8123a952008-04-10 02:22:51 +000043//===----------------------------------------------------------------------===//
44// CheckDefaultArgumentVisitor
45//===----------------------------------------------------------------------===//
46
Chris Lattner9e979552008-04-12 23:52:44 +000047namespace {
48 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
49 /// the default argument of a parameter to determine whether it
50 /// contains any ill-formed subexpressions. For example, this will
51 /// diagnose the use of local variables or parameters within the
52 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000053 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000054 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000055 Expr *DefaultArg;
56 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000057
Chris Lattner9e979552008-04-12 23:52:44 +000058 public:
Mike Stump1eb44332009-09-09 15:08:12 +000059 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000060 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000061
Chris Lattner9e979552008-04-12 23:52:44 +000062 bool VisitExpr(Expr *Node);
63 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000064 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000065 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000066 };
Chris Lattner8123a952008-04-10 02:22:51 +000067
Chris Lattner9e979552008-04-12 23:52:44 +000068 /// VisitExpr - Visit all of the children of this expression.
69 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
70 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000071 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000072 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000073 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000074 }
75
Chris Lattner9e979552008-04-12 23:52:44 +000076 /// VisitDeclRefExpr - Visit a reference to a declaration, to
77 /// determine whether this declaration can be used in the default
78 /// argument expression.
79 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000080 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000081 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
82 // C++ [dcl.fct.default]p9
83 // Default arguments are evaluated each time the function is
84 // called. The order of evaluation of function arguments is
85 // unspecified. Consequently, parameters of a function shall not
86 // be used in default argument expressions, even if they are not
87 // evaluated. Parameters of a function declared before a default
88 // argument expression are in scope and can hide namespace and
89 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000092 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000093 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000094 // C++ [dcl.fct.default]p7
95 // Local variables shall not be used in default argument
96 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000097 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000098 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000099 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000100 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000101 }
Chris Lattner8123a952008-04-10 02:22:51 +0000102
Douglas Gregor3996f232008-11-04 13:41:56 +0000103 return false;
104 }
Chris Lattner9e979552008-04-12 23:52:44 +0000105
Douglas Gregor796da182008-11-04 14:32:21 +0000106 /// VisitCXXThisExpr - Visit a C++ "this" expression.
107 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
108 // C++ [dcl.fct.default]p8:
109 // The keyword this shall not be used in a default argument of a
110 // member function.
111 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000112 diag::err_param_default_argument_references_this)
113 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000114 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000115
116 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
117 // C++11 [expr.lambda.prim]p13:
118 // A lambda-expression appearing in a default argument shall not
119 // implicitly or explicitly capture any entity.
120 if (Lambda->capture_begin() == Lambda->capture_end())
121 return false;
122
123 return S->Diag(Lambda->getLocStart(),
124 diag::err_lambda_capture_default_arg);
125 }
Chris Lattner8123a952008-04-10 02:22:51 +0000126}
127
Sean Hunt001cad92011-05-10 00:49:42 +0000128void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000129 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith7a614d82011-06-11 17:19:42 +0000130 // If we have an MSAny or unknown spec already, don't bother.
131 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000132 return;
133
134 const FunctionProtoType *Proto
135 = Method->getType()->getAs<FunctionProtoType>();
136
137 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
138
139 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000140 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000141 ClearExceptions();
142 ComputedEST = EST;
143 return;
144 }
145
Richard Smith7a614d82011-06-11 17:19:42 +0000146 // FIXME: If the call to this decl is using any of its default arguments, we
147 // need to search them for potentially-throwing calls.
148
Sean Hunt001cad92011-05-10 00:49:42 +0000149 // If this function has a basic noexcept, it doesn't affect the outcome.
150 if (EST == EST_BasicNoexcept)
151 return;
152
153 // If we have a throw-all spec at this point, ignore the function.
154 if (ComputedEST == EST_None)
155 return;
156
157 // If we're still at noexcept(true) and there's a nothrow() callee,
158 // change to that specification.
159 if (EST == EST_DynamicNone) {
160 if (ComputedEST == EST_BasicNoexcept)
161 ComputedEST = EST_DynamicNone;
162 return;
163 }
164
165 // Check out noexcept specs.
166 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000167 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000168 assert(NR != FunctionProtoType::NR_NoNoexcept &&
169 "Must have noexcept result for EST_ComputedNoexcept.");
170 assert(NR != FunctionProtoType::NR_Dependent &&
171 "Should not generate implicit declarations for dependent cases, "
172 "and don't know how to handle them anyway.");
173
174 // noexcept(false) -> no spec on the new function
175 if (NR == FunctionProtoType::NR_Throw) {
176 ClearExceptions();
177 ComputedEST = EST_None;
178 }
179 // noexcept(true) won't change anything either.
180 return;
181 }
182
183 assert(EST == EST_Dynamic && "EST case not considered earlier.");
184 assert(ComputedEST != EST_None &&
185 "Shouldn't collect exceptions when throw-all is guaranteed.");
186 ComputedEST = EST_Dynamic;
187 // Record the exceptions in this function's exception specification.
188 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
189 EEnd = Proto->exception_end();
190 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000191 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000192 Exceptions.push_back(*E);
193}
194
Richard Smith7a614d82011-06-11 17:19:42 +0000195void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
196 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
197 return;
198
199 // FIXME:
200 //
201 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000202 // [An] implicit exception-specification specifies the type-id T if and
203 // only if T is allowed by the exception-specification of a function directly
204 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000205 // function it directly invokes allows all exceptions, and f shall allow no
206 // exceptions if every function it directly invokes allows no exceptions.
207 //
208 // Note in particular that if an implicit exception-specification is generated
209 // for a function containing a throw-expression, that specification can still
210 // be noexcept(true).
211 //
212 // Note also that 'directly invoked' is not defined in the standard, and there
213 // is no indication that we should only consider potentially-evaluated calls.
214 //
215 // Ultimately we should implement the intent of the standard: the exception
216 // specification should be the set of exceptions which can be thrown by the
217 // implicit definition. For now, we assume that any non-nothrow expression can
218 // throw any exception.
219
220 if (E->CanThrow(*Context))
221 ComputedEST = EST_None;
222}
223
Anders Carlssoned961f92009-08-25 02:29:20 +0000224bool
John McCall9ae2f072010-08-23 23:25:46 +0000225Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000226 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000227 if (RequireCompleteType(Param->getLocation(), Param->getType(),
228 diag::err_typecheck_decl_incomplete_type)) {
229 Param->setInvalidDecl();
230 return true;
231 }
232
Anders Carlssoned961f92009-08-25 02:29:20 +0000233 // C++ [dcl.fct.default]p5
234 // A default argument expression is implicitly converted (clause
235 // 4) to the parameter type. The default argument expression has
236 // the same semantic constraints as the initializer expression in
237 // a declaration of a variable of the parameter type, using the
238 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000239 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
240 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000241 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
242 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000243 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000244 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000245 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000246 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000247 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000248 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000249
John McCallb4eb64d2010-10-08 02:01:28 +0000250 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000251 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Anders Carlssoned961f92009-08-25 02:29:20 +0000253 // Okay: add the default argument to the parameter
254 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000256 // We have already instantiated this parameter; provide each of the
257 // instantiations with the uninstantiated default argument.
258 UnparsedDefaultArgInstantiationsMap::iterator InstPos
259 = UnparsedDefaultArgInstantiations.find(Param);
260 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
261 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
262 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
263
264 // We're done tracking this parameter's instantiations.
265 UnparsedDefaultArgInstantiations.erase(InstPos);
266 }
267
Anders Carlsson9351c172009-08-25 03:18:48 +0000268 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000269}
270
Chris Lattner8123a952008-04-10 02:22:51 +0000271/// ActOnParamDefaultArgument - Check whether the default argument
272/// provided for a function parameter is well-formed. If so, attach it
273/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000274void
John McCalld226f652010-08-21 09:40:31 +0000275Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000276 Expr *DefaultArg) {
277 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000278 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000279
John McCalld226f652010-08-21 09:40:31 +0000280 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000281 UnparsedDefaultArgLocs.erase(Param);
282
Chris Lattner3d1cee32008-04-08 05:04:30 +0000283 // Default arguments are only permitted in C++
284 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000285 Diag(EqualLoc, diag::err_param_default_argument)
286 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000287 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000288 return;
289 }
290
Douglas Gregor6f526752010-12-16 08:48:57 +0000291 // Check for unexpanded parameter packs.
292 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
293 Param->setInvalidDecl();
294 return;
295 }
296
Anders Carlsson66e30672009-08-25 01:02:06 +0000297 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000298 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
299 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000300 Param->setInvalidDecl();
301 return;
302 }
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCall9ae2f072010-08-23 23:25:46 +0000304 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000305}
306
Douglas Gregor61366e92008-12-24 00:01:03 +0000307/// ActOnParamUnparsedDefaultArgument - We've seen a default
308/// argument for a function parameter, but we can't parse it yet
309/// because we're inside a class definition. Note that this default
310/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000311void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000312 SourceLocation EqualLoc,
313 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000314 if (!param)
315 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000316
John McCalld226f652010-08-21 09:40:31 +0000317 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000318 if (Param)
319 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Anders Carlsson5e300d12009-06-12 16:51:40 +0000321 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000322}
323
Douglas Gregor72b505b2008-12-16 21:30:33 +0000324/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
325/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000326void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000327 if (!param)
328 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000329
John McCalld226f652010-08-21 09:40:31 +0000330 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Anders Carlsson5e300d12009-06-12 16:51:40 +0000332 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Anders Carlsson5e300d12009-06-12 16:51:40 +0000334 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000335}
336
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000337/// CheckExtraCXXDefaultArguments - Check for any extra default
338/// arguments in the declarator, which is not a function declaration
339/// or definition and therefore is not permitted to have default
340/// arguments. This routine should be invoked for every declarator
341/// that is not a function declaration or definition.
342void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
343 // C++ [dcl.fct.default]p3
344 // A default argument expression shall be specified only in the
345 // parameter-declaration-clause of a function declaration or in a
346 // template-parameter (14.1). It shall not be specified for a
347 // parameter pack. If it is specified in a
348 // parameter-declaration-clause, it shall not occur within a
349 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000350 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000351 DeclaratorChunk &chunk = D.getTypeObject(i);
352 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000353 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
354 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000355 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000356 if (Param->hasUnparsedDefaultArg()) {
357 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000358 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
359 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
360 delete Toks;
361 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000362 } else if (Param->getDefaultArg()) {
363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364 << Param->getDefaultArg()->getSourceRange();
365 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000366 }
367 }
368 }
369 }
370}
371
Chris Lattner3d1cee32008-04-08 05:04:30 +0000372// MergeCXXFunctionDecl - Merge two declarations of the same C++
373// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000374// type. Subroutine of MergeFunctionDecl. Returns true if there was an
375// error, false otherwise.
376bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
377 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
Douglas Gregor6cc15182009-09-11 18:44:32 +0000401 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000402
Francois Pichet8d051e02011-04-10 03:03:52 +0000403 unsigned DiagDefaultParamID =
404 diag::err_param_default_argument_redefinition;
405
406 // MSVC accepts that default parameters be redefined for member functions
407 // of template class. The new default parameter's value is ignored.
408 Invalid = true;
Francois Pichet62ec1f22011-09-17 17:15:52 +0000409 if (getLangOptions().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000410 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
411 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000412 // Merge the old default argument into the new parameter.
413 NewParam->setHasInheritedDefaultArg();
414 if (OldParam->hasUninstantiatedDefaultArg())
415 NewParam->setUninstantiatedDefaultArg(
416 OldParam->getUninstantiatedDefaultArg());
417 else
418 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000419 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000420 Invalid = false;
421 }
422 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000423
Francois Pichet8cf90492011-04-10 04:58:30 +0000424 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
425 // hint here. Alternatively, we could walk the type-source information
426 // for NewParam to find the last source location in the type... but it
427 // isn't worth the effort right now. This is the kind of test case that
428 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000429 // int f(int);
430 // void g(int (*fp)(int) = f);
431 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000432 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000433 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000434
435 // Look for the function declaration where the default argument was
436 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000437 for (FunctionDecl *Older = Old->getPreviousDecl();
438 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000439 if (!Older->getParamDecl(p)->hasDefaultArg())
440 break;
441
442 OldParam = Older->getParamDecl(p);
443 }
444
445 Diag(OldParam->getLocation(), diag::note_previous_definition)
446 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000447 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000448 // Merge the old default argument into the new parameter.
449 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000450 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000451 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000452 if (OldParam->hasUninstantiatedDefaultArg())
453 NewParam->setUninstantiatedDefaultArg(
454 OldParam->getUninstantiatedDefaultArg());
455 else
John McCall3d6c1782010-05-04 01:53:42 +0000456 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000457 } else if (NewParam->hasDefaultArg()) {
458 if (New->getDescribedFunctionTemplate()) {
459 // Paragraph 4, quoted above, only applies to non-template functions.
460 Diag(NewParam->getLocation(),
461 diag::err_param_default_argument_template_redecl)
462 << NewParam->getDefaultArgRange();
463 Diag(Old->getLocation(), diag::note_template_prev_declaration)
464 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000465 } else if (New->getTemplateSpecializationKind()
466 != TSK_ImplicitInstantiation &&
467 New->getTemplateSpecializationKind() != TSK_Undeclared) {
468 // C++ [temp.expr.spec]p21:
469 // Default function arguments shall not be specified in a declaration
470 // or a definition for one of the following explicit specializations:
471 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000472 // - the explicit specialization of a member function template;
473 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000474 // template where the class template specialization to which the
475 // member function specialization belongs is implicitly
476 // instantiated.
477 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
478 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
479 << New->getDeclName()
480 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000481 } else if (New->getDeclContext()->isDependentContext()) {
482 // C++ [dcl.fct.default]p6 (DR217):
483 // Default arguments for a member function of a class template shall
484 // be specified on the initial declaration of the member function
485 // within the class template.
486 //
487 // Reading the tea leaves a bit in DR217 and its reference to DR205
488 // leads me to the conclusion that one cannot add default function
489 // arguments for an out-of-line definition of a member function of a
490 // dependent type.
491 int WhichKind = 2;
492 if (CXXRecordDecl *Record
493 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
494 if (Record->getDescribedClassTemplate())
495 WhichKind = 0;
496 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
497 WhichKind = 1;
498 else
499 WhichKind = 2;
500 }
501
502 Diag(NewParam->getLocation(),
503 diag::err_param_default_argument_member_template_redecl)
504 << WhichKind
505 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000506 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
507 CXXSpecialMember NewSM = getSpecialMember(Ctor),
508 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
509 if (NewSM != OldSM) {
510 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
511 << NewParam->getDefaultArgRange() << NewSM;
512 Diag(Old->getLocation(), diag::note_previous_declaration_special)
513 << OldSM;
514 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000515 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000516 }
517 }
518
Richard Smith9f569cc2011-10-01 02:31:28 +0000519 // C++0x [dcl.constexpr]p1: If any declaration of a function or function
520 // template has a constexpr specifier then all its declarations shall
521 // contain the constexpr specifier. [Note: An explicit specialization can
522 // differ from the template declaration with respect to the constexpr
523 // specifier. -- end note]
524 //
525 // FIXME: Don't reject changes in constexpr in explicit specializations.
526 if (New->isConstexpr() != Old->isConstexpr()) {
527 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
528 << New << New->isConstexpr();
529 Diag(Old->getLocation(), diag::note_previous_declaration);
530 Invalid = true;
531 }
532
Douglas Gregore13ad832010-02-12 07:32:17 +0000533 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000534 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000535
Douglas Gregorcda9c672009-02-16 17:45:42 +0000536 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000537}
538
Sebastian Redl60618fa2011-03-12 11:50:43 +0000539/// \brief Merge the exception specifications of two variable declarations.
540///
541/// This is called when there's a redeclaration of a VarDecl. The function
542/// checks if the redeclaration might have an exception specification and
543/// validates compatibility and merges the specs if necessary.
544void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
545 // Shortcut if exceptions are disabled.
546 if (!getLangOptions().CXXExceptions)
547 return;
548
549 assert(Context.hasSameType(New->getType(), Old->getType()) &&
550 "Should only be called if types are otherwise the same.");
551
552 QualType NewType = New->getType();
553 QualType OldType = Old->getType();
554
555 // We're only interested in pointers and references to functions, as well
556 // as pointers to member functions.
557 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
558 NewType = R->getPointeeType();
559 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
560 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
561 NewType = P->getPointeeType();
562 OldType = OldType->getAs<PointerType>()->getPointeeType();
563 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
564 NewType = M->getPointeeType();
565 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
566 }
567
568 if (!NewType->isFunctionProtoType())
569 return;
570
571 // There's lots of special cases for functions. For function pointers, system
572 // libraries are hopefully not as broken so that we don't need these
573 // workarounds.
574 if (CheckEquivalentExceptionSpec(
575 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
576 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
577 New->setInvalidDecl();
578 }
579}
580
Chris Lattner3d1cee32008-04-08 05:04:30 +0000581/// CheckCXXDefaultArguments - Verify that the default arguments for a
582/// function declaration are well-formed according to C++
583/// [dcl.fct.default].
584void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
585 unsigned NumParams = FD->getNumParams();
586 unsigned p;
587
588 // Find first parameter with a default argument
589 for (p = 0; p < NumParams; ++p) {
590 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000591 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000592 break;
593 }
594
595 // C++ [dcl.fct.default]p4:
596 // In a given function declaration, all parameters
597 // subsequent to a parameter with a default argument shall
598 // have default arguments supplied in this or previous
599 // declarations. A default argument shall not be redefined
600 // by a later declaration (not even to the same value).
601 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000602 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000603 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000604 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000605 if (Param->isInvalidDecl())
606 /* We already complained about this parameter. */;
607 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000608 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000609 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000610 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000611 else
Mike Stump1eb44332009-09-09 15:08:12 +0000612 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000613 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Chris Lattner3d1cee32008-04-08 05:04:30 +0000615 LastMissingDefaultArg = p;
616 }
617 }
618
619 if (LastMissingDefaultArg > 0) {
620 // Some default arguments were missing. Clear out all of the
621 // default arguments up to (and including) the last missing
622 // default argument, so that we leave the function parameters
623 // in a semantically valid state.
624 for (p = 0; p <= LastMissingDefaultArg; ++p) {
625 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000626 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000627 Param->setDefaultArg(0);
628 }
629 }
630 }
631}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000632
Richard Smith9f569cc2011-10-01 02:31:28 +0000633// CheckConstexprParameterTypes - Check whether a function's parameter types
634// are all literal types. If so, return true. If not, produce a suitable
635// diagnostic depending on @p CCK and return false.
636static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD,
637 Sema::CheckConstexprKind CCK) {
638 unsigned ArgIndex = 0;
639 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
640 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
641 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
642 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
643 SourceLocation ParamLoc = PD->getLocation();
644 if (!(*i)->isDependentType() &&
645 SemaRef.RequireLiteralType(ParamLoc, *i, CCK == Sema::CCK_Declaration ?
646 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
647 << ArgIndex+1 << PD->getSourceRange()
648 << isa<CXXConstructorDecl>(FD) :
649 SemaRef.PDiag(),
650 /*AllowIncompleteType*/ true)) {
651 if (CCK == Sema::CCK_NoteNonConstexprInstantiation)
652 SemaRef.Diag(ParamLoc, diag::note_constexpr_tmpl_non_literal_param)
653 << ArgIndex+1 << PD->getSourceRange()
654 << isa<CXXConstructorDecl>(FD) << *i;
655 return false;
656 }
657 }
658 return true;
659}
660
661// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
662// the requirements of a constexpr function declaration or a constexpr
663// constructor declaration. Return true if it does, false if not.
664//
Richard Smith35340502012-01-13 04:54:00 +0000665// This implements C++11 [dcl.constexpr]p3,4, as amended by N3308.
Richard Smith9f569cc2011-10-01 02:31:28 +0000666//
667// \param CCK Specifies whether to produce diagnostics if the function does not
668// satisfy the requirements.
669bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD,
670 CheckConstexprKind CCK) {
671 assert((CCK != CCK_NoteNonConstexprInstantiation ||
672 (NewFD->getTemplateInstantiationPattern() &&
673 NewFD->getTemplateInstantiationPattern()->isConstexpr())) &&
674 "only constexpr templates can be instantiated non-constexpr");
675
Richard Smith35340502012-01-13 04:54:00 +0000676 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
677 if (MD && MD->isInstance()) {
678 // C++11 [dcl.constexpr]p4: In the definition of a constexpr constructor...
Richard Smith9f569cc2011-10-01 02:31:28 +0000679 // In addition, either its function-body shall be = delete or = default or
680 // it shall satisfy the following constraints:
681 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000682 //
683 // We apply this to constexpr member functions too: the class cannot be a
684 // literal type, so the members are not permitted to be constexpr.
685 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000686 if (RD->getNumVBases()) {
687 // Note, this is still illegal if the body is = default, since the
688 // implicit body does not satisfy the requirements of a constexpr
689 // constructor. We also reject cases where the body is = delete, as
690 // required by N3308.
691 if (CCK != CCK_Instantiation) {
692 Diag(NewFD->getLocation(),
693 CCK == CCK_Declaration ? diag::err_constexpr_virtual_base
694 : diag::note_constexpr_tmpl_virtual_base)
Richard Smith35340502012-01-13 04:54:00 +0000695 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
696 << RD->getNumVBases();
Richard Smith9f569cc2011-10-01 02:31:28 +0000697 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
698 E = RD->vbases_end(); I != E; ++I)
699 Diag(I->getSourceRange().getBegin(),
700 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
701 }
702 return false;
703 }
Richard Smith35340502012-01-13 04:54:00 +0000704 }
705
706 if (!isa<CXXConstructorDecl>(NewFD)) {
707 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000708 // The definition of a constexpr function shall satisfy the following
709 // constraints:
710 // - it shall not be virtual;
711 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
712 if (Method && Method->isVirtual()) {
713 if (CCK != CCK_Instantiation) {
714 Diag(NewFD->getLocation(),
715 CCK == CCK_Declaration ? diag::err_constexpr_virtual
716 : diag::note_constexpr_tmpl_virtual);
717
718 // If it's not obvious why this function is virtual, find an overridden
719 // function which uses the 'virtual' keyword.
720 const CXXMethodDecl *WrittenVirtual = Method;
721 while (!WrittenVirtual->isVirtualAsWritten())
722 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
723 if (WrittenVirtual != Method)
Richard Smith35340502012-01-13 04:54:00 +0000724 Diag(WrittenVirtual->getLocation(),
Richard Smith9f569cc2011-10-01 02:31:28 +0000725 diag::note_overridden_virtual_function);
726 }
727 return false;
728 }
729
730 // - its return type shall be a literal type;
731 QualType RT = NewFD->getResultType();
732 if (!RT->isDependentType() &&
733 RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ?
734 PDiag(diag::err_constexpr_non_literal_return) :
735 PDiag(),
736 /*AllowIncompleteType*/ true)) {
737 if (CCK == CCK_NoteNonConstexprInstantiation)
738 Diag(NewFD->getLocation(),
739 diag::note_constexpr_tmpl_non_literal_return) << RT;
740 return false;
741 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000742 }
743
Richard Smith35340502012-01-13 04:54:00 +0000744 // - each of its parameter types shall be a literal type;
745 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
746 return false;
747
Richard Smith9f569cc2011-10-01 02:31:28 +0000748 return true;
749}
750
751/// Check the given declaration statement is legal within a constexpr function
752/// body. C++0x [dcl.constexpr]p3,p4.
753///
754/// \return true if the body is OK, false if we have diagnosed a problem.
755static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
756 DeclStmt *DS) {
757 // C++0x [dcl.constexpr]p3 and p4:
758 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
759 // contain only
760 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
761 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
762 switch ((*DclIt)->getKind()) {
763 case Decl::StaticAssert:
764 case Decl::Using:
765 case Decl::UsingShadow:
766 case Decl::UsingDirective:
767 case Decl::UnresolvedUsingTypename:
768 // - static_assert-declarations
769 // - using-declarations,
770 // - using-directives,
771 continue;
772
773 case Decl::Typedef:
774 case Decl::TypeAlias: {
775 // - typedef declarations and alias-declarations that do not define
776 // classes or enumerations,
777 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
778 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
779 // Don't allow variably-modified types in constexpr functions.
780 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
781 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
782 << TL.getSourceRange() << TL.getType()
783 << isa<CXXConstructorDecl>(Dcl);
784 return false;
785 }
786 continue;
787 }
788
789 case Decl::Enum:
790 case Decl::CXXRecord:
791 // As an extension, we allow the declaration (but not the definition) of
792 // classes and enumerations in all declarations, not just in typedef and
793 // alias declarations.
794 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
795 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
796 << isa<CXXConstructorDecl>(Dcl);
797 return false;
798 }
799 continue;
800
801 case Decl::Var:
802 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
803 << isa<CXXConstructorDecl>(Dcl);
804 return false;
805
806 default:
807 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
808 << isa<CXXConstructorDecl>(Dcl);
809 return false;
810 }
811 }
812
813 return true;
814}
815
816/// Check that the given field is initialized within a constexpr constructor.
817///
818/// \param Dcl The constexpr constructor being checked.
819/// \param Field The field being checked. This may be a member of an anonymous
820/// struct or union nested within the class being checked.
821/// \param Inits All declarations, including anonymous struct/union members and
822/// indirect members, for which any initialization was provided.
823/// \param Diagnosed Set to true if an error is produced.
824static void CheckConstexprCtorInitializer(Sema &SemaRef,
825 const FunctionDecl *Dcl,
826 FieldDecl *Field,
827 llvm::SmallSet<Decl*, 16> &Inits,
828 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000829 if (Field->isUnnamedBitfield())
830 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000831
832 if (Field->isAnonymousStructOrUnion() &&
833 Field->getType()->getAsCXXRecordDecl()->isEmpty())
834 return;
835
Richard Smith9f569cc2011-10-01 02:31:28 +0000836 if (!Inits.count(Field)) {
837 if (!Diagnosed) {
838 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
839 Diagnosed = true;
840 }
841 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
842 } else if (Field->isAnonymousStructOrUnion()) {
843 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
844 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
845 I != E; ++I)
846 // If an anonymous union contains an anonymous struct of which any member
847 // is initialized, all members must be initialized.
848 if (!RD->isUnion() || Inits.count(*I))
849 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
850 }
851}
852
853/// Check the body for the given constexpr function declaration only contains
854/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
855///
856/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smithd79093a2012-02-05 02:30:54 +0000857bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body,
858 bool IsInstantiation) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000859 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000860 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000861 // The definition of a constexpr function shall satisfy the following
862 // constraints: [...]
863 // - its function-body shall be = delete, = default, or a
864 // compound-statement
865 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000866 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000867 // In the definition of a constexpr constructor, [...]
868 // - its function-body shall not be a function-try-block;
869 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
870 << isa<CXXConstructorDecl>(Dcl);
871 return false;
872 }
873
874 // - its function-body shall be [...] a compound-statement that contains only
875 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
876
877 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
878 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
879 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
880 switch ((*BodyIt)->getStmtClass()) {
881 case Stmt::NullStmtClass:
882 // - null statements,
883 continue;
884
885 case Stmt::DeclStmtClass:
886 // - static_assert-declarations
887 // - using-declarations,
888 // - using-directives,
889 // - typedef declarations and alias-declarations that do not define
890 // classes or enumerations,
891 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
892 return false;
893 continue;
894
895 case Stmt::ReturnStmtClass:
896 // - and exactly one return statement;
897 if (isa<CXXConstructorDecl>(Dcl))
898 break;
899
900 ReturnStmts.push_back((*BodyIt)->getLocStart());
901 // FIXME
902 // - every constructor call and implicit conversion used in initializing
903 // the return value shall be one of those allowed in a constant
904 // expression.
905 // Deal with this as part of a general check that the function can produce
906 // a constant expression (for [dcl.constexpr]p5).
907 continue;
908
909 default:
910 break;
911 }
912
913 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
914 << isa<CXXConstructorDecl>(Dcl);
915 return false;
916 }
917
918 if (const CXXConstructorDecl *Constructor
919 = dyn_cast<CXXConstructorDecl>(Dcl)) {
920 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000921 // DR1359:
922 // - every non-variant non-static data member and base class sub-object
923 // shall be initialized;
924 // - if the class is a non-empty union, or for each non-empty anonymous
925 // union member of a non-union class, exactly one non-static data member
926 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000927 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000928 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000929 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
930 return false;
931 }
Richard Smith6e433752011-10-10 16:38:04 +0000932 } else if (!Constructor->isDependentContext() &&
933 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000934 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
935
936 // Skip detailed checking if we have enough initializers, and we would
937 // allow at most one initializer per member.
938 bool AnyAnonStructUnionMembers = false;
939 unsigned Fields = 0;
940 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
941 E = RD->field_end(); I != E; ++I, ++Fields) {
942 if ((*I)->isAnonymousStructOrUnion()) {
943 AnyAnonStructUnionMembers = true;
944 break;
945 }
946 }
947 if (AnyAnonStructUnionMembers ||
948 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
949 // Check initialization of non-static data members. Base classes are
950 // always initialized so do not need to be checked. Dependent bases
951 // might not have initializers in the member initializer list.
952 llvm::SmallSet<Decl*, 16> Inits;
953 for (CXXConstructorDecl::init_const_iterator
954 I = Constructor->init_begin(), E = Constructor->init_end();
955 I != E; ++I) {
956 if (FieldDecl *FD = (*I)->getMember())
957 Inits.insert(FD);
958 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
959 Inits.insert(ID->chain_begin(), ID->chain_end());
960 }
961
962 bool Diagnosed = false;
963 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
964 E = RD->field_end(); I != E; ++I)
965 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
966 if (Diagnosed)
967 return false;
968 }
969 }
970
971 // FIXME
972 // - every constructor involved in initializing non-static data members
973 // and base class sub-objects shall be a constexpr constructor;
974 // - every assignment-expression that is an initializer-clause appearing
975 // directly or indirectly within a brace-or-equal-initializer for
976 // a non-static data member that is not named by a mem-initializer-id
977 // shall be a constant expression; and
978 // - every implicit conversion used in converting a constructor argument
979 // to the corresponding parameter type and converting
980 // a full-expression to the corresponding member type shall be one of
981 // those allowed in a constant expression.
982 // Deal with these as part of a general check that the function can produce
983 // a constant expression (for [dcl.constexpr]p5).
984 } else {
985 if (ReturnStmts.empty()) {
986 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
987 return false;
988 }
989 if (ReturnStmts.size() > 1) {
990 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
991 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
992 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
993 return false;
994 }
995 }
996
Richard Smith5ba73e12012-02-04 00:33:54 +0000997 // C++11 [dcl.constexpr]p5:
998 // if no function argument values exist such that the function invocation
999 // substitution would produce a constant expression, the program is
1000 // ill-formed; no diagnostic required.
1001 // C++11 [dcl.constexpr]p3:
1002 // - every constructor call and implicit conversion used in initializing the
1003 // return value shall be one of those allowed in a constant expression.
1004 // C++11 [dcl.constexpr]p4:
1005 // - every constructor involved in initializing non-static data members and
1006 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +00001007 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith925d8e72012-02-08 06:14:53 +00001008 if (!IsInstantiation && !Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +00001009 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
1010 << isa<CXXConstructorDecl>(Dcl);
1011 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1012 Diag(Diags[I].first, Diags[I].second);
1013 return false;
1014 }
1015
Richard Smith9f569cc2011-10-01 02:31:28 +00001016 return true;
1017}
1018
Douglas Gregorb48fe382008-10-31 09:07:45 +00001019/// isCurrentClassName - Determine whether the identifier II is the
1020/// name of the class type currently being defined. In the case of
1021/// nested classes, this will only return true if II is the name of
1022/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001023bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1024 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001025 assert(getLangOptions().CPlusPlus && "No class names in C!");
1026
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001027 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001028 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001029 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001030 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1031 } else
1032 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1033
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001034 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001035 return &II == CurDecl->getIdentifier();
1036 else
1037 return false;
1038}
1039
Mike Stump1eb44332009-09-09 15:08:12 +00001040/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001041///
1042/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1043/// and returns NULL otherwise.
1044CXXBaseSpecifier *
1045Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1046 SourceRange SpecifierRange,
1047 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001048 TypeSourceInfo *TInfo,
1049 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001050 QualType BaseType = TInfo->getType();
1051
Douglas Gregor2943aed2009-03-03 04:44:36 +00001052 // C++ [class.union]p1:
1053 // A union shall not have base classes.
1054 if (Class->isUnion()) {
1055 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1056 << SpecifierRange;
1057 return 0;
1058 }
1059
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001060 if (EllipsisLoc.isValid() &&
1061 !TInfo->getType()->containsUnexpandedParameterPack()) {
1062 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1063 << TInfo->getTypeLoc().getSourceRange();
1064 EllipsisLoc = SourceLocation();
1065 }
1066
Douglas Gregor2943aed2009-03-03 04:44:36 +00001067 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001068 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001069 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001070 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001071
1072 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001073
1074 // Base specifiers must be record types.
1075 if (!BaseType->isRecordType()) {
1076 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1077 return 0;
1078 }
1079
1080 // C++ [class.union]p1:
1081 // A union shall not be used as a base class.
1082 if (BaseType->isUnionType()) {
1083 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1084 return 0;
1085 }
1086
1087 // C++ [class.derived]p2:
1088 // The class-name in a base-specifier shall not be an incompletely
1089 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001090 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001091 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001092 << SpecifierRange)) {
1093 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001094 return 0;
John McCall572fc622010-08-17 07:23:57 +00001095 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001096
Eli Friedman1d954f62009-08-15 21:55:26 +00001097 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001098 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001099 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001100 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001101 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001102 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1103 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001104
Anders Carlsson1d209272011-03-25 14:55:14 +00001105 // C++ [class]p3:
1106 // If a class is marked final and it appears as a base-type-specifier in
1107 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001108 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001109 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1110 << CXXBaseDecl->getDeclName();
1111 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1112 << CXXBaseDecl->getDeclName();
1113 return 0;
1114 }
1115
John McCall572fc622010-08-17 07:23:57 +00001116 if (BaseDecl->isInvalidDecl())
1117 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001118
1119 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001120 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001121 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001122 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001123}
1124
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001125/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1126/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001127/// example:
1128/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001129/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001130BaseResult
John McCalld226f652010-08-21 09:40:31 +00001131Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001132 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001133 ParsedType basetype, SourceLocation BaseLoc,
1134 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001135 if (!classdecl)
1136 return true;
1137
Douglas Gregor40808ce2009-03-09 23:48:35 +00001138 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001139 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001140 if (!Class)
1141 return true;
1142
Nick Lewycky56062202010-07-26 16:56:01 +00001143 TypeSourceInfo *TInfo = 0;
1144 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001145
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001146 if (EllipsisLoc.isInvalid() &&
1147 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001148 UPPC_BaseType))
1149 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001150
Douglas Gregor2943aed2009-03-03 04:44:36 +00001151 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001152 Virtual, Access, TInfo,
1153 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001154 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Douglas Gregor2943aed2009-03-03 04:44:36 +00001156 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001157}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001158
Douglas Gregor2943aed2009-03-03 04:44:36 +00001159/// \brief Performs the actual work of attaching the given base class
1160/// specifiers to a C++ class.
1161bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1162 unsigned NumBases) {
1163 if (NumBases == 0)
1164 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001165
1166 // Used to keep track of which base types we have already seen, so
1167 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001168 // that the key is always the unqualified canonical type of the base
1169 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001170 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1171
1172 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001173 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001174 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001175 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001176 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001177 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001178 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001179 if (KnownBaseTypes[NewBaseType]) {
1180 // C++ [class.mi]p3:
1181 // A class shall not be specified as a direct base class of a
1182 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001183 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001184 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +00001185 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001186 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001187
1188 // Delete the duplicate base class specifier; we're going to
1189 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001190 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001191
1192 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001193 } else {
1194 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001195 KnownBaseTypes[NewBaseType] = Bases[idx];
1196 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001197 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001198 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1199 if (RD->hasAttr<WeakAttr>())
1200 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001201 }
1202 }
1203
1204 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001205 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001206
1207 // Delete the remaining (good) base class specifiers, since their
1208 // data has been copied into the CXXRecordDecl.
1209 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001210 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001211
1212 return Invalid;
1213}
1214
1215/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1216/// class, after checking whether there are any duplicate base
1217/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001218void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001219 unsigned NumBases) {
1220 if (!ClassDecl || !Bases || !NumBases)
1221 return;
1222
1223 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001224 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001225 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001226}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001227
John McCall3cb0ebd2010-03-10 03:28:59 +00001228static CXXRecordDecl *GetClassForType(QualType T) {
1229 if (const RecordType *RT = T->getAs<RecordType>())
1230 return cast<CXXRecordDecl>(RT->getDecl());
1231 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1232 return ICT->getDecl();
1233 else
1234 return 0;
1235}
1236
Douglas Gregora8f32e02009-10-06 17:59:45 +00001237/// \brief Determine whether the type \p Derived is a C++ class that is
1238/// derived from the type \p Base.
1239bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1240 if (!getLangOptions().CPlusPlus)
1241 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001242
1243 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1244 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001245 return false;
1246
John McCall3cb0ebd2010-03-10 03:28:59 +00001247 CXXRecordDecl *BaseRD = GetClassForType(Base);
1248 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001249 return false;
1250
John McCall86ff3082010-02-04 22:26:26 +00001251 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1252 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001253}
1254
1255/// \brief Determine whether the type \p Derived is a C++ class that is
1256/// derived from the type \p Base.
1257bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1258 if (!getLangOptions().CPlusPlus)
1259 return false;
1260
John McCall3cb0ebd2010-03-10 03:28:59 +00001261 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1262 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001263 return false;
1264
John McCall3cb0ebd2010-03-10 03:28:59 +00001265 CXXRecordDecl *BaseRD = GetClassForType(Base);
1266 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001267 return false;
1268
Douglas Gregora8f32e02009-10-06 17:59:45 +00001269 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1270}
1271
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001272void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001273 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001274 assert(BasePathArray.empty() && "Base path array must be empty!");
1275 assert(Paths.isRecordingPaths() && "Must record paths!");
1276
1277 const CXXBasePath &Path = Paths.front();
1278
1279 // We first go backward and check if we have a virtual base.
1280 // FIXME: It would be better if CXXBasePath had the base specifier for
1281 // the nearest virtual base.
1282 unsigned Start = 0;
1283 for (unsigned I = Path.size(); I != 0; --I) {
1284 if (Path[I - 1].Base->isVirtual()) {
1285 Start = I - 1;
1286 break;
1287 }
1288 }
1289
1290 // Now add all bases.
1291 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001292 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001293}
1294
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001295/// \brief Determine whether the given base path includes a virtual
1296/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001297bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1298 for (CXXCastPath::const_iterator B = BasePath.begin(),
1299 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001300 B != BEnd; ++B)
1301 if ((*B)->isVirtual())
1302 return true;
1303
1304 return false;
1305}
1306
Douglas Gregora8f32e02009-10-06 17:59:45 +00001307/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1308/// conversion (where Derived and Base are class types) is
1309/// well-formed, meaning that the conversion is unambiguous (and
1310/// that all of the base classes are accessible). Returns true
1311/// and emits a diagnostic if the code is ill-formed, returns false
1312/// otherwise. Loc is the location where this routine should point to
1313/// if there is an error, and Range is the source range to highlight
1314/// if there is an error.
1315bool
1316Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001317 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001318 unsigned AmbigiousBaseConvID,
1319 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001320 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001321 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001322 // First, determine whether the path from Derived to Base is
1323 // ambiguous. This is slightly more expensive than checking whether
1324 // the Derived to Base conversion exists, because here we need to
1325 // explore multiple paths to determine if there is an ambiguity.
1326 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1327 /*DetectVirtual=*/false);
1328 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1329 assert(DerivationOkay &&
1330 "Can only be used with a derived-to-base conversion");
1331 (void)DerivationOkay;
1332
1333 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001334 if (InaccessibleBaseID) {
1335 // Check that the base class can be accessed.
1336 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1337 InaccessibleBaseID)) {
1338 case AR_inaccessible:
1339 return true;
1340 case AR_accessible:
1341 case AR_dependent:
1342 case AR_delayed:
1343 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001344 }
John McCall6b2accb2010-02-10 09:31:12 +00001345 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001346
1347 // Build a base path if necessary.
1348 if (BasePath)
1349 BuildBasePathArray(Paths, *BasePath);
1350 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001351 }
1352
1353 // We know that the derived-to-base conversion is ambiguous, and
1354 // we're going to produce a diagnostic. Perform the derived-to-base
1355 // search just one more time to compute all of the possible paths so
1356 // that we can print them out. This is more expensive than any of
1357 // the previous derived-to-base checks we've done, but at this point
1358 // performance isn't as much of an issue.
1359 Paths.clear();
1360 Paths.setRecordingPaths(true);
1361 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1362 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1363 (void)StillOkay;
1364
1365 // Build up a textual representation of the ambiguous paths, e.g.,
1366 // D -> B -> A, that will be used to illustrate the ambiguous
1367 // conversions in the diagnostic. We only print one of the paths
1368 // to each base class subobject.
1369 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1370
1371 Diag(Loc, AmbigiousBaseConvID)
1372 << Derived << Base << PathDisplayStr << Range << Name;
1373 return true;
1374}
1375
1376bool
1377Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001378 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001379 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001380 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001381 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001382 IgnoreAccess ? 0
1383 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001384 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001385 Loc, Range, DeclarationName(),
1386 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001387}
1388
1389
1390/// @brief Builds a string representing ambiguous paths from a
1391/// specific derived class to different subobjects of the same base
1392/// class.
1393///
1394/// This function builds a string that can be used in error messages
1395/// to show the different paths that one can take through the
1396/// inheritance hierarchy to go from the derived class to different
1397/// subobjects of a base class. The result looks something like this:
1398/// @code
1399/// struct D -> struct B -> struct A
1400/// struct D -> struct C -> struct A
1401/// @endcode
1402std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1403 std::string PathDisplayStr;
1404 std::set<unsigned> DisplayedPaths;
1405 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1406 Path != Paths.end(); ++Path) {
1407 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1408 // We haven't displayed a path to this particular base
1409 // class subobject yet.
1410 PathDisplayStr += "\n ";
1411 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1412 for (CXXBasePath::const_iterator Element = Path->begin();
1413 Element != Path->end(); ++Element)
1414 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1415 }
1416 }
1417
1418 return PathDisplayStr;
1419}
1420
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001421//===----------------------------------------------------------------------===//
1422// C++ class member Handling
1423//===----------------------------------------------------------------------===//
1424
Abramo Bagnara6206d532010-06-05 05:09:32 +00001425/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001426bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1427 SourceLocation ASLoc,
1428 SourceLocation ColonLoc,
1429 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001430 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001431 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001432 ASLoc, ColonLoc);
1433 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001434 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001435}
1436
Anders Carlsson9e682d92011-01-20 05:57:14 +00001437/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001438void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001439 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001440 if (!MD || !MD->isVirtual())
1441 return;
1442
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001443 if (MD->isDependentContext())
1444 return;
1445
Anders Carlsson9e682d92011-01-20 05:57:14 +00001446 // C++0x [class.virtual]p3:
1447 // If a virtual function is marked with the virt-specifier override and does
1448 // not override a member function of a base class,
1449 // the program is ill-formed.
1450 bool HasOverriddenMethods =
1451 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001452 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001453 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001454 diag::err_function_marked_override_not_overriding)
1455 << MD->getDeclName();
1456 return;
1457 }
1458}
1459
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001460/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1461/// function overrides a virtual member function marked 'final', according to
1462/// C++0x [class.virtual]p3.
1463bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1464 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001465 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001466 return false;
1467
1468 Diag(New->getLocation(), diag::err_final_function_overridden)
1469 << New->getDeclName();
1470 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1471 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001472}
1473
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001474/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1475/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001476/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1477/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1478/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001479Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001480Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001481 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001482 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001483 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001484 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001485 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1486 DeclarationName Name = NameInfo.getName();
1487 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001488
1489 // For anonymous bitfields, the location should point to the type.
1490 if (Loc.isInvalid())
1491 Loc = D.getSourceRange().getBegin();
1492
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001493 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001494
John McCall4bde1e12010-06-04 08:34:12 +00001495 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001496 assert(!DS.isFriendSpecified());
1497
Richard Smith1ab0d902011-06-25 02:28:38 +00001498 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001499
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001500 // C++ 9.2p6: A member shall not be declared to have automatic storage
1501 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001502 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1503 // data members and cannot be applied to names declared const or static,
1504 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001505 switch (DS.getStorageClassSpec()) {
1506 case DeclSpec::SCS_unspecified:
1507 case DeclSpec::SCS_typedef:
1508 case DeclSpec::SCS_static:
1509 // FALL THROUGH.
1510 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001511 case DeclSpec::SCS_mutable:
1512 if (isFunc) {
1513 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001514 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001515 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001516 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Sebastian Redla11f42f2008-11-17 23:24:37 +00001518 // FIXME: It would be nicer if the keyword was ignored only for this
1519 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001520 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001521 }
1522 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001523 default:
1524 if (DS.getStorageClassSpecLoc().isValid())
1525 Diag(DS.getStorageClassSpecLoc(),
1526 diag::err_storageclass_invalid_for_member);
1527 else
1528 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1529 D.getMutableDeclSpec().ClearStorageClassSpecs();
1530 }
1531
Sebastian Redl669d5d72008-11-14 23:42:31 +00001532 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1533 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001534 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001535
1536 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001537 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001538 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001539
1540 // Data members must have identifiers for names.
1541 if (Name.getNameKind() != DeclarationName::Identifier) {
1542 Diag(Loc, diag::err_bad_variable_name)
1543 << Name;
1544 return 0;
1545 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001546
Douglas Gregorf2503652011-09-21 14:40:46 +00001547 IdentifierInfo *II = Name.getAsIdentifierInfo();
1548
1549 // Member field could not be with "template" keyword.
1550 // So TemplateParameterLists should be empty in this case.
1551 if (TemplateParameterLists.size()) {
1552 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1553 if (TemplateParams->size()) {
1554 // There is no such thing as a member field template.
1555 Diag(D.getIdentifierLoc(), diag::err_template_member)
1556 << II
1557 << SourceRange(TemplateParams->getTemplateLoc(),
1558 TemplateParams->getRAngleLoc());
1559 } else {
1560 // There is an extraneous 'template<>' for this member.
1561 Diag(TemplateParams->getTemplateLoc(),
1562 diag::err_template_member_noparams)
1563 << II
1564 << SourceRange(TemplateParams->getTemplateLoc(),
1565 TemplateParams->getRAngleLoc());
1566 }
1567 return 0;
1568 }
1569
Douglas Gregor922fff22010-10-13 22:19:53 +00001570 if (SS.isSet() && !SS.isInvalid()) {
1571 // The user provided a superfluous scope specifier inside a class
1572 // definition:
1573 //
1574 // class X {
1575 // int X::member;
1576 // };
1577 DeclContext *DC = 0;
1578 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1579 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001580 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor922fff22010-10-13 22:19:53 +00001581 else
1582 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1583 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001584
Douglas Gregor922fff22010-10-13 22:19:53 +00001585 SS.clear();
1586 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001587
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001588 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001589 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001590 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001591 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001592 assert(!HasDeferredInit);
1593
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001594 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001595 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001596 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001597 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001598
1599 // Non-instance-fields can't have a bitfield.
1600 if (BitWidth) {
1601 if (Member->isInvalidDecl()) {
1602 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001603 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001604 // C++ 9.6p3: A bit-field shall not be a static member.
1605 // "static member 'A' cannot be a bit-field"
1606 Diag(Loc, diag::err_static_not_bitfield)
1607 << Name << BitWidth->getSourceRange();
1608 } else if (isa<TypedefDecl>(Member)) {
1609 // "typedef member 'x' cannot be a bit-field"
1610 Diag(Loc, diag::err_typedef_not_bitfield)
1611 << Name << BitWidth->getSourceRange();
1612 } else {
1613 // A function typedef ("typedef int f(); f a;").
1614 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1615 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001616 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001617 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001618 }
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Chris Lattner8b963ef2009-03-05 23:01:03 +00001620 BitWidth = 0;
1621 Member->setInvalidDecl();
1622 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001623
1624 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Douglas Gregor37b372b2009-08-20 22:52:58 +00001626 // If we have declared a member function template, set the access of the
1627 // templated declaration as well.
1628 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1629 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001630 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001631
Anders Carlssonaae5af22011-01-20 04:34:22 +00001632 if (VS.isOverrideSpecified()) {
1633 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1634 if (!MD || !MD->isVirtual()) {
1635 Diag(Member->getLocStart(),
1636 diag::override_keyword_only_allowed_on_virtual_member_functions)
1637 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001638 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001639 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001640 }
1641 if (VS.isFinalSpecified()) {
1642 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1643 if (!MD || !MD->isVirtual()) {
1644 Diag(Member->getLocStart(),
1645 diag::override_keyword_only_allowed_on_virtual_member_functions)
1646 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001647 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001648 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001649 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001650
Douglas Gregorf5251602011-03-08 17:10:18 +00001651 if (VS.getLastLocation().isValid()) {
1652 // Update the end location of a method that has a virt-specifiers.
1653 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1654 MD->setRangeEnd(VS.getLastLocation());
1655 }
1656
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001657 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001658
Douglas Gregor10bd3682008-11-17 22:58:34 +00001659 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001660
John McCallb25b2952011-02-15 07:12:36 +00001661 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001662 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001663 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001664}
1665
Richard Smith7a614d82011-06-11 17:19:42 +00001666/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001667/// in-class initializer for a non-static C++ class member, and after
1668/// instantiating an in-class initializer in a class template. Such actions
1669/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001670void
1671Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1672 Expr *InitExpr) {
1673 FieldDecl *FD = cast<FieldDecl>(D);
1674
1675 if (!InitExpr) {
1676 FD->setInvalidDecl();
1677 FD->removeInClassInitializer();
1678 return;
1679 }
1680
Peter Collingbournefef21892011-10-23 18:59:44 +00001681 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1682 FD->setInvalidDecl();
1683 FD->removeInClassInitializer();
1684 return;
1685 }
1686
Richard Smith7a614d82011-06-11 17:19:42 +00001687 ExprResult Init = InitExpr;
1688 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1689 // FIXME: if there is no EqualLoc, this is list-initialization.
1690 Init = PerformCopyInitialization(
1691 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1692 if (Init.isInvalid()) {
1693 FD->setInvalidDecl();
1694 return;
1695 }
1696
1697 CheckImplicitConversions(Init.get(), EqualLoc);
1698 }
1699
1700 // C++0x [class.base.init]p7:
1701 // The initialization of each base and member constitutes a
1702 // full-expression.
1703 Init = MaybeCreateExprWithCleanups(Init);
1704 if (Init.isInvalid()) {
1705 FD->setInvalidDecl();
1706 return;
1707 }
1708
1709 InitExpr = Init.release();
1710
1711 FD->setInClassInitializer(InitExpr);
1712}
1713
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001714/// \brief Find the direct and/or virtual base specifiers that
1715/// correspond to the given base type, for use in base initialization
1716/// within a constructor.
1717static bool FindBaseInitializer(Sema &SemaRef,
1718 CXXRecordDecl *ClassDecl,
1719 QualType BaseType,
1720 const CXXBaseSpecifier *&DirectBaseSpec,
1721 const CXXBaseSpecifier *&VirtualBaseSpec) {
1722 // First, check for a direct base class.
1723 DirectBaseSpec = 0;
1724 for (CXXRecordDecl::base_class_const_iterator Base
1725 = ClassDecl->bases_begin();
1726 Base != ClassDecl->bases_end(); ++Base) {
1727 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1728 // We found a direct base of this type. That's what we're
1729 // initializing.
1730 DirectBaseSpec = &*Base;
1731 break;
1732 }
1733 }
1734
1735 // Check for a virtual base class.
1736 // FIXME: We might be able to short-circuit this if we know in advance that
1737 // there are no virtual bases.
1738 VirtualBaseSpec = 0;
1739 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1740 // We haven't found a base yet; search the class hierarchy for a
1741 // virtual base class.
1742 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1743 /*DetectVirtual=*/false);
1744 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1745 BaseType, Paths)) {
1746 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1747 Path != Paths.end(); ++Path) {
1748 if (Path->back().Base->isVirtual()) {
1749 VirtualBaseSpec = Path->back().Base;
1750 break;
1751 }
1752 }
1753 }
1754 }
1755
1756 return DirectBaseSpec || VirtualBaseSpec;
1757}
1758
Sebastian Redl6df65482011-09-24 17:48:25 +00001759/// \brief Handle a C++ member initializer using braced-init-list syntax.
1760MemInitResult
1761Sema::ActOnMemInitializer(Decl *ConstructorD,
1762 Scope *S,
1763 CXXScopeSpec &SS,
1764 IdentifierInfo *MemberOrBase,
1765 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001766 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001767 SourceLocation IdLoc,
1768 Expr *InitList,
1769 SourceLocation EllipsisLoc) {
1770 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001771 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001772 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001773}
1774
1775/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001776MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001777Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001778 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001779 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001780 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001781 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001782 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001783 SourceLocation IdLoc,
1784 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001785 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001786 SourceLocation RParenLoc,
1787 SourceLocation EllipsisLoc) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001788 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1789 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001790 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001791 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001792}
1793
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001794namespace {
1795
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001796// Callback to only accept typo corrections that can be a valid C++ member
1797// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001798class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1799 public:
1800 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1801 : ClassDecl(ClassDecl) {}
1802
1803 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1804 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1805 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1806 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1807 else
1808 return isa<TypeDecl>(ND);
1809 }
1810 return false;
1811 }
1812
1813 private:
1814 CXXRecordDecl *ClassDecl;
1815};
1816
1817}
1818
Sebastian Redl6df65482011-09-24 17:48:25 +00001819/// \brief Handle a C++ member initializer.
1820MemInitResult
1821Sema::BuildMemInitializer(Decl *ConstructorD,
1822 Scope *S,
1823 CXXScopeSpec &SS,
1824 IdentifierInfo *MemberOrBase,
1825 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001826 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001827 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001828 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001829 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001830 if (!ConstructorD)
1831 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001833 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001834
1835 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001836 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001837 if (!Constructor) {
1838 // The user wrote a constructor initializer on a function that is
1839 // not a C++ constructor. Ignore the error for now, because we may
1840 // have more member initializers coming; we'll diagnose it just
1841 // once in ActOnMemInitializers.
1842 return true;
1843 }
1844
1845 CXXRecordDecl *ClassDecl = Constructor->getParent();
1846
1847 // C++ [class.base.init]p2:
1848 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001849 // constructor's class and, if not found in that scope, are looked
1850 // up in the scope containing the constructor's definition.
1851 // [Note: if the constructor's class contains a member with the
1852 // same name as a direct or virtual base class of the class, a
1853 // mem-initializer-id naming the member or base class and composed
1854 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001855 // mem-initializer-id for the hidden base class may be specified
1856 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001857 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001858 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001859 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001860 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001861 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001862 ValueDecl *Member;
1863 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1864 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001865 if (EllipsisLoc.isValid())
1866 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001867 << MemberOrBase
1868 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001869
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001870 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001871 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001872 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001873 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001874 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001875 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001876 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001877
1878 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001879 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001880 } else if (DS.getTypeSpecType() == TST_decltype) {
1881 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001882 } else {
1883 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1884 LookupParsedName(R, S, &SS);
1885
1886 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1887 if (!TyD) {
1888 if (R.isAmbiguous()) return true;
1889
John McCallfd225442010-04-09 19:01:14 +00001890 // We don't want access-control diagnostics here.
1891 R.suppressDiagnostics();
1892
Douglas Gregor7a886e12010-01-19 06:46:48 +00001893 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1894 bool NotUnknownSpecialization = false;
1895 DeclContext *DC = computeDeclContext(SS, false);
1896 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1897 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1898
1899 if (!NotUnknownSpecialization) {
1900 // When the scope specifier can refer to a member of an unknown
1901 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001902 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1903 SS.getWithLocInContext(Context),
1904 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001905 if (BaseType.isNull())
1906 return true;
1907
Douglas Gregor7a886e12010-01-19 06:46:48 +00001908 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001909 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001910 }
1911 }
1912
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001913 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001914 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001915 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001916 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001917 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001918 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001919 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1920 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1921 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001922 // We have found a non-static data member with a similar
1923 // name to what was typed; complain and initialize that
1924 // member.
1925 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1926 << MemberOrBase << true << CorrectedQuotedStr
1927 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1928 Diag(Member->getLocation(), diag::note_previous_decl)
1929 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001930
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001931 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001932 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001933 const CXXBaseSpecifier *DirectBaseSpec;
1934 const CXXBaseSpecifier *VirtualBaseSpec;
1935 if (FindBaseInitializer(*this, ClassDecl,
1936 Context.getTypeDeclType(Type),
1937 DirectBaseSpec, VirtualBaseSpec)) {
1938 // We have found a direct or virtual base class with a
1939 // similar name to what was typed; complain and initialize
1940 // that base class.
1941 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001942 << MemberOrBase << false << CorrectedQuotedStr
1943 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001944
1945 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1946 : VirtualBaseSpec;
1947 Diag(BaseSpec->getSourceRange().getBegin(),
1948 diag::note_base_class_specified_here)
1949 << BaseSpec->getType()
1950 << BaseSpec->getSourceRange();
1951
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001952 TyD = Type;
1953 }
1954 }
1955 }
1956
Douglas Gregor7a886e12010-01-19 06:46:48 +00001957 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001958 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001959 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001960 return true;
1961 }
John McCall2b194412009-12-21 10:41:20 +00001962 }
1963
Douglas Gregor7a886e12010-01-19 06:46:48 +00001964 if (BaseType.isNull()) {
1965 BaseType = Context.getTypeDeclType(TyD);
1966 if (SS.isSet()) {
1967 NestedNameSpecifier *Qualifier =
1968 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001969
Douglas Gregor7a886e12010-01-19 06:46:48 +00001970 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001971 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001972 }
John McCall2b194412009-12-21 10:41:20 +00001973 }
1974 }
Mike Stump1eb44332009-09-09 15:08:12 +00001975
John McCalla93c9342009-12-07 02:54:59 +00001976 if (!TInfo)
1977 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001978
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001979 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001980}
1981
Chandler Carruth81c64772011-09-03 01:14:15 +00001982/// Checks a member initializer expression for cases where reference (or
1983/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001984static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1985 Expr *Init,
1986 SourceLocation IdLoc) {
1987 QualType MemberTy = Member->getType();
1988
1989 // We only handle pointers and references currently.
1990 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1991 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1992 return;
1993
1994 const bool IsPointer = MemberTy->isPointerType();
1995 if (IsPointer) {
1996 if (const UnaryOperator *Op
1997 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1998 // The only case we're worried about with pointers requires taking the
1999 // address.
2000 if (Op->getOpcode() != UO_AddrOf)
2001 return;
2002
2003 Init = Op->getSubExpr();
2004 } else {
2005 // We only handle address-of expression initializers for pointers.
2006 return;
2007 }
2008 }
2009
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002010 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2011 // Taking the address of a temporary will be diagnosed as a hard error.
2012 if (IsPointer)
2013 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002014
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002015 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2016 << Member << Init->getSourceRange();
2017 } else if (const DeclRefExpr *DRE
2018 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2019 // We only warn when referring to a non-reference parameter declaration.
2020 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2021 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002022 return;
2023
2024 S.Diag(Init->getExprLoc(),
2025 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2026 : diag::warn_bind_ref_member_to_parameter)
2027 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002028 } else {
2029 // Other initializers are fine.
2030 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002031 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002032
2033 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2034 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002035}
2036
John McCallb4190042009-11-04 23:02:40 +00002037/// Checks an initializer expression for use of uninitialized fields, such as
2038/// containing the field that is being initialized. Returns true if there is an
2039/// uninitialized field was used an updates the SourceLocation parameter; false
2040/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002041static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002042 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002043 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002044 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2045
Nick Lewycky43ad1822010-06-15 07:32:55 +00002046 if (isa<CallExpr>(S)) {
2047 // Do not descend into function calls or constructors, as the use
2048 // of an uninitialized field may be valid. One would have to inspect
2049 // the contents of the function/ctor to determine if it is safe or not.
2050 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2051 // may be safe, depending on what the function/ctor does.
2052 return false;
2053 }
2054 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2055 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002056
2057 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2058 // The member expression points to a static data member.
2059 assert(VD->isStaticDataMember() &&
2060 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002061 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002062 return false;
2063 }
2064
2065 if (isa<EnumConstantDecl>(RhsField)) {
2066 // The member expression points to an enum.
2067 return false;
2068 }
2069
John McCallb4190042009-11-04 23:02:40 +00002070 if (RhsField == LhsField) {
2071 // Initializing a field with itself. Throw a warning.
2072 // But wait; there are exceptions!
2073 // Exception #1: The field may not belong to this record.
2074 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002075 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002076 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2077 // Even though the field matches, it does not belong to this record.
2078 return false;
2079 }
2080 // None of the exceptions triggered; return true to indicate an
2081 // uninitialized field was used.
2082 *L = ME->getMemberLoc();
2083 return true;
2084 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002085 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002086 // sizeof/alignof doesn't reference contents, do not warn.
2087 return false;
2088 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2089 // address-of doesn't reference contents (the pointer may be dereferenced
2090 // in the same expression but it would be rare; and weird).
2091 if (UOE->getOpcode() == UO_AddrOf)
2092 return false;
John McCallb4190042009-11-04 23:02:40 +00002093 }
John McCall7502c1d2011-02-13 04:07:26 +00002094 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002095 if (!*it) {
2096 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002097 continue;
2098 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002099 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2100 return true;
John McCallb4190042009-11-04 23:02:40 +00002101 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002102 return false;
John McCallb4190042009-11-04 23:02:40 +00002103}
2104
John McCallf312b1e2010-08-26 23:41:50 +00002105MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002106Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002107 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002108 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2109 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2110 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002111 "Member must be a FieldDecl or IndirectFieldDecl");
2112
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002113 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002114 return true;
2115
Douglas Gregor464b2f02010-11-05 22:21:31 +00002116 if (Member->isInvalidDecl())
2117 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002118
John McCallb4190042009-11-04 23:02:40 +00002119 // Diagnose value-uses of fields to initialize themselves, e.g.
2120 // foo(foo)
2121 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002122 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002123 Expr **Args;
2124 unsigned NumArgs;
2125 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2126 Args = ParenList->getExprs();
2127 NumArgs = ParenList->getNumExprs();
2128 } else {
2129 InitListExpr *InitList = cast<InitListExpr>(Init);
2130 Args = InitList->getInits();
2131 NumArgs = InitList->getNumInits();
2132 }
2133 for (unsigned i = 0; i < NumArgs; ++i) {
John McCallb4190042009-11-04 23:02:40 +00002134 SourceLocation L;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002135 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002136 // FIXME: Return true in the case when other fields are used before being
2137 // uninitialized. For example, let this field be the i'th field. When
2138 // initializing the i'th field, throw a warning if any of the >= i'th
2139 // fields are used, as they are not yet initialized.
2140 // Right now we are only handling the case where the i'th field uses
2141 // itself in its initializer.
2142 Diag(L, diag::warn_field_is_uninit);
2143 }
2144 }
2145
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002146 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002147
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002148 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002149 // Can't check initialization for a member of dependent type or when
2150 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002151 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002152 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002153 bool InitList = false;
2154 if (isa<InitListExpr>(Init)) {
2155 InitList = true;
2156 Args = &Init;
2157 NumArgs = 1;
2158 }
2159
Chandler Carruth894aed92010-12-06 09:23:57 +00002160 // Initialize the member.
2161 InitializedEntity MemberEntity =
2162 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2163 : InitializedEntity::InitializeMember(IndirectMember, 0);
2164 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002165 InitList ? InitializationKind::CreateDirectList(IdLoc)
2166 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2167 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002168
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002169 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2170 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2171 MultiExprArg(*this, Args, NumArgs),
2172 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002173 if (MemberInit.isInvalid())
2174 return true;
2175
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002176 CheckImplicitConversions(MemberInit.get(),
2177 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002178
2179 // C++0x [class.base.init]p7:
2180 // The initialization of each base and member constitutes a
2181 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002182 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002183 if (MemberInit.isInvalid())
2184 return true;
2185
2186 // If we are in a dependent context, template instantiation will
2187 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002188 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002189 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2190 // of the information that we have about the member
2191 // initializer. However, deconstructing the ASTs is a dicey process,
2192 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002193 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002194 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002195 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002196 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002197 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2198 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002199 }
2200
Chandler Carruth894aed92010-12-06 09:23:57 +00002201 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002202 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2203 InitRange.getBegin(), Init,
2204 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002205 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002206 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2207 InitRange.getBegin(), Init,
2208 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002209 }
Eli Friedman59c04372009-07-29 19:44:27 +00002210}
2211
John McCallf312b1e2010-08-26 23:41:50 +00002212MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002213Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002214 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002215 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002216 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002217 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002218 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002219 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002220
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002221 bool InitList = true;
2222 Expr **Args = &Init;
2223 unsigned NumArgs = 1;
2224 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2225 InitList = false;
2226 Args = ParenList->getExprs();
2227 NumArgs = ParenList->getNumExprs();
2228 }
2229
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002230 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002231 // Initialize the object.
2232 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2233 QualType(ClassDecl->getTypeForDecl(), 0));
2234 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002235 InitList ? InitializationKind::CreateDirectList(NameLoc)
2236 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2237 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002238 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2239 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2240 MultiExprArg(*this, Args,NumArgs),
2241 0);
Sean Hunt41717662011-02-26 19:13:13 +00002242 if (DelegationInit.isInvalid())
2243 return true;
2244
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002245 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2246 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002247
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002248 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002249
2250 // C++0x [class.base.init]p7:
2251 // The initialization of each base and member constitutes a
2252 // full-expression.
2253 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2254 if (DelegationInit.isInvalid())
2255 return true;
2256
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002257 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002258 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002259 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002260}
2261
2262MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002263Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002264 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002265 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002266 SourceLocation BaseLoc
2267 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002268
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002269 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2270 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2271 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2272
2273 // C++ [class.base.init]p2:
2274 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002275 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002276 // of that class, the mem-initializer is ill-formed. A
2277 // mem-initializer-list can initialize a base class using any
2278 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002279 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002280
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002281 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002282 if (EllipsisLoc.isValid()) {
2283 // This is a pack expansion.
2284 if (!BaseType->containsUnexpandedParameterPack()) {
2285 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002286 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002287
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002288 EllipsisLoc = SourceLocation();
2289 }
2290 } else {
2291 // Check for any unexpanded parameter packs.
2292 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2293 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002294
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002295 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002296 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002297 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002298
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002299 // Check for direct and virtual base classes.
2300 const CXXBaseSpecifier *DirectBaseSpec = 0;
2301 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2302 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002303 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2304 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002305 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002306
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002307 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2308 VirtualBaseSpec);
2309
2310 // C++ [base.class.init]p2:
2311 // Unless the mem-initializer-id names a nonstatic data member of the
2312 // constructor's class or a direct or virtual base of that class, the
2313 // mem-initializer is ill-formed.
2314 if (!DirectBaseSpec && !VirtualBaseSpec) {
2315 // If the class has any dependent bases, then it's possible that
2316 // one of those types will resolve to the same type as
2317 // BaseType. Therefore, just treat this as a dependent base
2318 // class initialization. FIXME: Should we try to check the
2319 // initialization anyway? It seems odd.
2320 if (ClassDecl->hasAnyDependentBases())
2321 Dependent = true;
2322 else
2323 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2324 << BaseType << Context.getTypeDeclType(ClassDecl)
2325 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2326 }
2327 }
2328
2329 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002330 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Sebastian Redl6df65482011-09-24 17:48:25 +00002332 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2333 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002334 InitRange.getBegin(), Init,
2335 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002336 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002337
2338 // C++ [base.class.init]p2:
2339 // If a mem-initializer-id is ambiguous because it designates both
2340 // a direct non-virtual base class and an inherited virtual base
2341 // class, the mem-initializer is ill-formed.
2342 if (DirectBaseSpec && VirtualBaseSpec)
2343 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002344 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002345
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002346 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002347 if (!BaseSpec)
2348 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2349
2350 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002351 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002352 Expr **Args = &Init;
2353 unsigned NumArgs = 1;
2354 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002355 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002356 Args = ParenList->getExprs();
2357 NumArgs = ParenList->getNumExprs();
2358 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002359
2360 InitializedEntity BaseEntity =
2361 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2362 InitializationKind Kind =
2363 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2364 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2365 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002366 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2367 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2368 MultiExprArg(*this, Args, NumArgs),
2369 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002370 if (BaseInit.isInvalid())
2371 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002372
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002373 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002374
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002375 // C++0x [class.base.init]p7:
2376 // The initialization of each base and member constitutes a
2377 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002378 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002379 if (BaseInit.isInvalid())
2380 return true;
2381
2382 // If we are in a dependent context, template instantiation will
2383 // perform this type-checking again. Just save the arguments that we
2384 // received in a ParenListExpr.
2385 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2386 // of the information that we have about the base
2387 // initializer. However, deconstructing the ASTs is a dicey process,
2388 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002389 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002390 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002391
Sean Huntcbb67482011-01-08 20:30:50 +00002392 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002393 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002394 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002395 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002396 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002397}
2398
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002399// Create a static_cast\<T&&>(expr).
2400static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2401 QualType ExprType = E->getType();
2402 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2403 SourceLocation ExprLoc = E->getLocStart();
2404 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2405 TargetType, ExprLoc);
2406
2407 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2408 SourceRange(ExprLoc, ExprLoc),
2409 E->getSourceRange()).take();
2410}
2411
Anders Carlssone5ef7402010-04-23 03:10:23 +00002412/// ImplicitInitializerKind - How an implicit base or member initializer should
2413/// initialize its base or member.
2414enum ImplicitInitializerKind {
2415 IIK_Default,
2416 IIK_Copy,
2417 IIK_Move
2418};
2419
Anders Carlssondefefd22010-04-23 02:00:02 +00002420static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002421BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002422 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002423 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002424 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002425 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002426 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002427 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2428 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002429
John McCall60d7b3a2010-08-24 06:29:42 +00002430 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002431
2432 switch (ImplicitInitKind) {
2433 case IIK_Default: {
2434 InitializationKind InitKind
2435 = InitializationKind::CreateDefault(Constructor->getLocation());
2436 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2437 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002438 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002439 break;
2440 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002441
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002442 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002443 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002444 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002445 ParmVarDecl *Param = Constructor->getParamDecl(0);
2446 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002447
Anders Carlssone5ef7402010-04-23 03:10:23 +00002448 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002449 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2450 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002451 Constructor->getLocation(), ParamType,
2452 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002453
Eli Friedman5f2987c2012-02-02 03:46:19 +00002454 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2455
Anders Carlssonc7957502010-04-24 22:02:54 +00002456 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002457 QualType ArgTy =
2458 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2459 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002460
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002461 if (Moving) {
2462 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2463 }
2464
John McCallf871d0c2010-08-07 06:22:56 +00002465 CXXCastPath BasePath;
2466 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002467 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2468 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002469 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002470 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002471
Anders Carlssone5ef7402010-04-23 03:10:23 +00002472 InitializationKind InitKind
2473 = InitializationKind::CreateDirect(Constructor->getLocation(),
2474 SourceLocation(), SourceLocation());
2475 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2476 &CopyCtorArg, 1);
2477 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002478 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002479 break;
2480 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002481 }
John McCall9ae2f072010-08-23 23:25:46 +00002482
Douglas Gregor53c374f2010-12-07 00:41:46 +00002483 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002484 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002485 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002486
Anders Carlssondefefd22010-04-23 02:00:02 +00002487 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002488 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002489 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2490 SourceLocation()),
2491 BaseSpec->isVirtual(),
2492 SourceLocation(),
2493 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002494 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002495 SourceLocation());
2496
Anders Carlssondefefd22010-04-23 02:00:02 +00002497 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002498}
2499
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002500static bool RefersToRValueRef(Expr *MemRef) {
2501 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2502 return Referenced->getType()->isRValueReferenceType();
2503}
2504
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002505static bool
2506BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002507 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002508 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002509 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002510 if (Field->isInvalidDecl())
2511 return true;
2512
Chandler Carruthf186b542010-06-29 23:50:44 +00002513 SourceLocation Loc = Constructor->getLocation();
2514
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002515 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2516 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002517 ParmVarDecl *Param = Constructor->getParamDecl(0);
2518 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002519
2520 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002521 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2522 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002523
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002524 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002525 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2526 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002527 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002528
Eli Friedman5f2987c2012-02-02 03:46:19 +00002529 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2530
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002531 if (Moving) {
2532 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2533 }
2534
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002535 // Build a reference to this field within the parameter.
2536 CXXScopeSpec SS;
2537 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2538 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002539 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2540 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002541 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002542 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002543 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002544 ParamType, Loc,
2545 /*IsArrow=*/false,
2546 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002547 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002548 /*FirstQualifierInScope=*/0,
2549 MemberLookup,
2550 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002551 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002552 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002553
2554 // C++11 [class.copy]p15:
2555 // - if a member m has rvalue reference type T&&, it is direct-initialized
2556 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002557 if (RefersToRValueRef(CtorArg.get())) {
2558 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002559 }
2560
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002561 // When the field we are copying is an array, create index variables for
2562 // each dimension of the array. We use these index variables to subscript
2563 // the source array, and other clients (e.g., CodeGen) will perform the
2564 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002565 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002566 QualType BaseType = Field->getType();
2567 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002568 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002569 while (const ConstantArrayType *Array
2570 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002571 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002572 // Create the iteration variable for this array index.
2573 IdentifierInfo *IterationVarName = 0;
2574 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002575 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002576 llvm::raw_svector_ostream OS(Str);
2577 OS << "__i" << IndexVariables.size();
2578 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2579 }
2580 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002581 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002582 IterationVarName, SizeType,
2583 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002584 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002585 IndexVariables.push_back(IterationVar);
2586
2587 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002588 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002589 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002590 assert(!IterationVarRef.isInvalid() &&
2591 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002592 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2593 assert(!IterationVarRef.isInvalid() &&
2594 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002595
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002596 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002597 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002598 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002599 Loc);
2600 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002601 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002602
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002603 BaseType = Array->getElementType();
2604 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002605
2606 // The array subscript expression is an lvalue, which is wrong for moving.
2607 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002608 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002609
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002610 // Construct the entity that we will be initializing. For an array, this
2611 // will be first element in the array, which may require several levels
2612 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002613 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002614 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002615 if (Indirect)
2616 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2617 else
2618 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002619 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2620 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2621 0,
2622 Entities.back()));
2623
2624 // Direct-initialize to use the copy constructor.
2625 InitializationKind InitKind =
2626 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2627
Sebastian Redl74e611a2011-09-04 18:14:28 +00002628 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002629 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002630 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002631
John McCall60d7b3a2010-08-24 06:29:42 +00002632 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002633 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002634 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002635 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002636 if (MemberInit.isInvalid())
2637 return true;
2638
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002639 if (Indirect) {
2640 assert(IndexVariables.size() == 0 &&
2641 "Indirect field improperly initialized");
2642 CXXMemberInit
2643 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2644 Loc, Loc,
2645 MemberInit.takeAs<Expr>(),
2646 Loc);
2647 } else
2648 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2649 Loc, MemberInit.takeAs<Expr>(),
2650 Loc,
2651 IndexVariables.data(),
2652 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002653 return false;
2654 }
2655
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002656 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2657
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002658 QualType FieldBaseElementType =
2659 SemaRef.Context.getBaseElementType(Field->getType());
2660
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002661 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002662 InitializedEntity InitEntity
2663 = Indirect? InitializedEntity::InitializeMember(Indirect)
2664 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002665 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002666 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002667
2668 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002669 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002670 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002671
Douglas Gregor53c374f2010-12-07 00:41:46 +00002672 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002673 if (MemberInit.isInvalid())
2674 return true;
2675
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002676 if (Indirect)
2677 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2678 Indirect, Loc,
2679 Loc,
2680 MemberInit.get(),
2681 Loc);
2682 else
2683 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2684 Field, Loc, Loc,
2685 MemberInit.get(),
2686 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002687 return false;
2688 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002689
Sean Hunt1f2f3842011-05-17 00:19:05 +00002690 if (!Field->getParent()->isUnion()) {
2691 if (FieldBaseElementType->isReferenceType()) {
2692 SemaRef.Diag(Constructor->getLocation(),
2693 diag::err_uninitialized_member_in_ctor)
2694 << (int)Constructor->isImplicit()
2695 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2696 << 0 << Field->getDeclName();
2697 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2698 return true;
2699 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002700
Sean Hunt1f2f3842011-05-17 00:19:05 +00002701 if (FieldBaseElementType.isConstQualified()) {
2702 SemaRef.Diag(Constructor->getLocation(),
2703 diag::err_uninitialized_member_in_ctor)
2704 << (int)Constructor->isImplicit()
2705 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2706 << 1 << Field->getDeclName();
2707 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2708 return true;
2709 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002710 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002711
John McCallf85e1932011-06-15 23:02:42 +00002712 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2713 FieldBaseElementType->isObjCRetainableType() &&
2714 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2715 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2716 // Instant objects:
2717 // Default-initialize Objective-C pointers to NULL.
2718 CXXMemberInit
2719 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2720 Loc, Loc,
2721 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2722 Loc);
2723 return false;
2724 }
2725
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002726 // Nothing to initialize.
2727 CXXMemberInit = 0;
2728 return false;
2729}
John McCallf1860e52010-05-20 23:23:51 +00002730
2731namespace {
2732struct BaseAndFieldInfo {
2733 Sema &S;
2734 CXXConstructorDecl *Ctor;
2735 bool AnyErrorsInInits;
2736 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002737 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002738 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002739
2740 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2741 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002742 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2743 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002744 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002745 else if (Generated && Ctor->isMoveConstructor())
2746 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002747 else
2748 IIK = IIK_Default;
2749 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002750
2751 bool isImplicitCopyOrMove() const {
2752 switch (IIK) {
2753 case IIK_Copy:
2754 case IIK_Move:
2755 return true;
2756
2757 case IIK_Default:
2758 return false;
2759 }
David Blaikie30263482012-01-20 21:50:17 +00002760
2761 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002762 }
John McCallf1860e52010-05-20 23:23:51 +00002763};
2764}
2765
Richard Smitha4950662011-09-19 13:34:43 +00002766/// \brief Determine whether the given indirect field declaration is somewhere
2767/// within an anonymous union.
2768static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2769 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2770 CEnd = F->chain_end();
2771 C != CEnd; ++C)
2772 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2773 if (Record->isUnion())
2774 return true;
2775
2776 return false;
2777}
2778
Douglas Gregorddb21472011-11-02 23:04:16 +00002779/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2780/// array type.
2781static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2782 if (T->isIncompleteArrayType())
2783 return true;
2784
2785 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2786 if (!ArrayT->getSize())
2787 return true;
2788
2789 T = ArrayT->getElementType();
2790 }
2791
2792 return false;
2793}
2794
Richard Smith7a614d82011-06-11 17:19:42 +00002795static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002796 FieldDecl *Field,
2797 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002798
Chandler Carruthe861c602010-06-30 02:59:29 +00002799 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002800 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002801 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002802 return false;
2803 }
2804
Richard Smith7a614d82011-06-11 17:19:42 +00002805 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2806 // has a brace-or-equal-initializer, the entity is initialized as specified
2807 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002808 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002809 CXXCtorInitializer *Init;
2810 if (Indirect)
2811 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2812 SourceLocation(),
2813 SourceLocation(), 0,
2814 SourceLocation());
2815 else
2816 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2817 SourceLocation(),
2818 SourceLocation(), 0,
2819 SourceLocation());
2820 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002821 return false;
2822 }
2823
Richard Smithc115f632011-09-18 11:14:50 +00002824 // Don't build an implicit initializer for union members if none was
2825 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002826 if (Field->getParent()->isUnion() ||
2827 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002828 return false;
2829
Douglas Gregorddb21472011-11-02 23:04:16 +00002830 // Don't initialize incomplete or zero-length arrays.
2831 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2832 return false;
2833
John McCallf1860e52010-05-20 23:23:51 +00002834 // Don't try to build an implicit initializer if there were semantic
2835 // errors in any of the initializers (and therefore we might be
2836 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002837 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002838 return false;
2839
Sean Huntcbb67482011-01-08 20:30:50 +00002840 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002841 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2842 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002843 return true;
John McCallf1860e52010-05-20 23:23:51 +00002844
Francois Pichet00eb3f92010-12-04 09:14:42 +00002845 if (Init)
2846 Info.AllToInit.push_back(Init);
2847
John McCallf1860e52010-05-20 23:23:51 +00002848 return false;
2849}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002850
2851bool
2852Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2853 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002854 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002855 Constructor->setNumCtorInitializers(1);
2856 CXXCtorInitializer **initializer =
2857 new (Context) CXXCtorInitializer*[1];
2858 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2859 Constructor->setCtorInitializers(initializer);
2860
Sean Huntb76af9c2011-05-03 23:05:34 +00002861 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002862 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002863 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2864 }
2865
Sean Huntc1598702011-05-05 00:05:47 +00002866 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002867
Sean Hunt059ce0d2011-05-01 07:04:31 +00002868 return false;
2869}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002870
John McCallb77115d2011-06-17 00:18:42 +00002871bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2872 CXXCtorInitializer **Initializers,
2873 unsigned NumInitializers,
2874 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002875 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002876 // Just store the initializers as written, they will be checked during
2877 // instantiation.
2878 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002879 Constructor->setNumCtorInitializers(NumInitializers);
2880 CXXCtorInitializer **baseOrMemberInitializers =
2881 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002882 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002883 NumInitializers * sizeof(CXXCtorInitializer*));
2884 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002885 }
2886
2887 return false;
2888 }
2889
John McCallf1860e52010-05-20 23:23:51 +00002890 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002891
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002892 // We need to build the initializer AST according to order of construction
2893 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002894 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002895 if (!ClassDecl)
2896 return true;
2897
Eli Friedman80c30da2009-11-09 19:20:36 +00002898 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002899
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002900 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002901 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002902
2903 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002904 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002905 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002906 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002907 }
2908
Anders Carlsson711f34a2010-04-21 19:52:01 +00002909 // Keep track of the direct virtual bases.
2910 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2911 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2912 E = ClassDecl->bases_end(); I != E; ++I) {
2913 if (I->isVirtual())
2914 DirectVBases.insert(I);
2915 }
2916
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002917 // Push virtual bases before others.
2918 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2919 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2920
Sean Huntcbb67482011-01-08 20:30:50 +00002921 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002922 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2923 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002924 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002925 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002926 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002927 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002928 VBase, IsInheritedVirtualBase,
2929 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002930 HadError = true;
2931 continue;
2932 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002933
John McCallf1860e52010-05-20 23:23:51 +00002934 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002935 }
2936 }
Mike Stump1eb44332009-09-09 15:08:12 +00002937
John McCallf1860e52010-05-20 23:23:51 +00002938 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002939 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2940 E = ClassDecl->bases_end(); Base != E; ++Base) {
2941 // Virtuals are in the virtual base list and already constructed.
2942 if (Base->isVirtual())
2943 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002944
Sean Huntcbb67482011-01-08 20:30:50 +00002945 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002946 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2947 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002948 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002949 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002950 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002951 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002952 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002953 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002954 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002955 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002956
John McCallf1860e52010-05-20 23:23:51 +00002957 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002958 }
2959 }
Mike Stump1eb44332009-09-09 15:08:12 +00002960
John McCallf1860e52010-05-20 23:23:51 +00002961 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002962 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2963 MemEnd = ClassDecl->decls_end();
2964 Mem != MemEnd; ++Mem) {
2965 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002966 // C++ [class.bit]p2:
2967 // A declaration for a bit-field that omits the identifier declares an
2968 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2969 // initialized.
2970 if (F->isUnnamedBitfield())
2971 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002972
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002973 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002974 // handle anonymous struct/union fields based on their individual
2975 // indirect fields.
2976 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2977 continue;
2978
2979 if (CollectFieldInitializer(*this, Info, F))
2980 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002981 continue;
2982 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002983
2984 // Beyond this point, we only consider default initialization.
2985 if (Info.IIK != IIK_Default)
2986 continue;
2987
2988 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2989 if (F->getType()->isIncompleteArrayType()) {
2990 assert(ClassDecl->hasFlexibleArrayMember() &&
2991 "Incomplete array type is not valid");
2992 continue;
2993 }
2994
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002995 // Initialize each field of an anonymous struct individually.
2996 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2997 HadError = true;
2998
2999 continue;
3000 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003001 }
Mike Stump1eb44332009-09-09 15:08:12 +00003002
John McCallf1860e52010-05-20 23:23:51 +00003003 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003004 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003005 Constructor->setNumCtorInitializers(NumInitializers);
3006 CXXCtorInitializer **baseOrMemberInitializers =
3007 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003008 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003009 NumInitializers * sizeof(CXXCtorInitializer*));
3010 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003011
John McCallef027fe2010-03-16 21:39:52 +00003012 // Constructors implicitly reference the base and member
3013 // destructors.
3014 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3015 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003016 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003017
3018 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003019}
3020
Eli Friedman6347f422009-07-21 19:28:10 +00003021static void *GetKeyForTopLevelField(FieldDecl *Field) {
3022 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003023 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003024 if (RT->getDecl()->isAnonymousStructOrUnion())
3025 return static_cast<void *>(RT->getDecl());
3026 }
3027 return static_cast<void *>(Field);
3028}
3029
Anders Carlssonea356fb2010-04-02 05:42:15 +00003030static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003031 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003032}
3033
Anders Carlssonea356fb2010-04-02 05:42:15 +00003034static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003035 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003036 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003037 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003038
Eli Friedman6347f422009-07-21 19:28:10 +00003039 // For fields injected into the class via declaration of an anonymous union,
3040 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003041 FieldDecl *Field = Member->getAnyMember();
3042
John McCall3c3ccdb2010-04-10 09:28:51 +00003043 // If the field is a member of an anonymous struct or union, our key
3044 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003045 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003046 if (RD->isAnonymousStructOrUnion()) {
3047 while (true) {
3048 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3049 if (Parent->isAnonymousStructOrUnion())
3050 RD = Parent;
3051 else
3052 break;
3053 }
3054
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003055 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003056 }
Mike Stump1eb44332009-09-09 15:08:12 +00003057
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003058 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003059}
3060
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003061static void
3062DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003063 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003064 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003065 unsigned NumInits) {
3066 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003067 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003068
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003069 // Don't check initializers order unless the warning is enabled at the
3070 // location of at least one initializer.
3071 bool ShouldCheckOrder = false;
3072 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003073 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003074 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3075 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003076 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003077 ShouldCheckOrder = true;
3078 break;
3079 }
3080 }
3081 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003082 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003083
John McCalld6ca8da2010-04-10 07:37:23 +00003084 // Build the list of bases and members in the order that they'll
3085 // actually be initialized. The explicit initializers should be in
3086 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003087 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003088
Anders Carlsson071d6102010-04-02 03:38:04 +00003089 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3090
John McCalld6ca8da2010-04-10 07:37:23 +00003091 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003092 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003093 ClassDecl->vbases_begin(),
3094 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003095 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003096
John McCalld6ca8da2010-04-10 07:37:23 +00003097 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003098 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003099 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003100 if (Base->isVirtual())
3101 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003102 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003103 }
Mike Stump1eb44332009-09-09 15:08:12 +00003104
John McCalld6ca8da2010-04-10 07:37:23 +00003105 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003106 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003107 E = ClassDecl->field_end(); Field != E; ++Field) {
3108 if (Field->isUnnamedBitfield())
3109 continue;
3110
John McCalld6ca8da2010-04-10 07:37:23 +00003111 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003112 }
3113
John McCalld6ca8da2010-04-10 07:37:23 +00003114 unsigned NumIdealInits = IdealInitKeys.size();
3115 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003116
Sean Huntcbb67482011-01-08 20:30:50 +00003117 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003118 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003119 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003120 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003121
3122 // Scan forward to try to find this initializer in the idealized
3123 // initializers list.
3124 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3125 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003126 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003127
3128 // If we didn't find this initializer, it must be because we
3129 // scanned past it on a previous iteration. That can only
3130 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003131 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003132 Sema::SemaDiagnosticBuilder D =
3133 SemaRef.Diag(PrevInit->getSourceLocation(),
3134 diag::warn_initializer_out_of_order);
3135
Francois Pichet00eb3f92010-12-04 09:14:42 +00003136 if (PrevInit->isAnyMemberInitializer())
3137 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003138 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003139 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003140
Francois Pichet00eb3f92010-12-04 09:14:42 +00003141 if (Init->isAnyMemberInitializer())
3142 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003143 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003144 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003145
3146 // Move back to the initializer's location in the ideal list.
3147 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3148 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003149 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003150
3151 assert(IdealIndex != NumIdealInits &&
3152 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003153 }
John McCalld6ca8da2010-04-10 07:37:23 +00003154
3155 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003156 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003157}
3158
John McCall3c3ccdb2010-04-10 09:28:51 +00003159namespace {
3160bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003161 CXXCtorInitializer *Init,
3162 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003163 if (!PrevInit) {
3164 PrevInit = Init;
3165 return false;
3166 }
3167
3168 if (FieldDecl *Field = Init->getMember())
3169 S.Diag(Init->getSourceLocation(),
3170 diag::err_multiple_mem_initialization)
3171 << Field->getDeclName()
3172 << Init->getSourceRange();
3173 else {
John McCallf4c73712011-01-19 06:33:43 +00003174 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003175 assert(BaseClass && "neither field nor base");
3176 S.Diag(Init->getSourceLocation(),
3177 diag::err_multiple_base_initialization)
3178 << QualType(BaseClass, 0)
3179 << Init->getSourceRange();
3180 }
3181 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3182 << 0 << PrevInit->getSourceRange();
3183
3184 return true;
3185}
3186
Sean Huntcbb67482011-01-08 20:30:50 +00003187typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003188typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3189
3190bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003191 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003192 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003193 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003194 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003195 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003196
3197 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003198 if (Parent->isUnion()) {
3199 UnionEntry &En = Unions[Parent];
3200 if (En.first && En.first != Child) {
3201 S.Diag(Init->getSourceLocation(),
3202 diag::err_multiple_mem_union_initialization)
3203 << Field->getDeclName()
3204 << Init->getSourceRange();
3205 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3206 << 0 << En.second->getSourceRange();
3207 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003208 }
3209 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003210 En.first = Child;
3211 En.second = Init;
3212 }
David Blaikie6fe29652011-11-17 06:01:57 +00003213 if (!Parent->isAnonymousStructOrUnion())
3214 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003215 }
3216
3217 Child = Parent;
3218 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003219 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003220
3221 return false;
3222}
3223}
3224
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003225/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003226void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003227 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003228 CXXCtorInitializer **meminits,
3229 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003230 bool AnyErrors) {
3231 if (!ConstructorDecl)
3232 return;
3233
3234 AdjustDeclIfTemplate(ConstructorDecl);
3235
3236 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003237 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003238
3239 if (!Constructor) {
3240 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3241 return;
3242 }
3243
Sean Huntcbb67482011-01-08 20:30:50 +00003244 CXXCtorInitializer **MemInits =
3245 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003246
3247 // Mapping for the duplicate initializers check.
3248 // For member initializers, this is keyed with a FieldDecl*.
3249 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003250 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003251
3252 // Mapping for the inconsistent anonymous-union initializers check.
3253 RedundantUnionMap MemberUnions;
3254
Anders Carlssonea356fb2010-04-02 05:42:15 +00003255 bool HadError = false;
3256 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003257 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003258
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003259 // Set the source order index.
3260 Init->setSourceOrder(i);
3261
Francois Pichet00eb3f92010-12-04 09:14:42 +00003262 if (Init->isAnyMemberInitializer()) {
3263 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003264 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3265 CheckRedundantUnionInit(*this, Init, MemberUnions))
3266 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003267 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003268 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3269 if (CheckRedundantInit(*this, Init, Members[Key]))
3270 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003271 } else {
3272 assert(Init->isDelegatingInitializer());
3273 // This must be the only initializer
3274 if (i != 0 || NumMemInits > 1) {
3275 Diag(MemInits[0]->getSourceLocation(),
3276 diag::err_delegating_initializer_alone)
3277 << MemInits[0]->getSourceRange();
3278 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003279 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003280 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003281 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003282 // Return immediately as the initializer is set.
3283 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003284 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003285 }
3286
Anders Carlssonea356fb2010-04-02 05:42:15 +00003287 if (HadError)
3288 return;
3289
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003290 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003291
Sean Huntcbb67482011-01-08 20:30:50 +00003292 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003293}
3294
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003295void
John McCallef027fe2010-03-16 21:39:52 +00003296Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3297 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003298 // Ignore dependent contexts. Also ignore unions, since their members never
3299 // have destructors implicitly called.
3300 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003301 return;
John McCall58e6f342010-03-16 05:22:47 +00003302
3303 // FIXME: all the access-control diagnostics are positioned on the
3304 // field/base declaration. That's probably good; that said, the
3305 // user might reasonably want to know why the destructor is being
3306 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003307
Anders Carlsson9f853df2009-11-17 04:44:12 +00003308 // Non-static data members.
3309 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3310 E = ClassDecl->field_end(); I != E; ++I) {
3311 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003312 if (Field->isInvalidDecl())
3313 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003314
3315 // Don't destroy incomplete or zero-length arrays.
3316 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3317 continue;
3318
Anders Carlsson9f853df2009-11-17 04:44:12 +00003319 QualType FieldType = Context.getBaseElementType(Field->getType());
3320
3321 const RecordType* RT = FieldType->getAs<RecordType>();
3322 if (!RT)
3323 continue;
3324
3325 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003326 if (FieldClassDecl->isInvalidDecl())
3327 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003328 if (FieldClassDecl->hasTrivialDestructor())
3329 continue;
3330
Douglas Gregordb89f282010-07-01 22:47:18 +00003331 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003332 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003333 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003334 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003335 << Field->getDeclName()
3336 << FieldType);
3337
Eli Friedman5f2987c2012-02-02 03:46:19 +00003338 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003339 }
3340
John McCall58e6f342010-03-16 05:22:47 +00003341 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3342
Anders Carlsson9f853df2009-11-17 04:44:12 +00003343 // Bases.
3344 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3345 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003346 // Bases are always records in a well-formed non-dependent class.
3347 const RecordType *RT = Base->getType()->getAs<RecordType>();
3348
3349 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003350 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003351 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003352
John McCall58e6f342010-03-16 05:22:47 +00003353 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003354 // If our base class is invalid, we probably can't get its dtor anyway.
3355 if (BaseClassDecl->isInvalidDecl())
3356 continue;
3357 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003358 if (BaseClassDecl->hasTrivialDestructor())
3359 continue;
John McCall58e6f342010-03-16 05:22:47 +00003360
Douglas Gregordb89f282010-07-01 22:47:18 +00003361 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003362 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003363
3364 // FIXME: caret should be on the start of the class name
3365 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003366 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003367 << Base->getType()
3368 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003369
Eli Friedman5f2987c2012-02-02 03:46:19 +00003370 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003371 }
3372
3373 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003374 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3375 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003376
3377 // Bases are always records in a well-formed non-dependent class.
3378 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3379
3380 // Ignore direct virtual bases.
3381 if (DirectVirtualBases.count(RT))
3382 continue;
3383
John McCall58e6f342010-03-16 05:22:47 +00003384 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003385 // If our base class is invalid, we probably can't get its dtor anyway.
3386 if (BaseClassDecl->isInvalidDecl())
3387 continue;
3388 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003389 if (BaseClassDecl->hasTrivialDestructor())
3390 continue;
John McCall58e6f342010-03-16 05:22:47 +00003391
Douglas Gregordb89f282010-07-01 22:47:18 +00003392 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003393 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003394 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003395 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003396 << VBase->getType());
3397
Eli Friedman5f2987c2012-02-02 03:46:19 +00003398 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003399 }
3400}
3401
John McCalld226f652010-08-21 09:40:31 +00003402void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003403 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003404 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003405
Mike Stump1eb44332009-09-09 15:08:12 +00003406 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003407 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003408 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003409}
3410
Mike Stump1eb44332009-09-09 15:08:12 +00003411bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003412 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003413 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003414 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003415 else
John McCall94c3b562010-08-18 09:41:07 +00003416 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003417}
3418
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003419bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003420 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003421 if (!getLangOptions().CPlusPlus)
3422 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Anders Carlsson11f21a02009-03-23 19:10:31 +00003424 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003425 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003426
Ted Kremenek6217b802009-07-29 21:53:49 +00003427 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003428 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003429 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003430 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003432 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003433 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003434 }
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Ted Kremenek6217b802009-07-29 21:53:49 +00003436 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003437 if (!RT)
3438 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003439
John McCall86ff3082010-02-04 22:26:26 +00003440 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003441
John McCall94c3b562010-08-18 09:41:07 +00003442 // We can't answer whether something is abstract until it has a
3443 // definition. If it's currently being defined, we'll walk back
3444 // over all the declarations when we have a full definition.
3445 const CXXRecordDecl *Def = RD->getDefinition();
3446 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003447 return false;
3448
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003449 if (!RD->isAbstract())
3450 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003452 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003453 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003454
John McCall94c3b562010-08-18 09:41:07 +00003455 return true;
3456}
3457
3458void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3459 // Check if we've already emitted the list of pure virtual functions
3460 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003461 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003462 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003463
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003464 CXXFinalOverriderMap FinalOverriders;
3465 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003466
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003467 // Keep a set of seen pure methods so we won't diagnose the same method
3468 // more than once.
3469 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3470
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003471 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3472 MEnd = FinalOverriders.end();
3473 M != MEnd;
3474 ++M) {
3475 for (OverridingMethods::iterator SO = M->second.begin(),
3476 SOEnd = M->second.end();
3477 SO != SOEnd; ++SO) {
3478 // C++ [class.abstract]p4:
3479 // A class is abstract if it contains or inherits at least one
3480 // pure virtual function for which the final overrider is pure
3481 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003482
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003483 //
3484 if (SO->second.size() != 1)
3485 continue;
3486
3487 if (!SO->second.front().Method->isPure())
3488 continue;
3489
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003490 if (!SeenPureMethods.insert(SO->second.front().Method))
3491 continue;
3492
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003493 Diag(SO->second.front().Method->getLocation(),
3494 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003495 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003496 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003497 }
3498
3499 if (!PureVirtualClassDiagSet)
3500 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3501 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003502}
3503
Anders Carlsson8211eff2009-03-24 01:19:16 +00003504namespace {
John McCall94c3b562010-08-18 09:41:07 +00003505struct AbstractUsageInfo {
3506 Sema &S;
3507 CXXRecordDecl *Record;
3508 CanQualType AbstractType;
3509 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003510
John McCall94c3b562010-08-18 09:41:07 +00003511 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3512 : S(S), Record(Record),
3513 AbstractType(S.Context.getCanonicalType(
3514 S.Context.getTypeDeclType(Record))),
3515 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003516
John McCall94c3b562010-08-18 09:41:07 +00003517 void DiagnoseAbstractType() {
3518 if (Invalid) return;
3519 S.DiagnoseAbstractType(Record);
3520 Invalid = true;
3521 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003522
John McCall94c3b562010-08-18 09:41:07 +00003523 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3524};
3525
3526struct CheckAbstractUsage {
3527 AbstractUsageInfo &Info;
3528 const NamedDecl *Ctx;
3529
3530 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3531 : Info(Info), Ctx(Ctx) {}
3532
3533 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3534 switch (TL.getTypeLocClass()) {
3535#define ABSTRACT_TYPELOC(CLASS, PARENT)
3536#define TYPELOC(CLASS, PARENT) \
3537 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3538#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003539 }
John McCall94c3b562010-08-18 09:41:07 +00003540 }
Mike Stump1eb44332009-09-09 15:08:12 +00003541
John McCall94c3b562010-08-18 09:41:07 +00003542 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3543 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3544 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003545 if (!TL.getArg(I))
3546 continue;
3547
John McCall94c3b562010-08-18 09:41:07 +00003548 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3549 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003550 }
John McCall94c3b562010-08-18 09:41:07 +00003551 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003552
John McCall94c3b562010-08-18 09:41:07 +00003553 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3554 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3555 }
Mike Stump1eb44332009-09-09 15:08:12 +00003556
John McCall94c3b562010-08-18 09:41:07 +00003557 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3558 // Visit the type parameters from a permissive context.
3559 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3560 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3561 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3562 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3563 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3564 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003565 }
John McCall94c3b562010-08-18 09:41:07 +00003566 }
Mike Stump1eb44332009-09-09 15:08:12 +00003567
John McCall94c3b562010-08-18 09:41:07 +00003568 // Visit pointee types from a permissive context.
3569#define CheckPolymorphic(Type) \
3570 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3571 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3572 }
3573 CheckPolymorphic(PointerTypeLoc)
3574 CheckPolymorphic(ReferenceTypeLoc)
3575 CheckPolymorphic(MemberPointerTypeLoc)
3576 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003577 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003578
John McCall94c3b562010-08-18 09:41:07 +00003579 /// Handle all the types we haven't given a more specific
3580 /// implementation for above.
3581 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3582 // Every other kind of type that we haven't called out already
3583 // that has an inner type is either (1) sugar or (2) contains that
3584 // inner type in some way as a subobject.
3585 if (TypeLoc Next = TL.getNextTypeLoc())
3586 return Visit(Next, Sel);
3587
3588 // If there's no inner type and we're in a permissive context,
3589 // don't diagnose.
3590 if (Sel == Sema::AbstractNone) return;
3591
3592 // Check whether the type matches the abstract type.
3593 QualType T = TL.getType();
3594 if (T->isArrayType()) {
3595 Sel = Sema::AbstractArrayType;
3596 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003597 }
John McCall94c3b562010-08-18 09:41:07 +00003598 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3599 if (CT != Info.AbstractType) return;
3600
3601 // It matched; do some magic.
3602 if (Sel == Sema::AbstractArrayType) {
3603 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3604 << T << TL.getSourceRange();
3605 } else {
3606 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3607 << Sel << T << TL.getSourceRange();
3608 }
3609 Info.DiagnoseAbstractType();
3610 }
3611};
3612
3613void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3614 Sema::AbstractDiagSelID Sel) {
3615 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3616}
3617
3618}
3619
3620/// Check for invalid uses of an abstract type in a method declaration.
3621static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3622 CXXMethodDecl *MD) {
3623 // No need to do the check on definitions, which require that
3624 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003625 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003626 return;
3627
3628 // For safety's sake, just ignore it if we don't have type source
3629 // information. This should never happen for non-implicit methods,
3630 // but...
3631 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3632 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3633}
3634
3635/// Check for invalid uses of an abstract type within a class definition.
3636static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3637 CXXRecordDecl *RD) {
3638 for (CXXRecordDecl::decl_iterator
3639 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3640 Decl *D = *I;
3641 if (D->isImplicit()) continue;
3642
3643 // Methods and method templates.
3644 if (isa<CXXMethodDecl>(D)) {
3645 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3646 } else if (isa<FunctionTemplateDecl>(D)) {
3647 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3648 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3649
3650 // Fields and static variables.
3651 } else if (isa<FieldDecl>(D)) {
3652 FieldDecl *FD = cast<FieldDecl>(D);
3653 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3654 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3655 } else if (isa<VarDecl>(D)) {
3656 VarDecl *VD = cast<VarDecl>(D);
3657 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3658 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3659
3660 // Nested classes and class templates.
3661 } else if (isa<CXXRecordDecl>(D)) {
3662 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3663 } else if (isa<ClassTemplateDecl>(D)) {
3664 CheckAbstractClassUsage(Info,
3665 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3666 }
3667 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003668}
3669
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003670/// \brief Perform semantic checks on a class definition that has been
3671/// completing, introducing implicitly-declared members, checking for
3672/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003673void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003674 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003675 return;
3676
John McCall94c3b562010-08-18 09:41:07 +00003677 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3678 AbstractUsageInfo Info(*this, Record);
3679 CheckAbstractClassUsage(Info, Record);
3680 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003681
3682 // If this is not an aggregate type and has no user-declared constructor,
3683 // complain about any non-static data members of reference or const scalar
3684 // type, since they will never get initializers.
3685 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003686 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3687 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003688 bool Complained = false;
3689 for (RecordDecl::field_iterator F = Record->field_begin(),
3690 FEnd = Record->field_end();
3691 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003692 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003693 continue;
3694
Douglas Gregor325e5932010-04-15 00:00:53 +00003695 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003696 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003697 if (!Complained) {
3698 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3699 << Record->getTagKind() << Record;
3700 Complained = true;
3701 }
3702
3703 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3704 << F->getType()->isReferenceType()
3705 << F->getDeclName();
3706 }
3707 }
3708 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003709
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003710 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003711 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003712
3713 if (Record->getIdentifier()) {
3714 // C++ [class.mem]p13:
3715 // If T is the name of a class, then each of the following shall have a
3716 // name different from T:
3717 // - every member of every anonymous union that is a member of class T.
3718 //
3719 // C++ [class.mem]p14:
3720 // In addition, if class T has a user-declared constructor (12.1), every
3721 // non-static data member of class T shall have a name different from T.
3722 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003723 R.first != R.second; ++R.first) {
3724 NamedDecl *D = *R.first;
3725 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3726 isa<IndirectFieldDecl>(D)) {
3727 Diag(D->getLocation(), diag::err_member_name_of_class)
3728 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003729 break;
3730 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003731 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003732 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003733
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003734 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003735 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003736 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003737 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003738 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3739 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3740 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003741
3742 // See if a method overloads virtual methods in a base
3743 /// class without overriding any.
3744 if (!Record->isDependentType()) {
3745 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3746 MEnd = Record->method_end();
3747 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003748 if (!(*M)->isStatic())
3749 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003750 }
3751 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003752
Richard Smith9f569cc2011-10-01 02:31:28 +00003753 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3754 // function that is not a constructor declares that member function to be
3755 // const. [...] The class of which that function is a member shall be
3756 // a literal type.
3757 //
3758 // It's fine to diagnose constructors here too: such constructors cannot
3759 // produce a constant expression, so are ill-formed (no diagnostic required).
3760 //
3761 // If the class has virtual bases, any constexpr members will already have
3762 // been diagnosed by the checks performed on the member declaration, so
3763 // suppress this (less useful) diagnostic.
3764 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3765 !Record->isLiteral() && !Record->getNumVBases()) {
3766 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3767 MEnd = Record->method_end();
3768 M != MEnd; ++M) {
Eli Friedman9ec0ef32012-01-13 02:31:53 +00003769 if (M->isConstexpr() && M->isInstance()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003770 switch (Record->getTemplateSpecializationKind()) {
3771 case TSK_ImplicitInstantiation:
3772 case TSK_ExplicitInstantiationDeclaration:
3773 case TSK_ExplicitInstantiationDefinition:
3774 // If a template instantiates to a non-literal type, but its members
3775 // instantiate to constexpr functions, the template is technically
3776 // ill-formed, but we allow it for sanity. Such members are treated as
3777 // non-constexpr.
3778 (*M)->setConstexpr(false);
3779 continue;
3780
3781 case TSK_Undeclared:
3782 case TSK_ExplicitSpecialization:
3783 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3784 PDiag(diag::err_constexpr_method_non_literal));
3785 break;
3786 }
3787
3788 // Only produce one error per class.
3789 break;
3790 }
3791 }
3792 }
3793
Sebastian Redlf677ea32011-02-05 19:23:19 +00003794 // Declare inherited constructors. We do this eagerly here because:
3795 // - The standard requires an eager diagnostic for conflicting inherited
3796 // constructors from different classes.
3797 // - The lazy declaration of the other implicit constructors is so as to not
3798 // waste space and performance on classes that are not meant to be
3799 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3800 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003801 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003802
Sean Hunteb88ae52011-05-23 21:07:59 +00003803 if (!Record->isDependentType())
3804 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003805}
3806
3807void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003808 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3809 ME = Record->method_end();
3810 MI != ME; ++MI) {
3811 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3812 switch (getSpecialMember(*MI)) {
3813 case CXXDefaultConstructor:
3814 CheckExplicitlyDefaultedDefaultConstructor(
3815 cast<CXXConstructorDecl>(*MI));
3816 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003817
Sean Huntcb45a0f2011-05-12 22:46:25 +00003818 case CXXDestructor:
3819 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3820 break;
3821
3822 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003823 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3824 break;
3825
Sean Huntcb45a0f2011-05-12 22:46:25 +00003826 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003827 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003828 break;
3829
Sean Hunt82713172011-05-25 23:16:36 +00003830 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003831 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003832 break;
3833
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003834 case CXXMoveAssignment:
3835 CheckExplicitlyDefaultedMoveAssignment(*MI);
3836 break;
3837
3838 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003839 llvm_unreachable("non-special member explicitly defaulted!");
3840 }
Sean Hunt001cad92011-05-10 00:49:42 +00003841 }
3842 }
3843
Sean Hunt001cad92011-05-10 00:49:42 +00003844}
3845
3846void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3847 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3848
3849 // Whether this was the first-declared instance of the constructor.
3850 // This affects whether we implicitly add an exception spec (and, eventually,
3851 // constexpr). It is also ill-formed to explicitly default a constructor such
3852 // that it would be deleted. (C++0x [decl.fct.def.default])
3853 bool First = CD == CD->getCanonicalDecl();
3854
Sean Hunt49634cf2011-05-13 06:10:58 +00003855 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003856 if (CD->getNumParams() != 0) {
3857 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3858 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003859 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003860 }
3861
3862 ImplicitExceptionSpecification Spec
3863 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3864 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003865 if (EPI.ExceptionSpecType == EST_Delayed) {
3866 // Exception specification depends on some deferred part of the class. We'll
3867 // try again when the class's definition has been fully processed.
3868 return;
3869 }
Sean Hunt001cad92011-05-10 00:49:42 +00003870 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3871 *ExceptionType = Context.getFunctionType(
3872 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3873
Richard Smith61802452011-12-22 02:22:31 +00003874 // C++11 [dcl.fct.def.default]p2:
3875 // An explicitly-defaulted function may be declared constexpr only if it
3876 // would have been implicitly declared as constexpr,
3877 if (CD->isConstexpr()) {
3878 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3879 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3880 << CXXDefaultConstructor;
3881 HadError = true;
3882 }
3883 }
3884 // and may have an explicit exception-specification only if it is compatible
3885 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003886 if (CtorType->hasExceptionSpec()) {
3887 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003888 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003889 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003890 PDiag(),
3891 ExceptionType, SourceLocation(),
3892 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003893 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003894 }
Richard Smith61802452011-12-22 02:22:31 +00003895 }
3896
3897 // If a function is explicitly defaulted on its first declaration,
3898 if (First) {
3899 // -- it is implicitly considered to be constexpr if the implicit
3900 // definition would be,
3901 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3902
3903 // -- it is implicitly considered to have the same
3904 // exception-specification as if it had been implicitly declared
3905 //
3906 // FIXME: a compatible, but different, explicit exception specification
3907 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003908 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003909 }
Sean Huntca46d132011-05-12 03:51:48 +00003910
Sean Hunt49634cf2011-05-13 06:10:58 +00003911 if (HadError) {
3912 CD->setInvalidDecl();
3913 return;
3914 }
3915
Sean Hunte16da072011-10-10 06:18:57 +00003916 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003917 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003918 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003919 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003920 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003921 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003922 CD->setInvalidDecl();
3923 }
3924 }
3925}
3926
3927void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3928 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3929
3930 // Whether this was the first-declared instance of the constructor.
3931 bool First = CD == CD->getCanonicalDecl();
3932
3933 bool HadError = false;
3934 if (CD->getNumParams() != 1) {
3935 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3936 << CD->getSourceRange();
3937 HadError = true;
3938 }
3939
3940 ImplicitExceptionSpecification Spec(Context);
3941 bool Const;
3942 llvm::tie(Spec, Const) =
3943 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3944
3945 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3946 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3947 *ExceptionType = Context.getFunctionType(
3948 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3949
3950 // Check for parameter type matching.
3951 // This is a copy ctor so we know it's a cv-qualified reference to T.
3952 QualType ArgType = CtorType->getArgType(0);
3953 if (ArgType->getPointeeType().isVolatileQualified()) {
3954 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3955 HadError = true;
3956 }
3957 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3958 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3959 HadError = true;
3960 }
3961
Richard Smith61802452011-12-22 02:22:31 +00003962 // C++11 [dcl.fct.def.default]p2:
3963 // An explicitly-defaulted function may be declared constexpr only if it
3964 // would have been implicitly declared as constexpr,
3965 if (CD->isConstexpr()) {
3966 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3967 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3968 << CXXCopyConstructor;
3969 HadError = true;
3970 }
3971 }
3972 // and may have an explicit exception-specification only if it is compatible
3973 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003974 if (CtorType->hasExceptionSpec()) {
3975 if (CheckEquivalentExceptionSpec(
3976 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003977 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003978 PDiag(),
3979 ExceptionType, SourceLocation(),
3980 CtorType, CD->getLocation())) {
3981 HadError = true;
3982 }
Richard Smith61802452011-12-22 02:22:31 +00003983 }
3984
3985 // If a function is explicitly defaulted on its first declaration,
3986 if (First) {
3987 // -- it is implicitly considered to be constexpr if the implicit
3988 // definition would be,
3989 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3990
3991 // -- it is implicitly considered to have the same
3992 // exception-specification as if it had been implicitly declared, and
3993 //
3994 // FIXME: a compatible, but different, explicit exception specification
3995 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003996 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003997
3998 // -- [...] it shall have the same parameter type as if it had been
3999 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00004000 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4001 }
4002
4003 if (HadError) {
4004 CD->setInvalidDecl();
4005 return;
4006 }
4007
Sean Huntc32d6842011-10-11 04:55:36 +00004008 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004009 if (First) {
4010 CD->setDeletedAsWritten();
4011 } else {
4012 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004013 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004014 CD->setInvalidDecl();
4015 }
Sean Huntca46d132011-05-12 03:51:48 +00004016 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004017}
Sean Hunt001cad92011-05-10 00:49:42 +00004018
Sean Hunt2b188082011-05-14 05:23:28 +00004019void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
4020 assert(MD->isExplicitlyDefaulted());
4021
4022 // Whether this was the first-declared instance of the operator
4023 bool First = MD == MD->getCanonicalDecl();
4024
4025 bool HadError = false;
4026 if (MD->getNumParams() != 1) {
4027 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
4028 << MD->getSourceRange();
4029 HadError = true;
4030 }
4031
4032 QualType ReturnType =
4033 MD->getType()->getAs<FunctionType>()->getResultType();
4034 if (!ReturnType->isLValueReferenceType() ||
4035 !Context.hasSameType(
4036 Context.getCanonicalType(ReturnType->getPointeeType()),
4037 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4038 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
4039 HadError = true;
4040 }
4041
4042 ImplicitExceptionSpecification Spec(Context);
4043 bool Const;
4044 llvm::tie(Spec, Const) =
4045 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4046
4047 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4048 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4049 *ExceptionType = Context.getFunctionType(
4050 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4051
Sean Hunt2b188082011-05-14 05:23:28 +00004052 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004053 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00004054 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004055 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00004056 } else {
4057 if (ArgType->getPointeeType().isVolatileQualified()) {
4058 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4059 HadError = true;
4060 }
4061 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4062 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4063 HadError = true;
4064 }
Sean Hunt2b188082011-05-14 05:23:28 +00004065 }
Sean Huntbe631222011-05-17 20:44:43 +00004066
Sean Hunt2b188082011-05-14 05:23:28 +00004067 if (OperType->getTypeQuals()) {
4068 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4069 HadError = true;
4070 }
4071
4072 if (OperType->hasExceptionSpec()) {
4073 if (CheckEquivalentExceptionSpec(
4074 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004075 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004076 PDiag(),
4077 ExceptionType, SourceLocation(),
4078 OperType, MD->getLocation())) {
4079 HadError = true;
4080 }
Richard Smith61802452011-12-22 02:22:31 +00004081 }
4082 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004083 // We set the declaration to have the computed exception spec here.
4084 // We duplicate the one parameter type.
4085 EPI.RefQualifier = OperType->getRefQualifier();
4086 EPI.ExtInfo = OperType->getExtInfo();
4087 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4088 }
4089
4090 if (HadError) {
4091 MD->setInvalidDecl();
4092 return;
4093 }
4094
4095 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4096 if (First) {
4097 MD->setDeletedAsWritten();
4098 } else {
4099 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004100 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004101 MD->setInvalidDecl();
4102 }
4103 }
4104}
4105
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004106void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4107 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4108
4109 // Whether this was the first-declared instance of the constructor.
4110 bool First = CD == CD->getCanonicalDecl();
4111
4112 bool HadError = false;
4113 if (CD->getNumParams() != 1) {
4114 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4115 << CD->getSourceRange();
4116 HadError = true;
4117 }
4118
4119 ImplicitExceptionSpecification Spec(
4120 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4121
4122 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4123 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4124 *ExceptionType = Context.getFunctionType(
4125 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4126
4127 // Check for parameter type matching.
4128 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4129 QualType ArgType = CtorType->getArgType(0);
4130 if (ArgType->getPointeeType().isVolatileQualified()) {
4131 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4132 HadError = true;
4133 }
4134 if (ArgType->getPointeeType().isConstQualified()) {
4135 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4136 HadError = true;
4137 }
4138
Richard Smith61802452011-12-22 02:22:31 +00004139 // C++11 [dcl.fct.def.default]p2:
4140 // An explicitly-defaulted function may be declared constexpr only if it
4141 // would have been implicitly declared as constexpr,
4142 if (CD->isConstexpr()) {
4143 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4144 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4145 << CXXMoveConstructor;
4146 HadError = true;
4147 }
4148 }
4149 // and may have an explicit exception-specification only if it is compatible
4150 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004151 if (CtorType->hasExceptionSpec()) {
4152 if (CheckEquivalentExceptionSpec(
4153 PDiag(diag::err_incorrect_defaulted_exception_spec)
4154 << CXXMoveConstructor,
4155 PDiag(),
4156 ExceptionType, SourceLocation(),
4157 CtorType, CD->getLocation())) {
4158 HadError = true;
4159 }
Richard Smith61802452011-12-22 02:22:31 +00004160 }
4161
4162 // If a function is explicitly defaulted on its first declaration,
4163 if (First) {
4164 // -- it is implicitly considered to be constexpr if the implicit
4165 // definition would be,
4166 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4167
4168 // -- it is implicitly considered to have the same
4169 // exception-specification as if it had been implicitly declared, and
4170 //
4171 // FIXME: a compatible, but different, explicit exception specification
4172 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004173 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004174
4175 // -- [...] it shall have the same parameter type as if it had been
4176 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004177 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4178 }
4179
4180 if (HadError) {
4181 CD->setInvalidDecl();
4182 return;
4183 }
4184
Sean Hunt769bb2d2011-10-11 06:43:29 +00004185 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004186 if (First) {
4187 CD->setDeletedAsWritten();
4188 } else {
4189 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4190 << CXXMoveConstructor;
4191 CD->setInvalidDecl();
4192 }
4193 }
4194}
4195
4196void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4197 assert(MD->isExplicitlyDefaulted());
4198
4199 // Whether this was the first-declared instance of the operator
4200 bool First = MD == MD->getCanonicalDecl();
4201
4202 bool HadError = false;
4203 if (MD->getNumParams() != 1) {
4204 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4205 << MD->getSourceRange();
4206 HadError = true;
4207 }
4208
4209 QualType ReturnType =
4210 MD->getType()->getAs<FunctionType>()->getResultType();
4211 if (!ReturnType->isLValueReferenceType() ||
4212 !Context.hasSameType(
4213 Context.getCanonicalType(ReturnType->getPointeeType()),
4214 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4215 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4216 HadError = true;
4217 }
4218
4219 ImplicitExceptionSpecification Spec(
4220 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4221
4222 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4223 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4224 *ExceptionType = Context.getFunctionType(
4225 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4226
4227 QualType ArgType = OperType->getArgType(0);
4228 if (!ArgType->isRValueReferenceType()) {
4229 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4230 HadError = true;
4231 } else {
4232 if (ArgType->getPointeeType().isVolatileQualified()) {
4233 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4234 HadError = true;
4235 }
4236 if (ArgType->getPointeeType().isConstQualified()) {
4237 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4238 HadError = true;
4239 }
4240 }
4241
4242 if (OperType->getTypeQuals()) {
4243 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4244 HadError = true;
4245 }
4246
4247 if (OperType->hasExceptionSpec()) {
4248 if (CheckEquivalentExceptionSpec(
4249 PDiag(diag::err_incorrect_defaulted_exception_spec)
4250 << CXXMoveAssignment,
4251 PDiag(),
4252 ExceptionType, SourceLocation(),
4253 OperType, MD->getLocation())) {
4254 HadError = true;
4255 }
Richard Smith61802452011-12-22 02:22:31 +00004256 }
4257 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004258 // We set the declaration to have the computed exception spec here.
4259 // We duplicate the one parameter type.
4260 EPI.RefQualifier = OperType->getRefQualifier();
4261 EPI.ExtInfo = OperType->getExtInfo();
4262 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4263 }
4264
4265 if (HadError) {
4266 MD->setInvalidDecl();
4267 return;
4268 }
4269
4270 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4271 if (First) {
4272 MD->setDeletedAsWritten();
4273 } else {
4274 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4275 << CXXMoveAssignment;
4276 MD->setInvalidDecl();
4277 }
4278 }
4279}
4280
Sean Huntcb45a0f2011-05-12 22:46:25 +00004281void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4282 assert(DD->isExplicitlyDefaulted());
4283
4284 // Whether this was the first-declared instance of the destructor.
4285 bool First = DD == DD->getCanonicalDecl();
4286
4287 ImplicitExceptionSpecification Spec
4288 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4289 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4290 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4291 *ExceptionType = Context.getFunctionType(
4292 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4293
4294 if (DtorType->hasExceptionSpec()) {
4295 if (CheckEquivalentExceptionSpec(
4296 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004297 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004298 PDiag(),
4299 ExceptionType, SourceLocation(),
4300 DtorType, DD->getLocation())) {
4301 DD->setInvalidDecl();
4302 return;
4303 }
Richard Smith61802452011-12-22 02:22:31 +00004304 }
4305 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004306 // We set the declaration to have the computed exception spec here.
4307 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004308 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004309 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4310 }
4311
4312 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004313 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004314 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004315 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004316 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004317 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004318 DD->setInvalidDecl();
4319 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004320 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004321}
4322
Sean Hunte16da072011-10-10 06:18:57 +00004323/// This function implements the following C++0x paragraphs:
4324/// - [class.ctor]/5
Sean Huntc32d6842011-10-11 04:55:36 +00004325/// - [class.copy]/11
Sean Hunte16da072011-10-10 06:18:57 +00004326bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4327 assert(!MD->isInvalidDecl());
4328 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004329 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004330 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004331 return false;
4332
Sean Hunte16da072011-10-10 06:18:57 +00004333 bool IsUnion = RD->isUnion();
4334 bool IsConstructor = false;
4335 bool IsAssignment = false;
4336 bool IsMove = false;
4337
4338 bool ConstArg = false;
4339
4340 switch (CSM) {
4341 case CXXDefaultConstructor:
4342 IsConstructor = true;
4343 break;
Sean Huntc32d6842011-10-11 04:55:36 +00004344 case CXXCopyConstructor:
4345 IsConstructor = true;
4346 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4347 break;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004348 case CXXMoveConstructor:
4349 IsConstructor = true;
4350 IsMove = true;
4351 break;
Sean Hunte16da072011-10-10 06:18:57 +00004352 default:
4353 llvm_unreachable("function only currently implemented for default ctors");
4354 }
4355
4356 SourceLocation Loc = MD->getLocation();
Sean Hunt71a682f2011-05-18 03:41:58 +00004357
Sean Huntc32d6842011-10-11 04:55:36 +00004358 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004359 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004360
Sean Huntcdee3fe2011-05-11 22:34:38 +00004361 bool AllConst = true;
4362
Sean Huntcdee3fe2011-05-11 22:34:38 +00004363 // We do this because we should never actually use an anonymous
4364 // union's constructor.
Sean Hunte16da072011-10-10 06:18:57 +00004365 if (IsUnion && RD->isAnonymousStructOrUnion())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004366 return false;
4367
4368 // FIXME: We should put some diagnostic logic right into this function.
4369
Sean Huntcdee3fe2011-05-11 22:34:38 +00004370 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4371 BE = RD->bases_end();
4372 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004373 // We'll handle this one later
4374 if (BI->isVirtual())
4375 continue;
4376
Sean Huntcdee3fe2011-05-11 22:34:38 +00004377 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4378 assert(BaseDecl && "base isn't a CXXRecordDecl");
4379
Sean Hunte16da072011-10-10 06:18:57 +00004380 // Unless we have an assignment operator, the base's destructor must
4381 // be accessible and not deleted.
4382 if (!IsAssignment) {
4383 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4384 if (BaseDtor->isDeleted())
4385 return true;
4386 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4387 AR_accessible)
4388 return true;
4389 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004390
Sean Hunte16da072011-10-10 06:18:57 +00004391 // Finding the corresponding member in the base should lead to a
Sean Huntc32d6842011-10-11 04:55:36 +00004392 // unique, accessible, non-deleted function. If we are doing
4393 // a destructor, we have already checked this case.
Sean Hunte16da072011-10-10 06:18:57 +00004394 if (CSM != CXXDestructor) {
4395 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004396 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004397 false);
4398 if (!SMOR->hasSuccess())
4399 return true;
4400 CXXMethodDecl *BaseMember = SMOR->getMethod();
4401 if (IsConstructor) {
4402 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4403 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4404 PDiag()) != AR_accessible)
4405 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004406
4407 // For a move operation, the corresponding operation must actually
4408 // be a move operation (and not a copy selected by overload
4409 // resolution) unless we are working on a trivially copyable class.
4410 if (IsMove && !BaseCtor->isMoveConstructor() &&
4411 !BaseDecl->isTriviallyCopyable())
4412 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004413 }
4414 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004415 }
4416
4417 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4418 BE = RD->vbases_end();
4419 BI != BE; ++BI) {
4420 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4421 assert(BaseDecl && "base isn't a CXXRecordDecl");
4422
Sean Hunte16da072011-10-10 06:18:57 +00004423 // Unless we have an assignment operator, the base's destructor must
4424 // be accessible and not deleted.
4425 if (!IsAssignment) {
4426 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4427 if (BaseDtor->isDeleted())
4428 return true;
4429 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4430 AR_accessible)
4431 return true;
4432 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004433
Sean Hunte16da072011-10-10 06:18:57 +00004434 // Finding the corresponding member in the base should lead to a
4435 // unique, accessible, non-deleted function.
4436 if (CSM != CXXDestructor) {
4437 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004438 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004439 false);
4440 if (!SMOR->hasSuccess())
4441 return true;
4442 CXXMethodDecl *BaseMember = SMOR->getMethod();
4443 if (IsConstructor) {
4444 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4445 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4446 PDiag()) != AR_accessible)
4447 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004448
4449 // For a move operation, the corresponding operation must actually
4450 // be a move operation (and not a copy selected by overload
4451 // resolution) unless we are working on a trivially copyable class.
4452 if (IsMove && !BaseCtor->isMoveConstructor() &&
4453 !BaseDecl->isTriviallyCopyable())
4454 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004455 }
4456 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004457 }
4458
4459 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4460 FE = RD->field_end();
4461 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004462 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004463 continue;
4464
Sean Huntcdee3fe2011-05-11 22:34:38 +00004465 QualType FieldType = Context.getBaseElementType(FI->getType());
4466 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00004467
Sean Hunte16da072011-10-10 06:18:57 +00004468 // For a default constructor, all references must be initialized in-class
4469 // and, if a union, it must have a non-const member.
4470 if (CSM == CXXDefaultConstructor) {
4471 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4472 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004473
Sean Hunte16da072011-10-10 06:18:57 +00004474 if (IsUnion && !FieldType.isConstQualified())
4475 AllConst = false;
Sean Huntc32d6842011-10-11 04:55:36 +00004476 // For a copy constructor, data members must not be of rvalue reference
4477 // type.
4478 } else if (CSM == CXXCopyConstructor) {
4479 if (FieldType->isRValueReferenceType())
4480 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004481 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004482
4483 if (FieldRecord) {
Sean Hunte16da072011-10-10 06:18:57 +00004484 // For a default constructor, a const member must have a user-provided
4485 // default constructor or else be explicitly initialized.
4486 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00004487 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004488 !FieldRecord->hasUserProvidedDefaultConstructor())
4489 return true;
4490
Sean Huntc32d6842011-10-11 04:55:36 +00004491 // Some additional restrictions exist on the variant members.
4492 if (!IsUnion && FieldRecord->isUnion() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004493 FieldRecord->isAnonymousStructOrUnion()) {
4494 // We're okay to reuse AllConst here since we only care about the
4495 // value otherwise if we're in a union.
4496 AllConst = true;
4497
4498 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4499 UE = FieldRecord->field_end();
4500 UI != UE; ++UI) {
4501 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4502 CXXRecordDecl *UnionFieldRecord =
4503 UnionFieldType->getAsCXXRecordDecl();
4504
4505 if (!UnionFieldType.isConstQualified())
4506 AllConst = false;
4507
Sean Huntc32d6842011-10-11 04:55:36 +00004508 if (UnionFieldRecord) {
4509 // FIXME: Checking for accessibility and validity of this
4510 // destructor is technically going beyond the
4511 // standard, but this is believed to be a defect.
4512 if (!IsAssignment) {
4513 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4514 if (FieldDtor->isDeleted())
4515 return true;
4516 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4517 AR_accessible)
4518 return true;
4519 if (!FieldDtor->isTrivial())
4520 return true;
4521 }
4522
4523 if (CSM != CXXDestructor) {
4524 SpecialMemberOverloadResult *SMOR =
4525 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Sean Hunt769bb2d2011-10-11 06:43:29 +00004526 false, false, false);
Sean Huntc32d6842011-10-11 04:55:36 +00004527 // FIXME: Checking for accessibility and validity of this
4528 // corresponding member is technically going beyond the
4529 // standard, but this is believed to be a defect.
4530 if (!SMOR->hasSuccess())
4531 return true;
4532
4533 CXXMethodDecl *FieldMember = SMOR->getMethod();
4534 // A member of a union must have a trivial corresponding
4535 // constructor.
4536 if (!FieldMember->isTrivial())
4537 return true;
4538
4539 if (IsConstructor) {
4540 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4541 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4542 PDiag()) != AR_accessible)
4543 return true;
4544 }
4545 }
4546 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004547 }
Sean Hunt2be7e902011-05-12 22:46:29 +00004548
Sean Huntc32d6842011-10-11 04:55:36 +00004549 // At least one member in each anonymous union must be non-const
4550 if (CSM == CXXDefaultConstructor && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004551 return true;
4552
4553 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00004554 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00004555 continue;
4556 }
Sean Huntb320e0c2011-06-10 03:50:41 +00004557
Sean Huntc32d6842011-10-11 04:55:36 +00004558 // Unless we're doing assignment, the field's destructor must be
4559 // accessible and not deleted.
4560 if (!IsAssignment) {
4561 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4562 if (FieldDtor->isDeleted())
4563 return true;
4564 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4565 AR_accessible)
4566 return true;
4567 }
4568
Sean Hunte16da072011-10-10 06:18:57 +00004569 // Check that the corresponding member of the field is accessible,
4570 // unique, and non-deleted. We don't do this if it has an explicit
4571 // initialization when default-constructing.
4572 if (CSM != CXXDestructor &&
4573 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4574 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004575 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004576 false);
4577 if (!SMOR->hasSuccess())
Richard Smith7a614d82011-06-11 17:19:42 +00004578 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004579
4580 CXXMethodDecl *FieldMember = SMOR->getMethod();
4581 if (IsConstructor) {
4582 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4583 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4584 PDiag()) != AR_accessible)
4585 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004586
4587 // For a move operation, the corresponding operation must actually
4588 // be a move operation (and not a copy selected by overload
4589 // resolution) unless we are working on a trivially copyable class.
4590 if (IsMove && !FieldCtor->isMoveConstructor() &&
4591 !FieldRecord->isTriviallyCopyable())
4592 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004593 }
4594
4595 // We need the corresponding member of a union to be trivial so that
4596 // we can safely copy them all simultaneously.
4597 // FIXME: Note that performing the check here (where we rely on the lack
4598 // of an in-class initializer) is technically ill-formed. However, this
4599 // seems most obviously to be a bug in the standard.
4600 if (IsUnion && !FieldMember->isTrivial())
Richard Smith7a614d82011-06-11 17:19:42 +00004601 return true;
4602 }
Sean Hunte16da072011-10-10 06:18:57 +00004603 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4604 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4605 // We can't initialize a const member of non-class type to any value.
Sean Hunte3406822011-05-20 21:43:47 +00004606 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004607 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004608 }
4609
Sean Hunte16da072011-10-10 06:18:57 +00004610 // We can't have all const members in a union when default-constructing,
4611 // or else they're all nonsensical garbage values that can't be changed.
4612 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004613 return true;
4614
4615 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004616}
4617
Sean Hunt7f410192011-05-14 05:23:24 +00004618bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4619 CXXRecordDecl *RD = MD->getParent();
4620 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004621 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004622 return false;
4623
Sean Hunt71a682f2011-05-18 03:41:58 +00004624 SourceLocation Loc = MD->getLocation();
4625
Sean Hunt7f410192011-05-14 05:23:24 +00004626 // Do access control from the constructor
4627 ContextRAII MethodContext(*this, MD);
4628
4629 bool Union = RD->isUnion();
4630
Sean Hunt661c67a2011-06-21 23:42:56 +00004631 unsigned ArgQuals =
4632 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4633 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004634
4635 // We do this because we should never actually use an anonymous
4636 // union's constructor.
4637 if (Union && RD->isAnonymousStructOrUnion())
4638 return false;
4639
Sean Hunt7f410192011-05-14 05:23:24 +00004640 // FIXME: We should put some diagnostic logic right into this function.
4641
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004642 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004643 // A defaulted [copy] assignment operator for class X is defined as deleted
4644 // if X has:
4645
4646 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4647 BE = RD->bases_end();
4648 BI != BE; ++BI) {
4649 // We'll handle this one later
4650 if (BI->isVirtual())
4651 continue;
4652
4653 QualType BaseType = BI->getType();
4654 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4655 assert(BaseDecl && "base isn't a CXXRecordDecl");
4656
4657 // -- a [direct base class] B that cannot be [copied] because overload
4658 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004659 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004660 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004661 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4662 0);
4663 if (!CopyOper || CopyOper->isDeleted())
4664 return true;
4665 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004666 return true;
4667 }
4668
4669 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4670 BE = RD->vbases_end();
4671 BI != BE; ++BI) {
4672 QualType BaseType = BI->getType();
4673 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4674 assert(BaseDecl && "base isn't a CXXRecordDecl");
4675
Sean Hunt7f410192011-05-14 05:23:24 +00004676 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004677 // resolution, as applied to B's [copy] assignment operator, results in
4678 // an ambiguity or a function that is deleted or inaccessible from the
4679 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004680 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4681 0);
4682 if (!CopyOper || CopyOper->isDeleted())
4683 return true;
4684 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004685 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004686 }
4687
4688 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4689 FE = RD->field_end();
4690 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004691 if (FI->isUnnamedBitfield())
4692 continue;
4693
Sean Hunt7f410192011-05-14 05:23:24 +00004694 QualType FieldType = Context.getBaseElementType(FI->getType());
4695
4696 // -- a non-static data member of reference type
4697 if (FieldType->isReferenceType())
4698 return true;
4699
4700 // -- a non-static data member of const non-class type (or array thereof)
4701 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4702 return true;
4703
4704 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4705
4706 if (FieldRecord) {
4707 // This is an anonymous union
4708 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4709 // Anonymous unions inside unions do not variant members create
4710 if (!Union) {
4711 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4712 UE = FieldRecord->field_end();
4713 UI != UE; ++UI) {
4714 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4715 CXXRecordDecl *UnionFieldRecord =
4716 UnionFieldType->getAsCXXRecordDecl();
4717
4718 // -- a variant member with a non-trivial [copy] assignment operator
4719 // and X is a union-like class
4720 if (UnionFieldRecord &&
4721 !UnionFieldRecord->hasTrivialCopyAssignment())
4722 return true;
4723 }
4724 }
4725
4726 // Don't try to initalize an anonymous union
4727 continue;
4728 // -- a variant member with a non-trivial [copy] assignment operator
4729 // and X is a union-like class
4730 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4731 return true;
4732 }
Sean Hunt7f410192011-05-14 05:23:24 +00004733
Sean Hunt661c67a2011-06-21 23:42:56 +00004734 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4735 false, 0);
4736 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004737 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004738 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004739 return true;
4740 }
4741 }
4742
4743 return false;
4744}
4745
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004746bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4747 CXXRecordDecl *RD = MD->getParent();
4748 assert(!RD->isDependentType() && "do deletion after instantiation");
4749 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4750 return false;
4751
4752 SourceLocation Loc = MD->getLocation();
4753
4754 // Do access control from the constructor
4755 ContextRAII MethodContext(*this, MD);
4756
4757 bool Union = RD->isUnion();
4758
4759 // We do this because we should never actually use an anonymous
4760 // union's constructor.
4761 if (Union && RD->isAnonymousStructOrUnion())
4762 return false;
4763
4764 // C++0x [class.copy]/20
4765 // A defaulted [move] assignment operator for class X is defined as deleted
4766 // if X has:
4767
4768 // -- for the move constructor, [...] any direct or indirect virtual base
4769 // class.
4770 if (RD->getNumVBases() != 0)
4771 return true;
4772
4773 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4774 BE = RD->bases_end();
4775 BI != BE; ++BI) {
4776
4777 QualType BaseType = BI->getType();
4778 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4779 assert(BaseDecl && "base isn't a CXXRecordDecl");
4780
4781 // -- a [direct base class] B that cannot be [moved] because overload
4782 // resolution, as applied to B's [move] assignment operator, results in
4783 // an ambiguity or a function that is deleted or inaccessible from the
4784 // assignment operator
4785 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4786 if (!MoveOper || MoveOper->isDeleted())
4787 return true;
4788 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4789 return true;
4790
4791 // -- for the move assignment operator, a [direct base class] with a type
4792 // that does not have a move assignment operator and is not trivially
4793 // copyable.
4794 if (!MoveOper->isMoveAssignmentOperator() &&
4795 !BaseDecl->isTriviallyCopyable())
4796 return true;
4797 }
4798
4799 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4800 FE = RD->field_end();
4801 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004802 if (FI->isUnnamedBitfield())
4803 continue;
4804
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004805 QualType FieldType = Context.getBaseElementType(FI->getType());
4806
4807 // -- a non-static data member of reference type
4808 if (FieldType->isReferenceType())
4809 return true;
4810
4811 // -- a non-static data member of const non-class type (or array thereof)
4812 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4813 return true;
4814
4815 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4816
4817 if (FieldRecord) {
4818 // This is an anonymous union
4819 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4820 // Anonymous unions inside unions do not variant members create
4821 if (!Union) {
4822 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4823 UE = FieldRecord->field_end();
4824 UI != UE; ++UI) {
4825 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4826 CXXRecordDecl *UnionFieldRecord =
4827 UnionFieldType->getAsCXXRecordDecl();
4828
4829 // -- a variant member with a non-trivial [move] assignment operator
4830 // and X is a union-like class
4831 if (UnionFieldRecord &&
4832 !UnionFieldRecord->hasTrivialMoveAssignment())
4833 return true;
4834 }
4835 }
4836
4837 // Don't try to initalize an anonymous union
4838 continue;
4839 // -- a variant member with a non-trivial [move] assignment operator
4840 // and X is a union-like class
4841 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4842 return true;
4843 }
4844
4845 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4846 if (!MoveOper || MoveOper->isDeleted())
4847 return true;
4848 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4849 return true;
4850
4851 // -- for the move assignment operator, a [non-static data member] with a
4852 // type that does not have a move assignment operator and is not
4853 // trivially copyable.
4854 if (!MoveOper->isMoveAssignmentOperator() &&
4855 !FieldRecord->isTriviallyCopyable())
4856 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004857 }
Sean Hunt7f410192011-05-14 05:23:24 +00004858 }
4859
4860 return false;
4861}
4862
Sean Huntcb45a0f2011-05-12 22:46:25 +00004863bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4864 CXXRecordDecl *RD = DD->getParent();
4865 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004866 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004867 return false;
4868
Sean Hunt71a682f2011-05-18 03:41:58 +00004869 SourceLocation Loc = DD->getLocation();
4870
Sean Huntcb45a0f2011-05-12 22:46:25 +00004871 // Do access control from the destructor
4872 ContextRAII CtorContext(*this, DD);
4873
4874 bool Union = RD->isUnion();
4875
Sean Hunt49634cf2011-05-13 06:10:58 +00004876 // We do this because we should never actually use an anonymous
4877 // union's destructor.
4878 if (Union && RD->isAnonymousStructOrUnion())
4879 return false;
4880
Sean Huntcb45a0f2011-05-12 22:46:25 +00004881 // C++0x [class.dtor]p5
4882 // A defaulted destructor for a class X is defined as deleted if:
4883 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4884 BE = RD->bases_end();
4885 BI != BE; ++BI) {
4886 // We'll handle this one later
4887 if (BI->isVirtual())
4888 continue;
4889
4890 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4891 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4892 assert(BaseDtor && "base has no destructor");
4893
4894 // -- any direct or virtual base class has a deleted destructor or
4895 // a destructor that is inaccessible from the defaulted destructor
4896 if (BaseDtor->isDeleted())
4897 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004898 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004899 AR_accessible)
4900 return true;
4901 }
4902
4903 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4904 BE = RD->vbases_end();
4905 BI != BE; ++BI) {
4906 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4907 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4908 assert(BaseDtor && "base has no destructor");
4909
4910 // -- any direct or virtual base class has a deleted destructor or
4911 // a destructor that is inaccessible from the defaulted destructor
4912 if (BaseDtor->isDeleted())
4913 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004914 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004915 AR_accessible)
4916 return true;
4917 }
4918
4919 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4920 FE = RD->field_end();
4921 FI != FE; ++FI) {
4922 QualType FieldType = Context.getBaseElementType(FI->getType());
4923 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4924 if (FieldRecord) {
4925 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4926 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4927 UE = FieldRecord->field_end();
4928 UI != UE; ++UI) {
4929 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4930 CXXRecordDecl *UnionFieldRecord =
4931 UnionFieldType->getAsCXXRecordDecl();
4932
4933 // -- X is a union-like class that has a variant member with a non-
4934 // trivial destructor.
4935 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4936 return true;
4937 }
4938 // Technically we are supposed to do this next check unconditionally.
4939 // But that makes absolutely no sense.
4940 } else {
4941 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4942
4943 // -- any of the non-static data members has class type M (or array
4944 // thereof) and M has a deleted destructor or a destructor that is
4945 // inaccessible from the defaulted destructor
4946 if (FieldDtor->isDeleted())
4947 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004948 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004949 AR_accessible)
4950 return true;
4951
4952 // -- X is a union-like class that has a variant member with a non-
4953 // trivial destructor.
4954 if (Union && !FieldDtor->isTrivial())
4955 return true;
4956 }
4957 }
4958 }
4959
4960 if (DD->isVirtual()) {
4961 FunctionDecl *OperatorDelete = 0;
4962 DeclarationName Name =
4963 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004964 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004965 false))
4966 return true;
4967 }
4968
4969
4970 return false;
4971}
4972
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004973/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004974namespace {
4975 struct FindHiddenVirtualMethodData {
4976 Sema *S;
4977 CXXMethodDecl *Method;
4978 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004979 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004980 };
4981}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004982
4983/// \brief Member lookup function that determines whether a given C++
4984/// method overloads virtual methods in a base class without overriding any,
4985/// to be used with CXXRecordDecl::lookupInBases().
4986static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4987 CXXBasePath &Path,
4988 void *UserData) {
4989 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4990
4991 FindHiddenVirtualMethodData &Data
4992 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4993
4994 DeclarationName Name = Data.Method->getDeclName();
4995 assert(Name.getNameKind() == DeclarationName::Identifier);
4996
4997 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004998 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004999 for (Path.Decls = BaseRecord->lookup(Name);
5000 Path.Decls.first != Path.Decls.second;
5001 ++Path.Decls.first) {
5002 NamedDecl *D = *Path.Decls.first;
5003 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005004 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005005 foundSameNameMethod = true;
5006 // Interested only in hidden virtual methods.
5007 if (!MD->isVirtual())
5008 continue;
5009 // If the method we are checking overrides a method from its base
5010 // don't warn about the other overloaded methods.
5011 if (!Data.S->IsOverload(Data.Method, MD, false))
5012 return true;
5013 // Collect the overload only if its hidden.
5014 if (!Data.OverridenAndUsingBaseMethods.count(MD))
5015 overloadedMethods.push_back(MD);
5016 }
5017 }
5018
5019 if (foundSameNameMethod)
5020 Data.OverloadedMethods.append(overloadedMethods.begin(),
5021 overloadedMethods.end());
5022 return foundSameNameMethod;
5023}
5024
5025/// \brief See if a method overloads virtual methods in a base class without
5026/// overriding any.
5027void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5028 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005029 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005030 return;
5031 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
5032 return;
5033
5034 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5035 /*bool RecordPaths=*/false,
5036 /*bool DetectVirtual=*/false);
5037 FindHiddenVirtualMethodData Data;
5038 Data.Method = MD;
5039 Data.S = this;
5040
5041 // Keep the base methods that were overriden or introduced in the subclass
5042 // by 'using' in a set. A base method not in this set is hidden.
5043 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5044 res.first != res.second; ++res.first) {
5045 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
5046 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5047 E = MD->end_overridden_methods();
5048 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005049 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005050 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5051 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005052 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005053 }
5054
5055 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5056 !Data.OverloadedMethods.empty()) {
5057 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5058 << MD << (Data.OverloadedMethods.size() > 1);
5059
5060 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5061 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5062 Diag(overloadedMD->getLocation(),
5063 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5064 }
5065 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005066}
5067
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005068void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005069 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005070 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005071 SourceLocation RBrac,
5072 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005073 if (!TagDecl)
5074 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005075
Douglas Gregor42af25f2009-05-11 19:58:34 +00005076 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005077
David Blaikie77b6de02011-09-22 02:58:26 +00005078 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005079 // strict aliasing violation!
5080 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005081 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005082
Douglas Gregor23c94db2010-07-02 17:43:08 +00005083 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005084 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005085}
5086
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005087/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5088/// special functions, such as the default constructor, copy
5089/// constructor, or destructor, to the given C++ class (C++
5090/// [special]p1). This routine can only be executed just before the
5091/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005092void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005093 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005094 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005095
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005096 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00005097 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005098
Richard Smithb701d3d2011-12-24 21:56:24 +00005099 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5100 ++ASTContext::NumImplicitMoveConstructors;
5101
Douglas Gregora376d102010-07-02 21:50:04 +00005102 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5103 ++ASTContext::NumImplicitCopyAssignmentOperators;
5104
5105 // If we have a dynamic class, then the copy assignment operator may be
5106 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5107 // it shows up in the right place in the vtable and that we diagnose
5108 // problems with the implicit exception specification.
5109 if (ClassDecl->isDynamicClass())
5110 DeclareImplicitCopyAssignment(ClassDecl);
5111 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005112
Richard Smithb701d3d2011-12-24 21:56:24 +00005113 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5114 ++ASTContext::NumImplicitMoveAssignmentOperators;
5115
5116 // Likewise for the move assignment operator.
5117 if (ClassDecl->isDynamicClass())
5118 DeclareImplicitMoveAssignment(ClassDecl);
5119 }
5120
Douglas Gregor4923aa22010-07-02 20:37:36 +00005121 if (!ClassDecl->hasUserDeclaredDestructor()) {
5122 ++ASTContext::NumImplicitDestructors;
5123
5124 // If we have a dynamic class, then the destructor may be virtual, so we
5125 // have to declare the destructor immediately. This ensures that, e.g., it
5126 // shows up in the right place in the vtable and that we diagnose problems
5127 // with the implicit exception specification.
5128 if (ClassDecl->isDynamicClass())
5129 DeclareImplicitDestructor(ClassDecl);
5130 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005131}
5132
Francois Pichet8387e2a2011-04-22 22:18:13 +00005133void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5134 if (!D)
5135 return;
5136
5137 int NumParamList = D->getNumTemplateParameterLists();
5138 for (int i = 0; i < NumParamList; i++) {
5139 TemplateParameterList* Params = D->getTemplateParameterList(i);
5140 for (TemplateParameterList::iterator Param = Params->begin(),
5141 ParamEnd = Params->end();
5142 Param != ParamEnd; ++Param) {
5143 NamedDecl *Named = cast<NamedDecl>(*Param);
5144 if (Named->getDeclName()) {
5145 S->AddDecl(Named);
5146 IdResolver.AddDecl(Named);
5147 }
5148 }
5149 }
5150}
5151
John McCalld226f652010-08-21 09:40:31 +00005152void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005153 if (!D)
5154 return;
5155
5156 TemplateParameterList *Params = 0;
5157 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5158 Params = Template->getTemplateParameters();
5159 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5160 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5161 Params = PartialSpec->getTemplateParameters();
5162 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005163 return;
5164
Douglas Gregor6569d682009-05-27 23:11:45 +00005165 for (TemplateParameterList::iterator Param = Params->begin(),
5166 ParamEnd = Params->end();
5167 Param != ParamEnd; ++Param) {
5168 NamedDecl *Named = cast<NamedDecl>(*Param);
5169 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005170 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005171 IdResolver.AddDecl(Named);
5172 }
5173 }
5174}
5175
John McCalld226f652010-08-21 09:40:31 +00005176void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005177 if (!RecordD) return;
5178 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005179 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005180 PushDeclContext(S, Record);
5181}
5182
John McCalld226f652010-08-21 09:40:31 +00005183void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005184 if (!RecordD) return;
5185 PopDeclContext();
5186}
5187
Douglas Gregor72b505b2008-12-16 21:30:33 +00005188/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5189/// parsing a top-level (non-nested) C++ class, and we are now
5190/// parsing those parts of the given Method declaration that could
5191/// not be parsed earlier (C++ [class.mem]p2), such as default
5192/// arguments. This action should enter the scope of the given
5193/// Method declaration as if we had just parsed the qualified method
5194/// name. However, it should not bring the parameters into scope;
5195/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005196void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005197}
5198
5199/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5200/// C++ method declaration. We're (re-)introducing the given
5201/// function parameter into scope for use in parsing later parts of
5202/// the method declaration. For example, we could see an
5203/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005204void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005205 if (!ParamD)
5206 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005207
John McCalld226f652010-08-21 09:40:31 +00005208 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005209
5210 // If this parameter has an unparsed default argument, clear it out
5211 // to make way for the parsed default argument.
5212 if (Param->hasUnparsedDefaultArg())
5213 Param->setDefaultArg(0);
5214
John McCalld226f652010-08-21 09:40:31 +00005215 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005216 if (Param->getDeclName())
5217 IdResolver.AddDecl(Param);
5218}
5219
5220/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5221/// processing the delayed method declaration for Method. The method
5222/// declaration is now considered finished. There may be a separate
5223/// ActOnStartOfFunctionDef action later (not necessarily
5224/// immediately!) for this method, if it was also defined inside the
5225/// class body.
John McCalld226f652010-08-21 09:40:31 +00005226void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005227 if (!MethodD)
5228 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005229
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005230 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005231
John McCalld226f652010-08-21 09:40:31 +00005232 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005233
5234 // Now that we have our default arguments, check the constructor
5235 // again. It could produce additional diagnostics or affect whether
5236 // the class has implicitly-declared destructors, among other
5237 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005238 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5239 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005240
5241 // Check the default arguments, which we may have added.
5242 if (!Method->isInvalidDecl())
5243 CheckCXXDefaultArguments(Method);
5244}
5245
Douglas Gregor42a552f2008-11-05 20:51:48 +00005246/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005247/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005248/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005249/// emit diagnostics and set the invalid bit to true. In any case, the type
5250/// will be updated to reflect a well-formed type for the constructor and
5251/// returned.
5252QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005253 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005254 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005255
5256 // C++ [class.ctor]p3:
5257 // A constructor shall not be virtual (10.3) or static (9.4). A
5258 // constructor can be invoked for a const, volatile or const
5259 // volatile object. A constructor shall not be declared const,
5260 // volatile, or const volatile (9.3.2).
5261 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005262 if (!D.isInvalidType())
5263 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5264 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5265 << SourceRange(D.getIdentifierLoc());
5266 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005267 }
John McCalld931b082010-08-26 03:08:43 +00005268 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005269 if (!D.isInvalidType())
5270 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5271 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5272 << SourceRange(D.getIdentifierLoc());
5273 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005274 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005275 }
Mike Stump1eb44332009-09-09 15:08:12 +00005276
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005277 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005278 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005279 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005280 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5281 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005282 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005283 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5284 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005285 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005286 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5287 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005288 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005289 }
Mike Stump1eb44332009-09-09 15:08:12 +00005290
Douglas Gregorc938c162011-01-26 05:01:58 +00005291 // C++0x [class.ctor]p4:
5292 // A constructor shall not be declared with a ref-qualifier.
5293 if (FTI.hasRefQualifier()) {
5294 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5295 << FTI.RefQualifierIsLValueRef
5296 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5297 D.setInvalidType();
5298 }
5299
Douglas Gregor42a552f2008-11-05 20:51:48 +00005300 // Rebuild the function type "R" without any type qualifiers (in
5301 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005302 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005303 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005304 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5305 return R;
5306
5307 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5308 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005309 EPI.RefQualifier = RQ_None;
5310
Chris Lattner65401802009-04-25 08:28:21 +00005311 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005312 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005313}
5314
Douglas Gregor72b505b2008-12-16 21:30:33 +00005315/// CheckConstructor - Checks a fully-formed constructor for
5316/// well-formedness, issuing any diagnostics required. Returns true if
5317/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005318void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005319 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005320 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5321 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005322 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005323
5324 // C++ [class.copy]p3:
5325 // A declaration of a constructor for a class X is ill-formed if
5326 // its first parameter is of type (optionally cv-qualified) X and
5327 // either there are no other parameters or else all other
5328 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005329 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005330 ((Constructor->getNumParams() == 1) ||
5331 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005332 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5333 Constructor->getTemplateSpecializationKind()
5334 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005335 QualType ParamType = Constructor->getParamDecl(0)->getType();
5336 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5337 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005338 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005339 const char *ConstRef
5340 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5341 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005342 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005343 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005344
5345 // FIXME: Rather that making the constructor invalid, we should endeavor
5346 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005347 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005348 }
5349 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005350}
5351
John McCall15442822010-08-04 01:04:25 +00005352/// CheckDestructor - Checks a fully-formed destructor definition for
5353/// well-formedness, issuing any diagnostics required. Returns true
5354/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005355bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005356 CXXRecordDecl *RD = Destructor->getParent();
5357
5358 if (Destructor->isVirtual()) {
5359 SourceLocation Loc;
5360
5361 if (!Destructor->isImplicit())
5362 Loc = Destructor->getLocation();
5363 else
5364 Loc = RD->getLocation();
5365
5366 // If we have a virtual destructor, look up the deallocation function
5367 FunctionDecl *OperatorDelete = 0;
5368 DeclarationName Name =
5369 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005370 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005371 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005372
Eli Friedman5f2987c2012-02-02 03:46:19 +00005373 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005374
5375 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005376 }
Anders Carlsson37909802009-11-30 21:24:50 +00005377
5378 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005379}
5380
Mike Stump1eb44332009-09-09 15:08:12 +00005381static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005382FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5383 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5384 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005385 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005386}
5387
Douglas Gregor42a552f2008-11-05 20:51:48 +00005388/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5389/// the well-formednes of the destructor declarator @p D with type @p
5390/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005391/// emit diagnostics and set the declarator to invalid. Even if this happens,
5392/// will be updated to reflect a well-formed type for the destructor and
5393/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005394QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005395 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005396 // C++ [class.dtor]p1:
5397 // [...] A typedef-name that names a class is a class-name
5398 // (7.1.3); however, a typedef-name that names a class shall not
5399 // be used as the identifier in the declarator for a destructor
5400 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005401 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005402 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005403 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005404 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005405 else if (const TemplateSpecializationType *TST =
5406 DeclaratorType->getAs<TemplateSpecializationType>())
5407 if (TST->isTypeAlias())
5408 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5409 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005410
5411 // C++ [class.dtor]p2:
5412 // A destructor is used to destroy objects of its class type. A
5413 // destructor takes no parameters, and no return type can be
5414 // specified for it (not even void). The address of a destructor
5415 // shall not be taken. A destructor shall not be static. A
5416 // destructor can be invoked for a const, volatile or const
5417 // volatile object. A destructor shall not be declared const,
5418 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005419 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005420 if (!D.isInvalidType())
5421 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5422 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005423 << SourceRange(D.getIdentifierLoc())
5424 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5425
John McCalld931b082010-08-26 03:08:43 +00005426 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005427 }
Chris Lattner65401802009-04-25 08:28:21 +00005428 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005429 // Destructors don't have return types, but the parser will
5430 // happily parse something like:
5431 //
5432 // class X {
5433 // float ~X();
5434 // };
5435 //
5436 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005437 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5438 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5439 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005440 }
Mike Stump1eb44332009-09-09 15:08:12 +00005441
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005442 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005443 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005444 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005445 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5446 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005447 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005448 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5449 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005450 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005451 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5452 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005453 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005454 }
5455
Douglas Gregorc938c162011-01-26 05:01:58 +00005456 // C++0x [class.dtor]p2:
5457 // A destructor shall not be declared with a ref-qualifier.
5458 if (FTI.hasRefQualifier()) {
5459 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5460 << FTI.RefQualifierIsLValueRef
5461 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5462 D.setInvalidType();
5463 }
5464
Douglas Gregor42a552f2008-11-05 20:51:48 +00005465 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005466 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005467 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5468
5469 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005470 FTI.freeArgs();
5471 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005472 }
5473
Mike Stump1eb44332009-09-09 15:08:12 +00005474 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005475 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005476 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005477 D.setInvalidType();
5478 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005479
5480 // Rebuild the function type "R" without any type qualifiers or
5481 // parameters (in case any of the errors above fired) and with
5482 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005483 // types.
John McCalle23cf432010-12-14 08:05:40 +00005484 if (!D.isInvalidType())
5485 return R;
5486
Douglas Gregord92ec472010-07-01 05:10:53 +00005487 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005488 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5489 EPI.Variadic = false;
5490 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005491 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005492 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005493}
5494
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005495/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5496/// well-formednes of the conversion function declarator @p D with
5497/// type @p R. If there are any errors in the declarator, this routine
5498/// will emit diagnostics and return true. Otherwise, it will return
5499/// false. Either way, the type @p R will be updated to reflect a
5500/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005501void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005502 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005503 // C++ [class.conv.fct]p1:
5504 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005505 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005506 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005507 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005508 if (!D.isInvalidType())
5509 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5510 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5511 << SourceRange(D.getIdentifierLoc());
5512 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005513 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005514 }
John McCalla3f81372010-04-13 00:04:31 +00005515
5516 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5517
Chris Lattner6e475012009-04-25 08:35:12 +00005518 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005519 // Conversion functions don't have return types, but the parser will
5520 // happily parse something like:
5521 //
5522 // class X {
5523 // float operator bool();
5524 // };
5525 //
5526 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005527 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5528 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5529 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005530 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005531 }
5532
John McCalla3f81372010-04-13 00:04:31 +00005533 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5534
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005535 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005536 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005537 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5538
5539 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005540 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005541 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005542 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005543 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005544 D.setInvalidType();
5545 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005546
John McCalla3f81372010-04-13 00:04:31 +00005547 // Diagnose "&operator bool()" and other such nonsense. This
5548 // is actually a gcc extension which we don't support.
5549 if (Proto->getResultType() != ConvType) {
5550 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5551 << Proto->getResultType();
5552 D.setInvalidType();
5553 ConvType = Proto->getResultType();
5554 }
5555
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005556 // C++ [class.conv.fct]p4:
5557 // The conversion-type-id shall not represent a function type nor
5558 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005559 if (ConvType->isArrayType()) {
5560 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5561 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005562 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005563 } else if (ConvType->isFunctionType()) {
5564 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5565 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005566 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005567 }
5568
5569 // Rebuild the function type "R" without any parameters (in case any
5570 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005571 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005572 if (D.isInvalidType())
5573 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005574
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005575 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005576 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005577 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005578 getLangOptions().CPlusPlus0x ?
5579 diag::warn_cxx98_compat_explicit_conversion_functions :
5580 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005581 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005582}
5583
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005584/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5585/// the declaration of the given C++ conversion function. This routine
5586/// is responsible for recording the conversion function in the C++
5587/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005588Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005589 assert(Conversion && "Expected to receive a conversion function declaration");
5590
Douglas Gregor9d350972008-12-12 08:25:50 +00005591 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005592
5593 // Make sure we aren't redeclaring the conversion function.
5594 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005595
5596 // C++ [class.conv.fct]p1:
5597 // [...] A conversion function is never used to convert a
5598 // (possibly cv-qualified) object to the (possibly cv-qualified)
5599 // same object type (or a reference to it), to a (possibly
5600 // cv-qualified) base class of that type (or a reference to it),
5601 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005602 // FIXME: Suppress this warning if the conversion function ends up being a
5603 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005604 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005605 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005606 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005607 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005608 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5609 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005610 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005611 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005612 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5613 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005614 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005615 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005616 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005617 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005618 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005619 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005620 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005621 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005622 }
5623
Douglas Gregore80622f2010-09-29 04:25:11 +00005624 if (FunctionTemplateDecl *ConversionTemplate
5625 = Conversion->getDescribedFunctionTemplate())
5626 return ConversionTemplate;
5627
John McCalld226f652010-08-21 09:40:31 +00005628 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005629}
5630
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005631//===----------------------------------------------------------------------===//
5632// Namespace Handling
5633//===----------------------------------------------------------------------===//
5634
John McCallea318642010-08-26 09:15:37 +00005635
5636
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005637/// ActOnStartNamespaceDef - This is called at the start of a namespace
5638/// definition.
John McCalld226f652010-08-21 09:40:31 +00005639Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005640 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005641 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005642 SourceLocation IdentLoc,
5643 IdentifierInfo *II,
5644 SourceLocation LBrace,
5645 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005646 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5647 // For anonymous namespace, take the location of the left brace.
5648 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005649 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005650 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005651 bool IsStd = false;
5652 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005653 Scope *DeclRegionScope = NamespcScope->getParent();
5654
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005655 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005656 if (II) {
5657 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005658 // The identifier in an original-namespace-definition shall not
5659 // have been previously defined in the declarative region in
5660 // which the original-namespace-definition appears. The
5661 // identifier in an original-namespace-definition is the name of
5662 // the namespace. Subsequently in that declarative region, it is
5663 // treated as an original-namespace-name.
5664 //
5665 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005666 // look through using directives, just look for any ordinary names.
5667
5668 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005669 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5670 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005671 NamedDecl *PrevDecl = 0;
5672 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005673 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005674 R.first != R.second; ++R.first) {
5675 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5676 PrevDecl = *R.first;
5677 break;
5678 }
5679 }
5680
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005681 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5682
5683 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005684 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005685 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005686 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005687 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005688 // The user probably just forgot the 'inline', so suggest that it
5689 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005690 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005691 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5692 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005693 Diag(Loc, diag::err_inline_namespace_mismatch)
5694 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005695 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005696 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5697
5698 IsInline = PrevNS->isInline();
5699 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005700 } else if (PrevDecl) {
5701 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005702 Diag(Loc, diag::err_redefinition_different_kind)
5703 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005704 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005705 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005706 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005707 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005708 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005709 // This is the first "real" definition of the namespace "std", so update
5710 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005711 PrevNS = getStdNamespace();
5712 IsStd = true;
5713 AddToKnown = !IsInline;
5714 } else {
5715 // We've seen this namespace for the first time.
5716 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005717 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005718 } else {
John McCall9aeed322009-10-01 00:25:31 +00005719 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005720
5721 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005722 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005723 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005724 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005725 } else {
5726 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005727 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005728 }
5729
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005730 if (PrevNS && IsInline != PrevNS->isInline()) {
5731 // inline-ness must match
5732 Diag(Loc, diag::err_inline_namespace_mismatch)
5733 << IsInline;
5734 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005735
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005736 // Recover by ignoring the new namespace's inline status.
5737 IsInline = PrevNS->isInline();
5738 }
5739 }
5740
5741 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5742 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005743 if (IsInvalid)
5744 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005745
5746 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005747
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005748 // FIXME: Should we be merging attributes?
5749 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005750 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005751
5752 if (IsStd)
5753 StdNamespace = Namespc;
5754 if (AddToKnown)
5755 KnownNamespaces[Namespc] = false;
5756
5757 if (II) {
5758 PushOnScopeChains(Namespc, DeclRegionScope);
5759 } else {
5760 // Link the anonymous namespace into its parent.
5761 DeclContext *Parent = CurContext->getRedeclContext();
5762 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5763 TU->setAnonymousNamespace(Namespc);
5764 } else {
5765 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005766 }
John McCall9aeed322009-10-01 00:25:31 +00005767
Douglas Gregora4181472010-03-24 00:46:35 +00005768 CurContext->addDecl(Namespc);
5769
John McCall9aeed322009-10-01 00:25:31 +00005770 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5771 // behaves as if it were replaced by
5772 // namespace unique { /* empty body */ }
5773 // using namespace unique;
5774 // namespace unique { namespace-body }
5775 // where all occurrences of 'unique' in a translation unit are
5776 // replaced by the same identifier and this identifier differs
5777 // from all other identifiers in the entire program.
5778
5779 // We just create the namespace with an empty name and then add an
5780 // implicit using declaration, just like the standard suggests.
5781 //
5782 // CodeGen enforces the "universally unique" aspect by giving all
5783 // declarations semantically contained within an anonymous
5784 // namespace internal linkage.
5785
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005786 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005787 UsingDirectiveDecl* UD
5788 = UsingDirectiveDecl::Create(Context, CurContext,
5789 /* 'using' */ LBrace,
5790 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005791 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005792 /* identifier */ SourceLocation(),
5793 Namespc,
5794 /* Ancestor */ CurContext);
5795 UD->setImplicit();
5796 CurContext->addDecl(UD);
5797 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005798 }
5799
5800 // Although we could have an invalid decl (i.e. the namespace name is a
5801 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005802 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5803 // for the namespace has the declarations that showed up in that particular
5804 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005805 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005806 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005807}
5808
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005809/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5810/// is a namespace alias, returns the namespace it points to.
5811static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5812 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5813 return AD->getNamespace();
5814 return dyn_cast_or_null<NamespaceDecl>(D);
5815}
5816
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005817/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5818/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005819void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005820 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5821 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005822 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005823 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005824 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005825 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005826}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005827
John McCall384aff82010-08-25 07:42:41 +00005828CXXRecordDecl *Sema::getStdBadAlloc() const {
5829 return cast_or_null<CXXRecordDecl>(
5830 StdBadAlloc.get(Context.getExternalSource()));
5831}
5832
5833NamespaceDecl *Sema::getStdNamespace() const {
5834 return cast_or_null<NamespaceDecl>(
5835 StdNamespace.get(Context.getExternalSource()));
5836}
5837
Douglas Gregor66992202010-06-29 17:53:46 +00005838/// \brief Retrieve the special "std" namespace, which may require us to
5839/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005840NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005841 if (!StdNamespace) {
5842 // The "std" namespace has not yet been defined, so build one implicitly.
5843 StdNamespace = NamespaceDecl::Create(Context,
5844 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005845 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005846 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005847 &PP.getIdentifierTable().get("std"),
5848 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005849 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005850 }
5851
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005852 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005853}
5854
Sebastian Redl395e04d2012-01-17 22:49:33 +00005855bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5856 assert(getLangOptions().CPlusPlus &&
5857 "Looking for std::initializer_list outside of C++.");
5858
5859 // We're looking for implicit instantiations of
5860 // template <typename E> class std::initializer_list.
5861
5862 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5863 return false;
5864
Sebastian Redl84760e32012-01-17 22:49:58 +00005865 ClassTemplateDecl *Template = 0;
5866 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005867
Sebastian Redl84760e32012-01-17 22:49:58 +00005868 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005869
Sebastian Redl84760e32012-01-17 22:49:58 +00005870 ClassTemplateSpecializationDecl *Specialization =
5871 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5872 if (!Specialization)
5873 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005874
Sebastian Redl84760e32012-01-17 22:49:58 +00005875 Template = Specialization->getSpecializedTemplate();
5876 Arguments = Specialization->getTemplateArgs().data();
5877 } else if (const TemplateSpecializationType *TST =
5878 Ty->getAs<TemplateSpecializationType>()) {
5879 Template = dyn_cast_or_null<ClassTemplateDecl>(
5880 TST->getTemplateName().getAsTemplateDecl());
5881 Arguments = TST->getArgs();
5882 }
5883 if (!Template)
5884 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005885
5886 if (!StdInitializerList) {
5887 // Haven't recognized std::initializer_list yet, maybe this is it.
5888 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5889 if (TemplateClass->getIdentifier() !=
5890 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005891 !getStdNamespace()->InEnclosingNamespaceSetOf(
5892 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005893 return false;
5894 // This is a template called std::initializer_list, but is it the right
5895 // template?
5896 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005897 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005898 return false;
5899 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5900 return false;
5901
5902 // It's the right template.
5903 StdInitializerList = Template;
5904 }
5905
5906 if (Template != StdInitializerList)
5907 return false;
5908
5909 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005910 if (Element)
5911 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005912 return true;
5913}
5914
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005915static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5916 NamespaceDecl *Std = S.getStdNamespace();
5917 if (!Std) {
5918 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5919 return 0;
5920 }
5921
5922 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5923 Loc, Sema::LookupOrdinaryName);
5924 if (!S.LookupQualifiedName(Result, Std)) {
5925 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5926 return 0;
5927 }
5928 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5929 if (!Template) {
5930 Result.suppressDiagnostics();
5931 // We found something weird. Complain about the first thing we found.
5932 NamedDecl *Found = *Result.begin();
5933 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5934 return 0;
5935 }
5936
5937 // We found some template called std::initializer_list. Now verify that it's
5938 // correct.
5939 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005940 if (Params->getMinRequiredArguments() != 1 ||
5941 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005942 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5943 return 0;
5944 }
5945
5946 return Template;
5947}
5948
5949QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5950 if (!StdInitializerList) {
5951 StdInitializerList = LookupStdInitializerList(*this, Loc);
5952 if (!StdInitializerList)
5953 return QualType();
5954 }
5955
5956 TemplateArgumentListInfo Args(Loc, Loc);
5957 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5958 Context.getTrivialTypeSourceInfo(Element,
5959 Loc)));
5960 return Context.getCanonicalType(
5961 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5962}
5963
Sebastian Redl98d36062012-01-17 22:50:14 +00005964bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5965 // C++ [dcl.init.list]p2:
5966 // A constructor is an initializer-list constructor if its first parameter
5967 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5968 // std::initializer_list<E> for some type E, and either there are no other
5969 // parameters or else all other parameters have default arguments.
5970 if (Ctor->getNumParams() < 1 ||
5971 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5972 return false;
5973
5974 QualType ArgType = Ctor->getParamDecl(0)->getType();
5975 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5976 ArgType = RT->getPointeeType().getUnqualifiedType();
5977
5978 return isStdInitializerList(ArgType, 0);
5979}
5980
Douglas Gregor9172aa62011-03-26 22:25:30 +00005981/// \brief Determine whether a using statement is in a context where it will be
5982/// apply in all contexts.
5983static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5984 switch (CurContext->getDeclKind()) {
5985 case Decl::TranslationUnit:
5986 return true;
5987 case Decl::LinkageSpec:
5988 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5989 default:
5990 return false;
5991 }
5992}
5993
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005994namespace {
5995
5996// Callback to only accept typo corrections that are namespaces.
5997class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5998 public:
5999 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6000 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6001 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6002 }
6003 return false;
6004 }
6005};
6006
6007}
6008
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006009static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6010 CXXScopeSpec &SS,
6011 SourceLocation IdentLoc,
6012 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006013 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006014 R.clear();
6015 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006016 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006017 Validator)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006018 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
6019 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
6020 if (DeclContext *DC = S.computeDeclContext(SS, false))
6021 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6022 << Ident << DC << CorrectedQuotedStr << SS.getRange()
6023 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6024 else
6025 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6026 << Ident << CorrectedQuotedStr
6027 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006028
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006029 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6030 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006031
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006032 Ident = Corrected.getCorrectionAsIdentifierInfo();
6033 R.addDecl(Corrected.getCorrectionDecl());
6034 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006035 }
6036 return false;
6037}
6038
John McCalld226f652010-08-21 09:40:31 +00006039Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006040 SourceLocation UsingLoc,
6041 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006042 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006043 SourceLocation IdentLoc,
6044 IdentifierInfo *NamespcName,
6045 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006046 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6047 assert(NamespcName && "Invalid NamespcName.");
6048 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006049
6050 // This can only happen along a recovery path.
6051 while (S->getFlags() & Scope::TemplateParamScope)
6052 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006053 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006054
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006055 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006056 NestedNameSpecifier *Qualifier = 0;
6057 if (SS.isSet())
6058 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6059
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006060 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006061 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6062 LookupParsedName(R, S, &SS);
6063 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006064 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006065
Douglas Gregor66992202010-06-29 17:53:46 +00006066 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006067 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006068 // Allow "using namespace std;" or "using namespace ::std;" even if
6069 // "std" hasn't been defined yet, for GCC compatibility.
6070 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6071 NamespcName->isStr("std")) {
6072 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006073 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006074 R.resolveKind();
6075 }
6076 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006077 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006078 }
6079
John McCallf36e02d2009-10-09 21:13:30 +00006080 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006081 NamedDecl *Named = R.getFoundDecl();
6082 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6083 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006084 // C++ [namespace.udir]p1:
6085 // A using-directive specifies that the names in the nominated
6086 // namespace can be used in the scope in which the
6087 // using-directive appears after the using-directive. During
6088 // unqualified name lookup (3.4.1), the names appear as if they
6089 // were declared in the nearest enclosing namespace which
6090 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006091 // namespace. [Note: in this context, "contains" means "contains
6092 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006093
6094 // Find enclosing context containing both using-directive and
6095 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006096 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006097 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6098 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6099 CommonAncestor = CommonAncestor->getParent();
6100
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006101 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006102 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006103 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006104
Douglas Gregor9172aa62011-03-26 22:25:30 +00006105 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006106 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006107 Diag(IdentLoc, diag::warn_using_directive_in_header);
6108 }
6109
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006110 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006111 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006112 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006113 }
6114
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006115 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006116 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006117}
6118
6119void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6120 // If scope has associated entity, then using directive is at namespace
6121 // or translation unit scope. We add UsingDirectiveDecls, into
6122 // it's lookup structure.
6123 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006124 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006125 else
6126 // Otherwise it is block-sope. using-directives will affect lookup
6127 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00006128 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006129}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006130
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006131
John McCalld226f652010-08-21 09:40:31 +00006132Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006133 AccessSpecifier AS,
6134 bool HasUsingKeyword,
6135 SourceLocation UsingLoc,
6136 CXXScopeSpec &SS,
6137 UnqualifiedId &Name,
6138 AttributeList *AttrList,
6139 bool IsTypeName,
6140 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006141 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006142
Douglas Gregor12c118a2009-11-04 16:30:06 +00006143 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006144 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006145 case UnqualifiedId::IK_Identifier:
6146 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006147 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006148 case UnqualifiedId::IK_ConversionFunctionId:
6149 break;
6150
6151 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006152 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00006153 // C++0x inherited constructors.
Richard Smithebaf0e62011-10-18 20:49:44 +00006154 Diag(Name.getSourceRange().getBegin(),
6155 getLangOptions().CPlusPlus0x ?
6156 diag::warn_cxx98_compat_using_decl_constructor :
6157 diag::err_using_decl_constructor)
6158 << SS.getRange();
6159
John McCall604e7f12009-12-08 07:46:18 +00006160 if (getLangOptions().CPlusPlus0x) break;
6161
John McCalld226f652010-08-21 09:40:31 +00006162 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006163
6164 case UnqualifiedId::IK_DestructorName:
6165 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6166 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006167 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006168
6169 case UnqualifiedId::IK_TemplateId:
6170 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6171 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006172 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006173 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006174
6175 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6176 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006177 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006178 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006179
John McCall60fa3cf2009-12-11 02:10:03 +00006180 // Warn about using declarations.
6181 // TODO: store that the declaration was written without 'using' and
6182 // talk about access decls instead of using decls in the
6183 // diagnostics.
6184 if (!HasUsingKeyword) {
6185 UsingLoc = Name.getSourceRange().getBegin();
6186
6187 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006188 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006189 }
6190
Douglas Gregor56c04582010-12-16 00:46:58 +00006191 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6192 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6193 return 0;
6194
John McCall9488ea12009-11-17 05:59:44 +00006195 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006196 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006197 /* IsInstantiation */ false,
6198 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006199 if (UD)
6200 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006201
John McCalld226f652010-08-21 09:40:31 +00006202 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006203}
6204
Douglas Gregor09acc982010-07-07 23:08:52 +00006205/// \brief Determine whether a using declaration considers the given
6206/// declarations as "equivalent", e.g., if they are redeclarations of
6207/// the same entity or are both typedefs of the same type.
6208static bool
6209IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6210 bool &SuppressRedeclaration) {
6211 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6212 SuppressRedeclaration = false;
6213 return true;
6214 }
6215
Richard Smith162e1c12011-04-15 14:24:37 +00006216 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6217 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006218 SuppressRedeclaration = true;
6219 return Context.hasSameType(TD1->getUnderlyingType(),
6220 TD2->getUnderlyingType());
6221 }
6222
6223 return false;
6224}
6225
6226
John McCall9f54ad42009-12-10 09:41:52 +00006227/// Determines whether to create a using shadow decl for a particular
6228/// decl, given the set of decls existing prior to this using lookup.
6229bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6230 const LookupResult &Previous) {
6231 // Diagnose finding a decl which is not from a base class of the
6232 // current class. We do this now because there are cases where this
6233 // function will silently decide not to build a shadow decl, which
6234 // will pre-empt further diagnostics.
6235 //
6236 // We don't need to do this in C++0x because we do the check once on
6237 // the qualifier.
6238 //
6239 // FIXME: diagnose the following if we care enough:
6240 // struct A { int foo; };
6241 // struct B : A { using A::foo; };
6242 // template <class T> struct C : A {};
6243 // template <class T> struct D : C<T> { using B::foo; } // <---
6244 // This is invalid (during instantiation) in C++03 because B::foo
6245 // resolves to the using decl in B, which is not a base class of D<T>.
6246 // We can't diagnose it immediately because C<T> is an unknown
6247 // specialization. The UsingShadowDecl in D<T> then points directly
6248 // to A::foo, which will look well-formed when we instantiate.
6249 // The right solution is to not collapse the shadow-decl chain.
6250 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6251 DeclContext *OrigDC = Orig->getDeclContext();
6252
6253 // Handle enums and anonymous structs.
6254 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6255 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6256 while (OrigRec->isAnonymousStructOrUnion())
6257 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6258
6259 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6260 if (OrigDC == CurContext) {
6261 Diag(Using->getLocation(),
6262 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006263 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006264 Diag(Orig->getLocation(), diag::note_using_decl_target);
6265 return true;
6266 }
6267
Douglas Gregordc355712011-02-25 00:36:19 +00006268 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006269 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006270 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006271 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006272 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006273 Diag(Orig->getLocation(), diag::note_using_decl_target);
6274 return true;
6275 }
6276 }
6277
6278 if (Previous.empty()) return false;
6279
6280 NamedDecl *Target = Orig;
6281 if (isa<UsingShadowDecl>(Target))
6282 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6283
John McCalld7533ec2009-12-11 02:33:26 +00006284 // If the target happens to be one of the previous declarations, we
6285 // don't have a conflict.
6286 //
6287 // FIXME: but we might be increasing its access, in which case we
6288 // should redeclare it.
6289 NamedDecl *NonTag = 0, *Tag = 0;
6290 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6291 I != E; ++I) {
6292 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006293 bool Result;
6294 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6295 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006296
6297 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6298 }
6299
John McCall9f54ad42009-12-10 09:41:52 +00006300 if (Target->isFunctionOrFunctionTemplate()) {
6301 FunctionDecl *FD;
6302 if (isa<FunctionTemplateDecl>(Target))
6303 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6304 else
6305 FD = cast<FunctionDecl>(Target);
6306
6307 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006308 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006309 case Ovl_Overload:
6310 return false;
6311
6312 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006313 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006314 break;
6315
6316 // We found a decl with the exact signature.
6317 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006318 // If we're in a record, we want to hide the target, so we
6319 // return true (without a diagnostic) to tell the caller not to
6320 // build a shadow decl.
6321 if (CurContext->isRecord())
6322 return true;
6323
6324 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006325 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006326 break;
6327 }
6328
6329 Diag(Target->getLocation(), diag::note_using_decl_target);
6330 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6331 return true;
6332 }
6333
6334 // Target is not a function.
6335
John McCall9f54ad42009-12-10 09:41:52 +00006336 if (isa<TagDecl>(Target)) {
6337 // No conflict between a tag and a non-tag.
6338 if (!Tag) return false;
6339
John McCall41ce66f2009-12-10 19:51:03 +00006340 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006341 Diag(Target->getLocation(), diag::note_using_decl_target);
6342 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6343 return true;
6344 }
6345
6346 // No conflict between a tag and a non-tag.
6347 if (!NonTag) return false;
6348
John McCall41ce66f2009-12-10 19:51:03 +00006349 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006350 Diag(Target->getLocation(), diag::note_using_decl_target);
6351 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6352 return true;
6353}
6354
John McCall9488ea12009-11-17 05:59:44 +00006355/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006356UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006357 UsingDecl *UD,
6358 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006359
6360 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006361 NamedDecl *Target = Orig;
6362 if (isa<UsingShadowDecl>(Target)) {
6363 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6364 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006365 }
6366
6367 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006368 = UsingShadowDecl::Create(Context, CurContext,
6369 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006370 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006371
6372 Shadow->setAccess(UD->getAccess());
6373 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6374 Shadow->setInvalidDecl();
6375
John McCall9488ea12009-11-17 05:59:44 +00006376 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006377 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006378 else
John McCall604e7f12009-12-08 07:46:18 +00006379 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006380
John McCall604e7f12009-12-08 07:46:18 +00006381
John McCall9f54ad42009-12-10 09:41:52 +00006382 return Shadow;
6383}
John McCall604e7f12009-12-08 07:46:18 +00006384
John McCall9f54ad42009-12-10 09:41:52 +00006385/// Hides a using shadow declaration. This is required by the current
6386/// using-decl implementation when a resolvable using declaration in a
6387/// class is followed by a declaration which would hide or override
6388/// one or more of the using decl's targets; for example:
6389///
6390/// struct Base { void foo(int); };
6391/// struct Derived : Base {
6392/// using Base::foo;
6393/// void foo(int);
6394/// };
6395///
6396/// The governing language is C++03 [namespace.udecl]p12:
6397///
6398/// When a using-declaration brings names from a base class into a
6399/// derived class scope, member functions in the derived class
6400/// override and/or hide member functions with the same name and
6401/// parameter types in a base class (rather than conflicting).
6402///
6403/// There are two ways to implement this:
6404/// (1) optimistically create shadow decls when they're not hidden
6405/// by existing declarations, or
6406/// (2) don't create any shadow decls (or at least don't make them
6407/// visible) until we've fully parsed/instantiated the class.
6408/// The problem with (1) is that we might have to retroactively remove
6409/// a shadow decl, which requires several O(n) operations because the
6410/// decl structures are (very reasonably) not designed for removal.
6411/// (2) avoids this but is very fiddly and phase-dependent.
6412void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006413 if (Shadow->getDeclName().getNameKind() ==
6414 DeclarationName::CXXConversionFunctionName)
6415 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6416
John McCall9f54ad42009-12-10 09:41:52 +00006417 // Remove it from the DeclContext...
6418 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006419
John McCall9f54ad42009-12-10 09:41:52 +00006420 // ...and the scope, if applicable...
6421 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006422 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006423 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006424 }
6425
John McCall9f54ad42009-12-10 09:41:52 +00006426 // ...and the using decl.
6427 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6428
6429 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006430 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006431}
6432
John McCall7ba107a2009-11-18 02:36:19 +00006433/// Builds a using declaration.
6434///
6435/// \param IsInstantiation - Whether this call arises from an
6436/// instantiation of an unresolved using declaration. We treat
6437/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006438NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6439 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006440 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006441 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006442 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006443 bool IsInstantiation,
6444 bool IsTypeName,
6445 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006446 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006447 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006448 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006449
Anders Carlsson550b14b2009-08-28 05:49:21 +00006450 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006451
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006452 if (SS.isEmpty()) {
6453 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006454 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006455 }
Mike Stump1eb44332009-09-09 15:08:12 +00006456
John McCall9f54ad42009-12-10 09:41:52 +00006457 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006458 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006459 ForRedeclaration);
6460 Previous.setHideTags(false);
6461 if (S) {
6462 LookupName(Previous, S);
6463
6464 // It is really dumb that we have to do this.
6465 LookupResult::Filter F = Previous.makeFilter();
6466 while (F.hasNext()) {
6467 NamedDecl *D = F.next();
6468 if (!isDeclInScope(D, CurContext, S))
6469 F.erase();
6470 }
6471 F.done();
6472 } else {
6473 assert(IsInstantiation && "no scope in non-instantiation");
6474 assert(CurContext->isRecord() && "scope not record in instantiation");
6475 LookupQualifiedName(Previous, CurContext);
6476 }
6477
John McCall9f54ad42009-12-10 09:41:52 +00006478 // Check for invalid redeclarations.
6479 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6480 return 0;
6481
6482 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006483 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6484 return 0;
6485
John McCallaf8e6ed2009-11-12 03:15:40 +00006486 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006487 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006488 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006489 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006490 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006491 // FIXME: not all declaration name kinds are legal here
6492 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6493 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006494 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006495 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006496 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006497 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6498 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006499 }
John McCalled976492009-12-04 22:46:56 +00006500 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006501 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6502 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006503 }
John McCalled976492009-12-04 22:46:56 +00006504 D->setAccess(AS);
6505 CurContext->addDecl(D);
6506
6507 if (!LookupContext) return D;
6508 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006509
John McCall77bb1aa2010-05-01 00:40:08 +00006510 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006511 UD->setInvalidDecl();
6512 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006513 }
6514
Sebastian Redlf677ea32011-02-05 19:23:19 +00006515 // Constructor inheriting using decls get special treatment.
6516 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006517 if (CheckInheritedConstructorUsingDecl(UD))
6518 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006519 return UD;
6520 }
6521
6522 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006523
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006524 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006525
John McCall604e7f12009-12-08 07:46:18 +00006526 // Unlike most lookups, we don't always want to hide tag
6527 // declarations: tag names are visible through the using declaration
6528 // even if hidden by ordinary names, *except* in a dependent context
6529 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006530 if (!IsInstantiation)
6531 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006532
John McCalla24dc2e2009-11-17 02:14:36 +00006533 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006534
John McCallf36e02d2009-10-09 21:13:30 +00006535 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006536 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006537 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006538 UD->setInvalidDecl();
6539 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006540 }
6541
John McCalled976492009-12-04 22:46:56 +00006542 if (R.isAmbiguous()) {
6543 UD->setInvalidDecl();
6544 return UD;
6545 }
Mike Stump1eb44332009-09-09 15:08:12 +00006546
John McCall7ba107a2009-11-18 02:36:19 +00006547 if (IsTypeName) {
6548 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006549 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006550 Diag(IdentLoc, diag::err_using_typename_non_type);
6551 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6552 Diag((*I)->getUnderlyingDecl()->getLocation(),
6553 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006554 UD->setInvalidDecl();
6555 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006556 }
6557 } else {
6558 // If we asked for a non-typename and we got a type, error out,
6559 // but only if this is an instantiation of an unresolved using
6560 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006561 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006562 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6563 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006564 UD->setInvalidDecl();
6565 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006566 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006567 }
6568
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006569 // C++0x N2914 [namespace.udecl]p6:
6570 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006571 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006572 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6573 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006574 UD->setInvalidDecl();
6575 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006576 }
Mike Stump1eb44332009-09-09 15:08:12 +00006577
John McCall9f54ad42009-12-10 09:41:52 +00006578 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6579 if (!CheckUsingShadowDecl(UD, *I, Previous))
6580 BuildUsingShadowDecl(S, UD, *I);
6581 }
John McCall9488ea12009-11-17 05:59:44 +00006582
6583 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006584}
6585
Sebastian Redlf677ea32011-02-05 19:23:19 +00006586/// Additional checks for a using declaration referring to a constructor name.
6587bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6588 if (UD->isTypeName()) {
6589 // FIXME: Cannot specify typename when specifying constructor
6590 return true;
6591 }
6592
Douglas Gregordc355712011-02-25 00:36:19 +00006593 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006594 assert(SourceType &&
6595 "Using decl naming constructor doesn't have type in scope spec.");
6596 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6597
6598 // Check whether the named type is a direct base class.
6599 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6600 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6601 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6602 BaseIt != BaseE; ++BaseIt) {
6603 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6604 if (CanonicalSourceType == BaseType)
6605 break;
6606 }
6607
6608 if (BaseIt == BaseE) {
6609 // Did not find SourceType in the bases.
6610 Diag(UD->getUsingLocation(),
6611 diag::err_using_decl_constructor_not_in_direct_base)
6612 << UD->getNameInfo().getSourceRange()
6613 << QualType(SourceType, 0) << TargetClass;
6614 return true;
6615 }
6616
6617 BaseIt->setInheritConstructors();
6618
6619 return false;
6620}
6621
John McCall9f54ad42009-12-10 09:41:52 +00006622/// Checks that the given using declaration is not an invalid
6623/// redeclaration. Note that this is checking only for the using decl
6624/// itself, not for any ill-formedness among the UsingShadowDecls.
6625bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6626 bool isTypeName,
6627 const CXXScopeSpec &SS,
6628 SourceLocation NameLoc,
6629 const LookupResult &Prev) {
6630 // C++03 [namespace.udecl]p8:
6631 // C++0x [namespace.udecl]p10:
6632 // A using-declaration is a declaration and can therefore be used
6633 // repeatedly where (and only where) multiple declarations are
6634 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006635 //
John McCall8a726212010-11-29 18:01:58 +00006636 // That's in non-member contexts.
6637 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006638 return false;
6639
6640 NestedNameSpecifier *Qual
6641 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6642
6643 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6644 NamedDecl *D = *I;
6645
6646 bool DTypename;
6647 NestedNameSpecifier *DQual;
6648 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6649 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006650 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006651 } else if (UnresolvedUsingValueDecl *UD
6652 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6653 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006654 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006655 } else if (UnresolvedUsingTypenameDecl *UD
6656 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6657 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006658 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006659 } else continue;
6660
6661 // using decls differ if one says 'typename' and the other doesn't.
6662 // FIXME: non-dependent using decls?
6663 if (isTypeName != DTypename) continue;
6664
6665 // using decls differ if they name different scopes (but note that
6666 // template instantiation can cause this check to trigger when it
6667 // didn't before instantiation).
6668 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6669 Context.getCanonicalNestedNameSpecifier(DQual))
6670 continue;
6671
6672 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006673 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006674 return true;
6675 }
6676
6677 return false;
6678}
6679
John McCall604e7f12009-12-08 07:46:18 +00006680
John McCalled976492009-12-04 22:46:56 +00006681/// Checks that the given nested-name qualifier used in a using decl
6682/// in the current context is appropriately related to the current
6683/// scope. If an error is found, diagnoses it and returns true.
6684bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6685 const CXXScopeSpec &SS,
6686 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006687 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006688
John McCall604e7f12009-12-08 07:46:18 +00006689 if (!CurContext->isRecord()) {
6690 // C++03 [namespace.udecl]p3:
6691 // C++0x [namespace.udecl]p8:
6692 // A using-declaration for a class member shall be a member-declaration.
6693
6694 // If we weren't able to compute a valid scope, it must be a
6695 // dependent class scope.
6696 if (!NamedContext || NamedContext->isRecord()) {
6697 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6698 << SS.getRange();
6699 return true;
6700 }
6701
6702 // Otherwise, everything is known to be fine.
6703 return false;
6704 }
6705
6706 // The current scope is a record.
6707
6708 // If the named context is dependent, we can't decide much.
6709 if (!NamedContext) {
6710 // FIXME: in C++0x, we can diagnose if we can prove that the
6711 // nested-name-specifier does not refer to a base class, which is
6712 // still possible in some cases.
6713
6714 // Otherwise we have to conservatively report that things might be
6715 // okay.
6716 return false;
6717 }
6718
6719 if (!NamedContext->isRecord()) {
6720 // Ideally this would point at the last name in the specifier,
6721 // but we don't have that level of source info.
6722 Diag(SS.getRange().getBegin(),
6723 diag::err_using_decl_nested_name_specifier_is_not_class)
6724 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6725 return true;
6726 }
6727
Douglas Gregor6fb07292010-12-21 07:41:49 +00006728 if (!NamedContext->isDependentContext() &&
6729 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6730 return true;
6731
John McCall604e7f12009-12-08 07:46:18 +00006732 if (getLangOptions().CPlusPlus0x) {
6733 // C++0x [namespace.udecl]p3:
6734 // In a using-declaration used as a member-declaration, the
6735 // nested-name-specifier shall name a base class of the class
6736 // being defined.
6737
6738 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6739 cast<CXXRecordDecl>(NamedContext))) {
6740 if (CurContext == NamedContext) {
6741 Diag(NameLoc,
6742 diag::err_using_decl_nested_name_specifier_is_current_class)
6743 << SS.getRange();
6744 return true;
6745 }
6746
6747 Diag(SS.getRange().getBegin(),
6748 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6749 << (NestedNameSpecifier*) SS.getScopeRep()
6750 << cast<CXXRecordDecl>(CurContext)
6751 << SS.getRange();
6752 return true;
6753 }
6754
6755 return false;
6756 }
6757
6758 // C++03 [namespace.udecl]p4:
6759 // A using-declaration used as a member-declaration shall refer
6760 // to a member of a base class of the class being defined [etc.].
6761
6762 // Salient point: SS doesn't have to name a base class as long as
6763 // lookup only finds members from base classes. Therefore we can
6764 // diagnose here only if we can prove that that can't happen,
6765 // i.e. if the class hierarchies provably don't intersect.
6766
6767 // TODO: it would be nice if "definitely valid" results were cached
6768 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6769 // need to be repeated.
6770
6771 struct UserData {
6772 llvm::DenseSet<const CXXRecordDecl*> Bases;
6773
6774 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6775 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6776 Data->Bases.insert(Base);
6777 return true;
6778 }
6779
6780 bool hasDependentBases(const CXXRecordDecl *Class) {
6781 return !Class->forallBases(collect, this);
6782 }
6783
6784 /// Returns true if the base is dependent or is one of the
6785 /// accumulated base classes.
6786 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6787 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6788 return !Data->Bases.count(Base);
6789 }
6790
6791 bool mightShareBases(const CXXRecordDecl *Class) {
6792 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6793 }
6794 };
6795
6796 UserData Data;
6797
6798 // Returns false if we find a dependent base.
6799 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6800 return false;
6801
6802 // Returns false if the class has a dependent base or if it or one
6803 // of its bases is present in the base set of the current context.
6804 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6805 return false;
6806
6807 Diag(SS.getRange().getBegin(),
6808 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6809 << (NestedNameSpecifier*) SS.getScopeRep()
6810 << cast<CXXRecordDecl>(CurContext)
6811 << SS.getRange();
6812
6813 return true;
John McCalled976492009-12-04 22:46:56 +00006814}
6815
Richard Smith162e1c12011-04-15 14:24:37 +00006816Decl *Sema::ActOnAliasDeclaration(Scope *S,
6817 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006818 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006819 SourceLocation UsingLoc,
6820 UnqualifiedId &Name,
6821 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006822 // Skip up to the relevant declaration scope.
6823 while (S->getFlags() & Scope::TemplateParamScope)
6824 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006825 assert((S->getFlags() & Scope::DeclScope) &&
6826 "got alias-declaration outside of declaration scope");
6827
6828 if (Type.isInvalid())
6829 return 0;
6830
6831 bool Invalid = false;
6832 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6833 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006834 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006835
6836 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6837 return 0;
6838
6839 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006840 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006841 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006842 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6843 TInfo->getTypeLoc().getBeginLoc());
6844 }
Richard Smith162e1c12011-04-15 14:24:37 +00006845
6846 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6847 LookupName(Previous, S);
6848
6849 // Warn about shadowing the name of a template parameter.
6850 if (Previous.isSingleResult() &&
6851 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006852 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006853 Previous.clear();
6854 }
6855
6856 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6857 "name in alias declaration must be an identifier");
6858 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6859 Name.StartLocation,
6860 Name.Identifier, TInfo);
6861
6862 NewTD->setAccess(AS);
6863
6864 if (Invalid)
6865 NewTD->setInvalidDecl();
6866
Richard Smith3e4c6c42011-05-05 21:57:07 +00006867 CheckTypedefForVariablyModifiedType(S, NewTD);
6868 Invalid |= NewTD->isInvalidDecl();
6869
Richard Smith162e1c12011-04-15 14:24:37 +00006870 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006871
6872 NamedDecl *NewND;
6873 if (TemplateParamLists.size()) {
6874 TypeAliasTemplateDecl *OldDecl = 0;
6875 TemplateParameterList *OldTemplateParams = 0;
6876
6877 if (TemplateParamLists.size() != 1) {
6878 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6879 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6880 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6881 }
6882 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6883
6884 // Only consider previous declarations in the same scope.
6885 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6886 /*ExplicitInstantiationOrSpecialization*/false);
6887 if (!Previous.empty()) {
6888 Redeclaration = true;
6889
6890 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6891 if (!OldDecl && !Invalid) {
6892 Diag(UsingLoc, diag::err_redefinition_different_kind)
6893 << Name.Identifier;
6894
6895 NamedDecl *OldD = Previous.getRepresentativeDecl();
6896 if (OldD->getLocation().isValid())
6897 Diag(OldD->getLocation(), diag::note_previous_definition);
6898
6899 Invalid = true;
6900 }
6901
6902 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6903 if (TemplateParameterListsAreEqual(TemplateParams,
6904 OldDecl->getTemplateParameters(),
6905 /*Complain=*/true,
6906 TPL_TemplateMatch))
6907 OldTemplateParams = OldDecl->getTemplateParameters();
6908 else
6909 Invalid = true;
6910
6911 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6912 if (!Invalid &&
6913 !Context.hasSameType(OldTD->getUnderlyingType(),
6914 NewTD->getUnderlyingType())) {
6915 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6916 // but we can't reasonably accept it.
6917 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6918 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6919 if (OldTD->getLocation().isValid())
6920 Diag(OldTD->getLocation(), diag::note_previous_definition);
6921 Invalid = true;
6922 }
6923 }
6924 }
6925
6926 // Merge any previous default template arguments into our parameters,
6927 // and check the parameter list.
6928 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6929 TPC_TypeAliasTemplate))
6930 return 0;
6931
6932 TypeAliasTemplateDecl *NewDecl =
6933 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6934 Name.Identifier, TemplateParams,
6935 NewTD);
6936
6937 NewDecl->setAccess(AS);
6938
6939 if (Invalid)
6940 NewDecl->setInvalidDecl();
6941 else if (OldDecl)
6942 NewDecl->setPreviousDeclaration(OldDecl);
6943
6944 NewND = NewDecl;
6945 } else {
6946 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6947 NewND = NewTD;
6948 }
Richard Smith162e1c12011-04-15 14:24:37 +00006949
6950 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006951 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006952
Richard Smith3e4c6c42011-05-05 21:57:07 +00006953 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006954}
6955
John McCalld226f652010-08-21 09:40:31 +00006956Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006957 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006958 SourceLocation AliasLoc,
6959 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006960 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006961 SourceLocation IdentLoc,
6962 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006963
Anders Carlsson81c85c42009-03-28 23:53:49 +00006964 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006965 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6966 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006967
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006968 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006969 NamedDecl *PrevDecl
6970 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6971 ForRedeclaration);
6972 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6973 PrevDecl = 0;
6974
6975 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006976 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006977 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006978 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006979 // FIXME: At some point, we'll want to create the (redundant)
6980 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006981 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006982 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006983 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006984 }
Mike Stump1eb44332009-09-09 15:08:12 +00006985
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006986 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6987 diag::err_redefinition_different_kind;
6988 Diag(AliasLoc, DiagID) << Alias;
6989 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006990 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006991 }
6992
John McCalla24dc2e2009-11-17 02:14:36 +00006993 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006994 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006995
John McCallf36e02d2009-10-09 21:13:30 +00006996 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006997 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006998 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006999 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007000 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007001 }
Mike Stump1eb44332009-09-09 15:08:12 +00007002
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007003 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007004 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007005 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007006 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007007
John McCall3dbd3d52010-02-16 06:53:13 +00007008 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007009 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007010}
7011
Douglas Gregor39957dc2010-05-01 15:04:51 +00007012namespace {
7013 /// \brief Scoped object used to handle the state changes required in Sema
7014 /// to implicitly define the body of a C++ member function;
7015 class ImplicitlyDefinedFunctionScope {
7016 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00007017 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00007018
7019 public:
7020 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00007021 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00007022 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00007023 S.PushFunctionScope();
7024 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
7025 }
7026
7027 ~ImplicitlyDefinedFunctionScope() {
7028 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00007029 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00007030 }
7031 };
7032}
7033
Sean Hunt001cad92011-05-10 00:49:42 +00007034Sema::ImplicitExceptionSpecification
7035Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007036 // C++ [except.spec]p14:
7037 // An implicitly declared special member function (Clause 12) shall have an
7038 // exception-specification. [...]
7039 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007040 if (ClassDecl->isInvalidDecl())
7041 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007042
Sebastian Redl60618fa2011-03-12 11:50:43 +00007043 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007044 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7045 BEnd = ClassDecl->bases_end();
7046 B != BEnd; ++B) {
7047 if (B->isVirtual()) // Handled below.
7048 continue;
7049
Douglas Gregor18274032010-07-03 00:47:00 +00007050 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7051 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007052 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7053 // If this is a deleted function, add it anyway. This might be conformant
7054 // with the standard. This might not. I'm not sure. It might not matter.
7055 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007056 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007057 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007058 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007059
7060 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007061 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7062 BEnd = ClassDecl->vbases_end();
7063 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007064 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7065 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007066 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7067 // If this is a deleted function, add it anyway. This might be conformant
7068 // with the standard. This might not. I'm not sure. It might not matter.
7069 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007070 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007071 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007072 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007073
7074 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007075 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7076 FEnd = ClassDecl->field_end();
7077 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007078 if (F->hasInClassInitializer()) {
7079 if (Expr *E = F->getInClassInitializer())
7080 ExceptSpec.CalledExpr(E);
7081 else if (!F->isInvalidDecl())
7082 ExceptSpec.SetDelayed();
7083 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007084 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007085 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7086 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7087 // If this is a deleted function, add it anyway. This might be conformant
7088 // with the standard. This might not. I'm not sure. It might not matter.
7089 // In particular, the problem is that this function never gets called. It
7090 // might just be ill-formed because this function attempts to refer to
7091 // a deleted function here.
7092 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007093 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007094 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007095 }
John McCalle23cf432010-12-14 08:05:40 +00007096
Sean Hunt001cad92011-05-10 00:49:42 +00007097 return ExceptSpec;
7098}
7099
7100CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7101 CXXRecordDecl *ClassDecl) {
7102 // C++ [class.ctor]p5:
7103 // A default constructor for a class X is a constructor of class X
7104 // that can be called without an argument. If there is no
7105 // user-declared constructor for class X, a default constructor is
7106 // implicitly declared. An implicitly-declared default constructor
7107 // is an inline public member of its class.
7108 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7109 "Should not build implicit default constructor!");
7110
7111 ImplicitExceptionSpecification Spec =
7112 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7113 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00007114
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007115 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007116 CanQualType ClassType
7117 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007118 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007119 DeclarationName Name
7120 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007121 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007122 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7123 Context, ClassDecl, ClassLoc, NameInfo,
7124 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7125 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7126 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7127 getLangOptions().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007128 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007129 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007130 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00007131 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00007132
7133 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007134 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7135
Douglas Gregor23c94db2010-07-02 17:43:08 +00007136 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007137 PushOnScopeChains(DefaultCon, S, false);
7138 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007139
Sean Hunte16da072011-10-10 06:18:57 +00007140 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00007141 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00007142
Douglas Gregor32df23e2010-07-01 22:02:46 +00007143 return DefaultCon;
7144}
7145
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007146void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7147 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007148 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007149 !Constructor->doesThisDeclarationHaveABody() &&
7150 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007151 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007152
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007153 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007154 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007155
Douglas Gregor39957dc2010-05-01 15:04:51 +00007156 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007157 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007158 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007159 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007160 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007161 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007162 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007163 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007164 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007165
7166 SourceLocation Loc = Constructor->getLocation();
7167 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7168
7169 Constructor->setUsed();
7170 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007171
7172 if (ASTMutationListener *L = getASTMutationListener()) {
7173 L->CompletedImplicitDefinition(Constructor);
7174 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007175}
7176
Richard Smith7a614d82011-06-11 17:19:42 +00007177/// Get any existing defaulted default constructor for the given class. Do not
7178/// implicitly define one if it does not exist.
7179static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7180 CXXRecordDecl *D) {
7181 ASTContext &Context = Self.Context;
7182 QualType ClassType = Context.getTypeDeclType(D);
7183 DeclarationName ConstructorName
7184 = Context.DeclarationNames.getCXXConstructorName(
7185 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7186
7187 DeclContext::lookup_const_iterator Con, ConEnd;
7188 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7189 Con != ConEnd; ++Con) {
7190 // A function template cannot be defaulted.
7191 if (isa<FunctionTemplateDecl>(*Con))
7192 continue;
7193
7194 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7195 if (Constructor->isDefaultConstructor())
7196 return Constructor->isDefaulted() ? Constructor : 0;
7197 }
7198 return 0;
7199}
7200
7201void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7202 if (!D) return;
7203 AdjustDeclIfTemplate(D);
7204
7205 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7206 CXXConstructorDecl *CtorDecl
7207 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7208
7209 if (!CtorDecl) return;
7210
7211 // Compute the exception specification for the default constructor.
7212 const FunctionProtoType *CtorTy =
7213 CtorDecl->getType()->castAs<FunctionProtoType>();
7214 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7215 ImplicitExceptionSpecification Spec =
7216 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7217 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7218 assert(EPI.ExceptionSpecType != EST_Delayed);
7219
7220 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7221 }
7222
7223 // If the default constructor is explicitly defaulted, checking the exception
7224 // specification is deferred until now.
7225 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7226 !ClassDecl->isDependentType())
7227 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7228}
7229
Sebastian Redlf677ea32011-02-05 19:23:19 +00007230void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7231 // We start with an initial pass over the base classes to collect those that
7232 // inherit constructors from. If there are none, we can forgo all further
7233 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007234 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007235 BasesVector BasesToInheritFrom;
7236 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7237 BaseE = ClassDecl->bases_end();
7238 BaseIt != BaseE; ++BaseIt) {
7239 if (BaseIt->getInheritConstructors()) {
7240 QualType Base = BaseIt->getType();
7241 if (Base->isDependentType()) {
7242 // If we inherit constructors from anything that is dependent, just
7243 // abort processing altogether. We'll get another chance for the
7244 // instantiations.
7245 return;
7246 }
7247 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7248 }
7249 }
7250 if (BasesToInheritFrom.empty())
7251 return;
7252
7253 // Now collect the constructors that we already have in the current class.
7254 // Those take precedence over inherited constructors.
7255 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7256 // unless there is a user-declared constructor with the same signature in
7257 // the class where the using-declaration appears.
7258 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7259 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7260 CtorE = ClassDecl->ctor_end();
7261 CtorIt != CtorE; ++CtorIt) {
7262 ExistingConstructors.insert(
7263 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7264 }
7265
7266 Scope *S = getScopeForContext(ClassDecl);
7267 DeclarationName CreatedCtorName =
7268 Context.DeclarationNames.getCXXConstructorName(
7269 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7270
7271 // Now comes the true work.
7272 // First, we keep a map from constructor types to the base that introduced
7273 // them. Needed for finding conflicting constructors. We also keep the
7274 // actually inserted declarations in there, for pretty diagnostics.
7275 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7276 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7277 ConstructorToSourceMap InheritedConstructors;
7278 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7279 BaseE = BasesToInheritFrom.end();
7280 BaseIt != BaseE; ++BaseIt) {
7281 const RecordType *Base = *BaseIt;
7282 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7283 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7284 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7285 CtorE = BaseDecl->ctor_end();
7286 CtorIt != CtorE; ++CtorIt) {
7287 // Find the using declaration for inheriting this base's constructors.
7288 DeclarationName Name =
7289 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7290 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7291 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7292 SourceLocation UsingLoc = UD ? UD->getLocation() :
7293 ClassDecl->getLocation();
7294
7295 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7296 // from the class X named in the using-declaration consists of actual
7297 // constructors and notional constructors that result from the
7298 // transformation of defaulted parameters as follows:
7299 // - all non-template default constructors of X, and
7300 // - for each non-template constructor of X that has at least one
7301 // parameter with a default argument, the set of constructors that
7302 // results from omitting any ellipsis parameter specification and
7303 // successively omitting parameters with a default argument from the
7304 // end of the parameter-type-list.
7305 CXXConstructorDecl *BaseCtor = *CtorIt;
7306 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7307 const FunctionProtoType *BaseCtorType =
7308 BaseCtor->getType()->getAs<FunctionProtoType>();
7309
7310 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7311 maxParams = BaseCtor->getNumParams();
7312 params <= maxParams; ++params) {
7313 // Skip default constructors. They're never inherited.
7314 if (params == 0)
7315 continue;
7316 // Skip copy and move constructors for the same reason.
7317 if (CanBeCopyOrMove && params == 1)
7318 continue;
7319
7320 // Build up a function type for this particular constructor.
7321 // FIXME: The working paper does not consider that the exception spec
7322 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007323 // source. This code doesn't yet, either. When it does, this code will
7324 // need to be delayed until after exception specifications and in-class
7325 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007326 const Type *NewCtorType;
7327 if (params == maxParams)
7328 NewCtorType = BaseCtorType;
7329 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007330 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007331 for (unsigned i = 0; i < params; ++i) {
7332 Args.push_back(BaseCtorType->getArgType(i));
7333 }
7334 FunctionProtoType::ExtProtoInfo ExtInfo =
7335 BaseCtorType->getExtProtoInfo();
7336 ExtInfo.Variadic = false;
7337 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7338 Args.data(), params, ExtInfo)
7339 .getTypePtr();
7340 }
7341 const Type *CanonicalNewCtorType =
7342 Context.getCanonicalType(NewCtorType);
7343
7344 // Now that we have the type, first check if the class already has a
7345 // constructor with this signature.
7346 if (ExistingConstructors.count(CanonicalNewCtorType))
7347 continue;
7348
7349 // Then we check if we have already declared an inherited constructor
7350 // with this signature.
7351 std::pair<ConstructorToSourceMap::iterator, bool> result =
7352 InheritedConstructors.insert(std::make_pair(
7353 CanonicalNewCtorType,
7354 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7355 if (!result.second) {
7356 // Already in the map. If it came from a different class, that's an
7357 // error. Not if it's from the same.
7358 CanQualType PreviousBase = result.first->second.first;
7359 if (CanonicalBase != PreviousBase) {
7360 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7361 const CXXConstructorDecl *PrevBaseCtor =
7362 PrevCtor->getInheritedConstructor();
7363 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7364
7365 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7366 Diag(BaseCtor->getLocation(),
7367 diag::note_using_decl_constructor_conflict_current_ctor);
7368 Diag(PrevBaseCtor->getLocation(),
7369 diag::note_using_decl_constructor_conflict_previous_ctor);
7370 Diag(PrevCtor->getLocation(),
7371 diag::note_using_decl_constructor_conflict_previous_using);
7372 }
7373 continue;
7374 }
7375
7376 // OK, we're there, now add the constructor.
7377 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007378 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007379 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7380 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007381 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7382 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007383 /*ImplicitlyDeclared=*/true,
7384 // FIXME: Due to a defect in the standard, we treat inherited
7385 // constructors as constexpr even if that makes them ill-formed.
7386 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007387 NewCtor->setAccess(BaseCtor->getAccess());
7388
7389 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007390 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007391 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007392 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7393 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007394 /*IdentifierInfo=*/0,
7395 BaseCtorType->getArgType(i),
7396 /*TInfo=*/0, SC_None,
7397 SC_None, /*DefaultArg=*/0));
7398 }
David Blaikie4278c652011-09-21 18:16:56 +00007399 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007400 NewCtor->setInheritedConstructor(BaseCtor);
7401
7402 PushOnScopeChains(NewCtor, S, false);
7403 ClassDecl->addDecl(NewCtor);
7404 result.first->second.second = NewCtor;
7405 }
7406 }
7407 }
7408}
7409
Sean Huntcb45a0f2011-05-12 22:46:25 +00007410Sema::ImplicitExceptionSpecification
7411Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007412 // C++ [except.spec]p14:
7413 // An implicitly declared special member function (Clause 12) shall have
7414 // an exception-specification.
7415 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007416 if (ClassDecl->isInvalidDecl())
7417 return ExceptSpec;
7418
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007419 // Direct base-class destructors.
7420 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7421 BEnd = ClassDecl->bases_end();
7422 B != BEnd; ++B) {
7423 if (B->isVirtual()) // Handled below.
7424 continue;
7425
7426 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7427 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007428 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007429 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007430
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007431 // Virtual base-class destructors.
7432 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7433 BEnd = ClassDecl->vbases_end();
7434 B != BEnd; ++B) {
7435 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7436 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007437 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007438 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007439
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007440 // Field destructors.
7441 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7442 FEnd = ClassDecl->field_end();
7443 F != FEnd; ++F) {
7444 if (const RecordType *RecordTy
7445 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7446 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007447 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007448 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007449
Sean Huntcb45a0f2011-05-12 22:46:25 +00007450 return ExceptSpec;
7451}
7452
7453CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7454 // C++ [class.dtor]p2:
7455 // If a class has no user-declared destructor, a destructor is
7456 // declared implicitly. An implicitly-declared destructor is an
7457 // inline public member of its class.
7458
7459 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007460 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007461 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7462
Douglas Gregor4923aa22010-07-02 20:37:36 +00007463 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007464 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007465
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007466 CanQualType ClassType
7467 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007468 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007469 DeclarationName Name
7470 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007471 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007472 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007473 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7474 /*isInline=*/true,
7475 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007476 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007477 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007478 Destructor->setImplicit();
7479 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007480
7481 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007482 ++ASTContext::NumImplicitDestructorsDeclared;
7483
7484 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007485 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007486 PushOnScopeChains(Destructor, S, false);
7487 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007488
7489 // This could be uniqued if it ever proves significant.
7490 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007491
7492 if (ShouldDeleteDestructor(Destructor))
7493 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007494
7495 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00007496
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007497 return Destructor;
7498}
7499
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007500void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007501 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007502 assert((Destructor->isDefaulted() &&
7503 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007504 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007505 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007506 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007507
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007508 if (Destructor->isInvalidDecl())
7509 return;
7510
Douglas Gregor39957dc2010-05-01 15:04:51 +00007511 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007512
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007513 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007514 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7515 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007516
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007517 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007518 Diag(CurrentLocation, diag::note_member_synthesized_at)
7519 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7520
7521 Destructor->setInvalidDecl();
7522 return;
7523 }
7524
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007525 SourceLocation Loc = Destructor->getLocation();
7526 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007527 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007528 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007529 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007530
7531 if (ASTMutationListener *L = getASTMutationListener()) {
7532 L->CompletedImplicitDefinition(Destructor);
7533 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007534}
7535
Sebastian Redl0ee33912011-05-19 05:13:44 +00007536void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7537 CXXDestructorDecl *destructor) {
7538 // C++11 [class.dtor]p3:
7539 // A declaration of a destructor that does not have an exception-
7540 // specification is implicitly considered to have the same exception-
7541 // specification as an implicit declaration.
7542 const FunctionProtoType *dtorType = destructor->getType()->
7543 getAs<FunctionProtoType>();
7544 if (dtorType->hasExceptionSpec())
7545 return;
7546
7547 ImplicitExceptionSpecification exceptSpec =
7548 ComputeDefaultedDtorExceptionSpec(classDecl);
7549
Chandler Carruth3f224b22011-09-20 04:55:26 +00007550 // Replace the destructor's type, building off the existing one. Fortunately,
7551 // the only thing of interest in the destructor type is its extended info.
7552 // The return and arguments are fixed.
7553 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007554 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7555 epi.NumExceptions = exceptSpec.size();
7556 epi.Exceptions = exceptSpec.data();
7557 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7558
7559 destructor->setType(ty);
7560
7561 // FIXME: If the destructor has a body that could throw, and the newly created
7562 // spec doesn't allow exceptions, we should emit a warning, because this
7563 // change in behavior can break conforming C++03 programs at runtime.
7564 // However, we don't have a body yet, so it needs to be done somewhere else.
7565}
7566
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007567/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007568/// \c To.
7569///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007570/// This routine is used to copy/move the members of a class with an
7571/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007572/// copied are arrays, this routine builds for loops to copy them.
7573///
7574/// \param S The Sema object used for type-checking.
7575///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007576/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007577///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007578/// \param T The type of the expressions being copied/moved. Both expressions
7579/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007580///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007581/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007582///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007583/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007584///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007585/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007586/// Otherwise, it's a non-static member subobject.
7587///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007588/// \param Copying Whether we're copying or moving.
7589///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007590/// \param Depth Internal parameter recording the depth of the recursion.
7591///
7592/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007593static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007594BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007595 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007596 bool CopyingBaseSubobject, bool Copying,
7597 unsigned Depth = 0) {
7598 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007599 // Each subobject is assigned in the manner appropriate to its type:
7600 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007601 // - if the subobject is of class type, as if by a call to operator= with
7602 // the subobject as the object expression and the corresponding
7603 // subobject of x as a single function argument (as if by explicit
7604 // qualification; that is, ignoring any possible virtual overriding
7605 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007606 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7607 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7608
7609 // Look for operator=.
7610 DeclarationName Name
7611 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7612 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7613 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7614
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007615 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007616 LookupResult::Filter F = OpLookup.makeFilter();
7617 while (F.hasNext()) {
7618 NamedDecl *D = F.next();
7619 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007620 if (Copying ? Method->isCopyAssignmentOperator() :
7621 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007622 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007623
Douglas Gregor06a9f362010-05-01 20:49:11 +00007624 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007625 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007626 F.done();
7627
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007628 // Suppress the protected check (C++ [class.protected]) for each of the
7629 // assignment operators we found. This strange dance is required when
7630 // we're assigning via a base classes's copy-assignment operator. To
7631 // ensure that we're getting the right base class subobject (without
7632 // ambiguities), we need to cast "this" to that subobject type; to
7633 // ensure that we don't go through the virtual call mechanism, we need
7634 // to qualify the operator= name with the base class (see below). However,
7635 // this means that if the base class has a protected copy assignment
7636 // operator, the protected member access check will fail. So, we
7637 // rewrite "protected" access to "public" access in this case, since we
7638 // know by construction that we're calling from a derived class.
7639 if (CopyingBaseSubobject) {
7640 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7641 L != LEnd; ++L) {
7642 if (L.getAccess() == AS_protected)
7643 L.setAccess(AS_public);
7644 }
7645 }
7646
Douglas Gregor06a9f362010-05-01 20:49:11 +00007647 // Create the nested-name-specifier that will be used to qualify the
7648 // reference to operator=; this is required to suppress the virtual
7649 // call mechanism.
7650 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007651 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007652 SS.MakeTrivial(S.Context,
7653 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007654 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007655 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007656
7657 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007658 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007659 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007660 /*TemplateKWLoc=*/SourceLocation(),
7661 /*FirstQualifierInScope=*/0,
7662 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007663 /*TemplateArgs=*/0,
7664 /*SuppressQualifierCheck=*/true);
7665 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007666 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007667
7668 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007669
John McCall60d7b3a2010-08-24 06:29:42 +00007670 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007671 OpEqualRef.takeAs<Expr>(),
7672 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007673 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007674 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007675
7676 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007677 }
John McCallb0207482010-03-16 06:11:48 +00007678
Douglas Gregor06a9f362010-05-01 20:49:11 +00007679 // - if the subobject is of scalar type, the built-in assignment
7680 // operator is used.
7681 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7682 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007683 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007684 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007685 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007686
7687 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007688 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007689
7690 // - if the subobject is an array, each element is assigned, in the
7691 // manner appropriate to the element type;
7692
7693 // Construct a loop over the array bounds, e.g.,
7694 //
7695 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7696 //
7697 // that will copy each of the array elements.
7698 QualType SizeType = S.Context.getSizeType();
7699
7700 // Create the iteration variable.
7701 IdentifierInfo *IterationVarName = 0;
7702 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007703 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007704 llvm::raw_svector_ostream OS(Str);
7705 OS << "__i" << Depth;
7706 IterationVarName = &S.Context.Idents.get(OS.str());
7707 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007708 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007709 IterationVarName, SizeType,
7710 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007711 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007712
7713 // Initialize the iteration variable to zero.
7714 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007715 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007716
7717 // Create a reference to the iteration variable; we'll use this several
7718 // times throughout.
7719 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007720 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007721 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007722 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7723 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7724
Douglas Gregor06a9f362010-05-01 20:49:11 +00007725 // Create the DeclStmt that holds the iteration variable.
7726 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7727
7728 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007729 llvm::APInt Upper
7730 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007731 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007732 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007733 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7734 BO_NE, S.Context.BoolTy,
7735 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007736
7737 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007738 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007739 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7740 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007741
7742 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007743 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007744 IterationVarRefRVal,
7745 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007746 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007747 IterationVarRefRVal,
7748 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007749 if (!Copying) // Cast to rvalue
7750 From = CastForMoving(S, From);
7751
7752 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007753 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7754 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007755 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007756 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007757 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007758
7759 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007760 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007761 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007762 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007763 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007764}
7765
Sean Hunt30de05c2011-05-14 05:23:20 +00007766std::pair<Sema::ImplicitExceptionSpecification, bool>
7767Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7768 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007769 if (ClassDecl->isInvalidDecl())
7770 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7771
Douglas Gregord3c35902010-07-01 16:36:15 +00007772 // C++ [class.copy]p10:
7773 // If the class definition does not explicitly declare a copy
7774 // assignment operator, one is declared implicitly.
7775 // The implicitly-defined copy assignment operator for a class X
7776 // will have the form
7777 //
7778 // X& X::operator=(const X&)
7779 //
7780 // if
7781 bool HasConstCopyAssignment = true;
7782
7783 // -- each direct base class B of X has a copy assignment operator
7784 // whose parameter is of type const B&, const volatile B& or B,
7785 // and
7786 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7787 BaseEnd = ClassDecl->bases_end();
7788 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007789 // We'll handle this below
7790 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7791 continue;
7792
Douglas Gregord3c35902010-07-01 16:36:15 +00007793 assert(!Base->getType()->isDependentType() &&
7794 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007795 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7796 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7797 &HasConstCopyAssignment);
7798 }
7799
Richard Smithebaf0e62011-10-18 20:49:44 +00007800 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007801 if (LangOpts.CPlusPlus0x) {
7802 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7803 BaseEnd = ClassDecl->vbases_end();
7804 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7805 assert(!Base->getType()->isDependentType() &&
7806 "Cannot generate implicit members for class with dependent bases.");
7807 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7808 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7809 &HasConstCopyAssignment);
7810 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007811 }
7812
7813 // -- for all the nonstatic data members of X that are of a class
7814 // type M (or array thereof), each such class type has a copy
7815 // assignment operator whose parameter is of type const M&,
7816 // const volatile M& or M.
7817 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7818 FieldEnd = ClassDecl->field_end();
7819 HasConstCopyAssignment && Field != FieldEnd;
7820 ++Field) {
7821 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007822 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7823 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7824 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007825 }
7826 }
7827
7828 // Otherwise, the implicitly declared copy assignment operator will
7829 // have the form
7830 //
7831 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007832
Douglas Gregorb87786f2010-07-01 17:48:08 +00007833 // C++ [except.spec]p14:
7834 // An implicitly declared special member function (Clause 12) shall have an
7835 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007836
7837 // It is unspecified whether or not an implicit copy assignment operator
7838 // attempts to deduplicate calls to assignment operators of virtual bases are
7839 // made. As such, this exception specification is effectively unspecified.
7840 // Based on a similar decision made for constness in C++0x, we're erring on
7841 // the side of assuming such calls to be made regardless of whether they
7842 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007843 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007844 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007845 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7846 BaseEnd = ClassDecl->bases_end();
7847 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007848 if (Base->isVirtual())
7849 continue;
7850
Douglas Gregora376d102010-07-02 21:50:04 +00007851 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007852 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007853 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7854 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007855 ExceptSpec.CalledDecl(CopyAssign);
7856 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007857
7858 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7859 BaseEnd = ClassDecl->vbases_end();
7860 Base != BaseEnd; ++Base) {
7861 CXXRecordDecl *BaseClassDecl
7862 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7863 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7864 ArgQuals, false, 0))
7865 ExceptSpec.CalledDecl(CopyAssign);
7866 }
7867
Douglas Gregorb87786f2010-07-01 17:48:08 +00007868 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7869 FieldEnd = ClassDecl->field_end();
7870 Field != FieldEnd;
7871 ++Field) {
7872 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007873 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7874 if (CXXMethodDecl *CopyAssign =
7875 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7876 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007877 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007878 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007879
Sean Hunt30de05c2011-05-14 05:23:20 +00007880 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7881}
7882
7883CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7884 // Note: The following rules are largely analoguous to the copy
7885 // constructor rules. Note that virtual bases are not taken into account
7886 // for determining the argument type of the operator. Note also that
7887 // operators taking an object instead of a reference are allowed.
7888
7889 ImplicitExceptionSpecification Spec(Context);
7890 bool Const;
7891 llvm::tie(Spec, Const) =
7892 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7893
7894 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7895 QualType RetType = Context.getLValueReferenceType(ArgType);
7896 if (Const)
7897 ArgType = ArgType.withConst();
7898 ArgType = Context.getLValueReferenceType(ArgType);
7899
Douglas Gregord3c35902010-07-01 16:36:15 +00007900 // An implicitly-declared copy assignment operator is an inline public
7901 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007902 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007903 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007904 SourceLocation ClassLoc = ClassDecl->getLocation();
7905 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007906 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007907 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007908 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007909 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007910 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007911 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007912 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007913 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007914 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007915 CopyAssignment->setImplicit();
7916 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007917
7918 // Add the parameter to the operator.
7919 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007920 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007921 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007922 SC_None,
7923 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007924 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007925
Douglas Gregora376d102010-07-02 21:50:04 +00007926 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007927 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007928
Douglas Gregor23c94db2010-07-02 17:43:08 +00007929 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007930 PushOnScopeChains(CopyAssignment, S, false);
7931 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007932
Nico Weberafcc96a2012-01-23 03:19:29 +00007933 // C++0x [class.copy]p19:
7934 // .... If the class definition does not explicitly declare a copy
7935 // assignment operator, there is no user-declared move constructor, and
7936 // there is no user-declared move assignment operator, a copy assignment
7937 // operator is implicitly declared as defaulted.
7938 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber28976602012-01-23 04:01:33 +00007939 !getLangOptions().MicrosoftMode) ||
7940 ClassDecl->hasUserDeclaredMoveAssignment() ||
Sean Hunt1ccbc542011-06-22 01:05:13 +00007941 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007942 CopyAssignment->setDeletedAsWritten();
7943
Douglas Gregord3c35902010-07-01 16:36:15 +00007944 AddOverriddenMethods(ClassDecl, CopyAssignment);
7945 return CopyAssignment;
7946}
7947
Douglas Gregor06a9f362010-05-01 20:49:11 +00007948void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7949 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007950 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007951 CopyAssignOperator->isOverloadedOperator() &&
7952 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007953 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007954 "DefineImplicitCopyAssignment called for wrong function");
7955
7956 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7957
7958 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7959 CopyAssignOperator->setInvalidDecl();
7960 return;
7961 }
7962
7963 CopyAssignOperator->setUsed();
7964
7965 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007966 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007967
7968 // C++0x [class.copy]p30:
7969 // The implicitly-defined or explicitly-defaulted copy assignment operator
7970 // for a non-union class X performs memberwise copy assignment of its
7971 // subobjects. The direct base classes of X are assigned first, in the
7972 // order of their declaration in the base-specifier-list, and then the
7973 // immediate non-static data members of X are assigned, in the order in
7974 // which they were declared in the class definition.
7975
7976 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007977 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007978
7979 // The parameter for the "other" object, which we are copying from.
7980 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7981 Qualifiers OtherQuals = Other->getType().getQualifiers();
7982 QualType OtherRefType = Other->getType();
7983 if (const LValueReferenceType *OtherRef
7984 = OtherRefType->getAs<LValueReferenceType>()) {
7985 OtherRefType = OtherRef->getPointeeType();
7986 OtherQuals = OtherRefType.getQualifiers();
7987 }
7988
7989 // Our location for everything implicitly-generated.
7990 SourceLocation Loc = CopyAssignOperator->getLocation();
7991
7992 // Construct a reference to the "other" object. We'll be using this
7993 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007994 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007995 assert(OtherRef && "Reference to parameter cannot fail!");
7996
7997 // Construct the "this" pointer. We'll be using this throughout the generated
7998 // ASTs.
7999 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8000 assert(This && "Reference to this cannot fail!");
8001
8002 // Assign base classes.
8003 bool Invalid = false;
8004 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8005 E = ClassDecl->bases_end(); Base != E; ++Base) {
8006 // Form the assignment:
8007 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8008 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008009 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008010 Invalid = true;
8011 continue;
8012 }
8013
John McCallf871d0c2010-08-07 06:22:56 +00008014 CXXCastPath BasePath;
8015 BasePath.push_back(Base);
8016
Douglas Gregor06a9f362010-05-01 20:49:11 +00008017 // Construct the "from" expression, which is an implicit cast to the
8018 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008019 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008020 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8021 CK_UncheckedDerivedToBase,
8022 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008023
8024 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008025 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008026
8027 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008028 To = ImpCastExprToType(To.take(),
8029 Context.getCVRQualifiedType(BaseType,
8030 CopyAssignOperator->getTypeQualifiers()),
8031 CK_UncheckedDerivedToBase,
8032 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008033
8034 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00008035 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008036 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008037 /*CopyingBaseSubobject=*/true,
8038 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008039 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008040 Diag(CurrentLocation, diag::note_member_synthesized_at)
8041 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8042 CopyAssignOperator->setInvalidDecl();
8043 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008044 }
8045
8046 // Success! Record the copy.
8047 Statements.push_back(Copy.takeAs<Expr>());
8048 }
8049
8050 // \brief Reference to the __builtin_memcpy function.
8051 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008052 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008053 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008054
8055 // Assign non-static members.
8056 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8057 FieldEnd = ClassDecl->field_end();
8058 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008059 if (Field->isUnnamedBitfield())
8060 continue;
8061
Douglas Gregor06a9f362010-05-01 20:49:11 +00008062 // Check for members of reference type; we can't copy those.
8063 if (Field->getType()->isReferenceType()) {
8064 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8065 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8066 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008067 Diag(CurrentLocation, diag::note_member_synthesized_at)
8068 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008069 Invalid = true;
8070 continue;
8071 }
8072
8073 // Check for members of const-qualified, non-class type.
8074 QualType BaseType = Context.getBaseElementType(Field->getType());
8075 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8076 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8077 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8078 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008079 Diag(CurrentLocation, diag::note_member_synthesized_at)
8080 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008081 Invalid = true;
8082 continue;
8083 }
John McCallb77115d2011-06-17 00:18:42 +00008084
8085 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008086 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8087 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008088
8089 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008090 if (FieldType->isIncompleteArrayType()) {
8091 assert(ClassDecl->hasFlexibleArrayMember() &&
8092 "Incomplete array type is not valid");
8093 continue;
8094 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008095
8096 // Build references to the field in the object we're copying from and to.
8097 CXXScopeSpec SS; // Intentionally empty
8098 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8099 LookupMemberName);
8100 MemberLookup.addDecl(*Field);
8101 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008102 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008103 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008104 SS, SourceLocation(), 0,
8105 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008106 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008107 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008108 SS, SourceLocation(), 0,
8109 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008110 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8111 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8112
8113 // If the field should be copied with __builtin_memcpy rather than via
8114 // explicit assignments, do so. This optimization only applies for arrays
8115 // of scalars and arrays of class type with trivial copy-assignment
8116 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00008117 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008118 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008119 // Compute the size of the memory buffer to be copied.
8120 QualType SizeType = Context.getSizeType();
8121 llvm::APInt Size(Context.getTypeSize(SizeType),
8122 Context.getTypeSizeInChars(BaseType).getQuantity());
8123 for (const ConstantArrayType *Array
8124 = Context.getAsConstantArrayType(FieldType);
8125 Array;
8126 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00008127 llvm::APInt ArraySize
8128 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008129 Size *= ArraySize;
8130 }
8131
8132 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00008133 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8134 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008135
8136 bool NeedsCollectableMemCpy =
8137 (BaseType->isRecordType() &&
8138 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8139
8140 if (NeedsCollectableMemCpy) {
8141 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008142 // Create a reference to the __builtin_objc_memmove_collectable function.
8143 LookupResult R(*this,
8144 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008145 Loc, LookupOrdinaryName);
8146 LookupName(R, TUScope, true);
8147
8148 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8149 if (!CollectableMemCpy) {
8150 // Something went horribly wrong earlier, and we will have
8151 // complained about it.
8152 Invalid = true;
8153 continue;
8154 }
8155
8156 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8157 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008158 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008159 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8160 }
8161 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008162 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008163 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008164 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8165 LookupOrdinaryName);
8166 LookupName(R, TUScope, true);
8167
8168 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8169 if (!BuiltinMemCpy) {
8170 // Something went horribly wrong earlier, and we will have complained
8171 // about it.
8172 Invalid = true;
8173 continue;
8174 }
8175
8176 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8177 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008178 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008179 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8180 }
8181
John McCallca0408f2010-08-23 06:44:23 +00008182 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008183 CallArgs.push_back(To.takeAs<Expr>());
8184 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008185 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00008186 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008187 if (NeedsCollectableMemCpy)
8188 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008189 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008190 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008191 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008192 else
8193 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008194 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008195 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008196 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008197
Douglas Gregor06a9f362010-05-01 20:49:11 +00008198 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8199 Statements.push_back(Call.takeAs<Expr>());
8200 continue;
8201 }
8202
8203 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00008204 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008205 To.get(), From.get(),
8206 /*CopyingBaseSubobject=*/false,
8207 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008208 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008209 Diag(CurrentLocation, diag::note_member_synthesized_at)
8210 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8211 CopyAssignOperator->setInvalidDecl();
8212 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008213 }
8214
8215 // Success! Record the copy.
8216 Statements.push_back(Copy.takeAs<Stmt>());
8217 }
8218
8219 if (!Invalid) {
8220 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008221 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008222
John McCall60d7b3a2010-08-24 06:29:42 +00008223 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008224 if (Return.isInvalid())
8225 Invalid = true;
8226 else {
8227 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008228
8229 if (Trap.hasErrorOccurred()) {
8230 Diag(CurrentLocation, diag::note_member_synthesized_at)
8231 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8232 Invalid = true;
8233 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008234 }
8235 }
8236
8237 if (Invalid) {
8238 CopyAssignOperator->setInvalidDecl();
8239 return;
8240 }
8241
John McCall60d7b3a2010-08-24 06:29:42 +00008242 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00008243 /*isStmtExpr=*/false);
8244 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8245 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008246
8247 if (ASTMutationListener *L = getASTMutationListener()) {
8248 L->CompletedImplicitDefinition(CopyAssignOperator);
8249 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008250}
8251
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008252Sema::ImplicitExceptionSpecification
8253Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8254 ImplicitExceptionSpecification ExceptSpec(Context);
8255
8256 if (ClassDecl->isInvalidDecl())
8257 return ExceptSpec;
8258
8259 // C++0x [except.spec]p14:
8260 // An implicitly declared special member function (Clause 12) shall have an
8261 // exception-specification. [...]
8262
8263 // It is unspecified whether or not an implicit move assignment operator
8264 // attempts to deduplicate calls to assignment operators of virtual bases are
8265 // made. As such, this exception specification is effectively unspecified.
8266 // Based on a similar decision made for constness in C++0x, we're erring on
8267 // the side of assuming such calls to be made regardless of whether they
8268 // actually happen.
8269 // Note that a move constructor is not implicitly declared when there are
8270 // virtual bases, but it can still be user-declared and explicitly defaulted.
8271 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8272 BaseEnd = ClassDecl->bases_end();
8273 Base != BaseEnd; ++Base) {
8274 if (Base->isVirtual())
8275 continue;
8276
8277 CXXRecordDecl *BaseClassDecl
8278 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8279 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8280 false, 0))
8281 ExceptSpec.CalledDecl(MoveAssign);
8282 }
8283
8284 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8285 BaseEnd = ClassDecl->vbases_end();
8286 Base != BaseEnd; ++Base) {
8287 CXXRecordDecl *BaseClassDecl
8288 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8289 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8290 false, 0))
8291 ExceptSpec.CalledDecl(MoveAssign);
8292 }
8293
8294 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8295 FieldEnd = ClassDecl->field_end();
8296 Field != FieldEnd;
8297 ++Field) {
8298 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8299 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8300 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8301 false, 0))
8302 ExceptSpec.CalledDecl(MoveAssign);
8303 }
8304 }
8305
8306 return ExceptSpec;
8307}
8308
8309CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8310 // Note: The following rules are largely analoguous to the move
8311 // constructor rules.
8312
8313 ImplicitExceptionSpecification Spec(
8314 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8315
8316 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8317 QualType RetType = Context.getLValueReferenceType(ArgType);
8318 ArgType = Context.getRValueReferenceType(ArgType);
8319
8320 // An implicitly-declared move assignment operator is an inline public
8321 // member of its class.
8322 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8323 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8324 SourceLocation ClassLoc = ClassDecl->getLocation();
8325 DeclarationNameInfo NameInfo(Name, ClassLoc);
8326 CXXMethodDecl *MoveAssignment
8327 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8328 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8329 /*TInfo=*/0, /*isStatic=*/false,
8330 /*StorageClassAsWritten=*/SC_None,
8331 /*isInline=*/true,
8332 /*isConstexpr=*/false,
8333 SourceLocation());
8334 MoveAssignment->setAccess(AS_public);
8335 MoveAssignment->setDefaulted();
8336 MoveAssignment->setImplicit();
8337 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8338
8339 // Add the parameter to the operator.
8340 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8341 ClassLoc, ClassLoc, /*Id=*/0,
8342 ArgType, /*TInfo=*/0,
8343 SC_None,
8344 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008345 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008346
8347 // Note that we have added this copy-assignment operator.
8348 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8349
8350 // C++0x [class.copy]p9:
8351 // If the definition of a class X does not explicitly declare a move
8352 // assignment operator, one will be implicitly declared as defaulted if and
8353 // only if:
8354 // [...]
8355 // - the move assignment operator would not be implicitly defined as
8356 // deleted.
8357 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8358 // Cache this result so that we don't try to generate this over and over
8359 // on every lookup, leaking memory and wasting time.
8360 ClassDecl->setFailedImplicitMoveAssignment();
8361 return 0;
8362 }
8363
8364 if (Scope *S = getScopeForContext(ClassDecl))
8365 PushOnScopeChains(MoveAssignment, S, false);
8366 ClassDecl->addDecl(MoveAssignment);
8367
8368 AddOverriddenMethods(ClassDecl, MoveAssignment);
8369 return MoveAssignment;
8370}
8371
8372void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8373 CXXMethodDecl *MoveAssignOperator) {
8374 assert((MoveAssignOperator->isDefaulted() &&
8375 MoveAssignOperator->isOverloadedOperator() &&
8376 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8377 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8378 "DefineImplicitMoveAssignment called for wrong function");
8379
8380 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8381
8382 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8383 MoveAssignOperator->setInvalidDecl();
8384 return;
8385 }
8386
8387 MoveAssignOperator->setUsed();
8388
8389 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8390 DiagnosticErrorTrap Trap(Diags);
8391
8392 // C++0x [class.copy]p28:
8393 // The implicitly-defined or move assignment operator for a non-union class
8394 // X performs memberwise move assignment of its subobjects. The direct base
8395 // classes of X are assigned first, in the order of their declaration in the
8396 // base-specifier-list, and then the immediate non-static data members of X
8397 // are assigned, in the order in which they were declared in the class
8398 // definition.
8399
8400 // The statements that form the synthesized function body.
8401 ASTOwningVector<Stmt*> Statements(*this);
8402
8403 // The parameter for the "other" object, which we are move from.
8404 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8405 QualType OtherRefType = Other->getType()->
8406 getAs<RValueReferenceType>()->getPointeeType();
8407 assert(OtherRefType.getQualifiers() == 0 &&
8408 "Bad argument type of defaulted move assignment");
8409
8410 // Our location for everything implicitly-generated.
8411 SourceLocation Loc = MoveAssignOperator->getLocation();
8412
8413 // Construct a reference to the "other" object. We'll be using this
8414 // throughout the generated ASTs.
8415 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8416 assert(OtherRef && "Reference to parameter cannot fail!");
8417 // Cast to rvalue.
8418 OtherRef = CastForMoving(*this, OtherRef);
8419
8420 // Construct the "this" pointer. We'll be using this throughout the generated
8421 // ASTs.
8422 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8423 assert(This && "Reference to this cannot fail!");
8424
8425 // Assign base classes.
8426 bool Invalid = false;
8427 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8428 E = ClassDecl->bases_end(); Base != E; ++Base) {
8429 // Form the assignment:
8430 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8431 QualType BaseType = Base->getType().getUnqualifiedType();
8432 if (!BaseType->isRecordType()) {
8433 Invalid = true;
8434 continue;
8435 }
8436
8437 CXXCastPath BasePath;
8438 BasePath.push_back(Base);
8439
8440 // Construct the "from" expression, which is an implicit cast to the
8441 // appropriately-qualified base type.
8442 Expr *From = OtherRef;
8443 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008444 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008445
8446 // Dereference "this".
8447 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8448
8449 // Implicitly cast "this" to the appropriately-qualified base type.
8450 To = ImpCastExprToType(To.take(),
8451 Context.getCVRQualifiedType(BaseType,
8452 MoveAssignOperator->getTypeQualifiers()),
8453 CK_UncheckedDerivedToBase,
8454 VK_LValue, &BasePath);
8455
8456 // Build the move.
8457 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8458 To.get(), From,
8459 /*CopyingBaseSubobject=*/true,
8460 /*Copying=*/false);
8461 if (Move.isInvalid()) {
8462 Diag(CurrentLocation, diag::note_member_synthesized_at)
8463 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8464 MoveAssignOperator->setInvalidDecl();
8465 return;
8466 }
8467
8468 // Success! Record the move.
8469 Statements.push_back(Move.takeAs<Expr>());
8470 }
8471
8472 // \brief Reference to the __builtin_memcpy function.
8473 Expr *BuiltinMemCpyRef = 0;
8474 // \brief Reference to the __builtin_objc_memmove_collectable function.
8475 Expr *CollectableMemCpyRef = 0;
8476
8477 // Assign non-static members.
8478 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8479 FieldEnd = ClassDecl->field_end();
8480 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008481 if (Field->isUnnamedBitfield())
8482 continue;
8483
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008484 // Check for members of reference type; we can't move those.
8485 if (Field->getType()->isReferenceType()) {
8486 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8487 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8488 Diag(Field->getLocation(), diag::note_declared_at);
8489 Diag(CurrentLocation, diag::note_member_synthesized_at)
8490 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8491 Invalid = true;
8492 continue;
8493 }
8494
8495 // Check for members of const-qualified, non-class type.
8496 QualType BaseType = Context.getBaseElementType(Field->getType());
8497 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8498 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8499 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8500 Diag(Field->getLocation(), diag::note_declared_at);
8501 Diag(CurrentLocation, diag::note_member_synthesized_at)
8502 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8503 Invalid = true;
8504 continue;
8505 }
8506
8507 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008508 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8509 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008510
8511 QualType FieldType = Field->getType().getNonReferenceType();
8512 if (FieldType->isIncompleteArrayType()) {
8513 assert(ClassDecl->hasFlexibleArrayMember() &&
8514 "Incomplete array type is not valid");
8515 continue;
8516 }
8517
8518 // Build references to the field in the object we're copying from and to.
8519 CXXScopeSpec SS; // Intentionally empty
8520 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8521 LookupMemberName);
8522 MemberLookup.addDecl(*Field);
8523 MemberLookup.resolveKind();
8524 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8525 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008526 SS, SourceLocation(), 0,
8527 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008528 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8529 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008530 SS, SourceLocation(), 0,
8531 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008532 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8533 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8534
8535 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8536 "Member reference with rvalue base must be rvalue except for reference "
8537 "members, which aren't allowed for move assignment.");
8538
8539 // If the field should be copied with __builtin_memcpy rather than via
8540 // explicit assignments, do so. This optimization only applies for arrays
8541 // of scalars and arrays of class type with trivial move-assignment
8542 // operators.
8543 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8544 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8545 // Compute the size of the memory buffer to be copied.
8546 QualType SizeType = Context.getSizeType();
8547 llvm::APInt Size(Context.getTypeSize(SizeType),
8548 Context.getTypeSizeInChars(BaseType).getQuantity());
8549 for (const ConstantArrayType *Array
8550 = Context.getAsConstantArrayType(FieldType);
8551 Array;
8552 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8553 llvm::APInt ArraySize
8554 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8555 Size *= ArraySize;
8556 }
8557
Douglas Gregor45d3d712011-09-01 02:09:07 +00008558 // Take the address of the field references for "from" and "to". We
8559 // directly construct UnaryOperators here because semantic analysis
8560 // does not permit us to take the address of an xvalue.
8561 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8562 Context.getPointerType(From.get()->getType()),
8563 VK_RValue, OK_Ordinary, Loc);
8564 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8565 Context.getPointerType(To.get()->getType()),
8566 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008567
8568 bool NeedsCollectableMemCpy =
8569 (BaseType->isRecordType() &&
8570 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8571
8572 if (NeedsCollectableMemCpy) {
8573 if (!CollectableMemCpyRef) {
8574 // Create a reference to the __builtin_objc_memmove_collectable function.
8575 LookupResult R(*this,
8576 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8577 Loc, LookupOrdinaryName);
8578 LookupName(R, TUScope, true);
8579
8580 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8581 if (!CollectableMemCpy) {
8582 // Something went horribly wrong earlier, and we will have
8583 // complained about it.
8584 Invalid = true;
8585 continue;
8586 }
8587
8588 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8589 CollectableMemCpy->getType(),
8590 VK_LValue, Loc, 0).take();
8591 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8592 }
8593 }
8594 // Create a reference to the __builtin_memcpy builtin function.
8595 else if (!BuiltinMemCpyRef) {
8596 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8597 LookupOrdinaryName);
8598 LookupName(R, TUScope, true);
8599
8600 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8601 if (!BuiltinMemCpy) {
8602 // Something went horribly wrong earlier, and we will have complained
8603 // about it.
8604 Invalid = true;
8605 continue;
8606 }
8607
8608 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8609 BuiltinMemCpy->getType(),
8610 VK_LValue, Loc, 0).take();
8611 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8612 }
8613
8614 ASTOwningVector<Expr*> CallArgs(*this);
8615 CallArgs.push_back(To.takeAs<Expr>());
8616 CallArgs.push_back(From.takeAs<Expr>());
8617 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8618 ExprResult Call = ExprError();
8619 if (NeedsCollectableMemCpy)
8620 Call = ActOnCallExpr(/*Scope=*/0,
8621 CollectableMemCpyRef,
8622 Loc, move_arg(CallArgs),
8623 Loc);
8624 else
8625 Call = ActOnCallExpr(/*Scope=*/0,
8626 BuiltinMemCpyRef,
8627 Loc, move_arg(CallArgs),
8628 Loc);
8629
8630 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8631 Statements.push_back(Call.takeAs<Expr>());
8632 continue;
8633 }
8634
8635 // Build the move of this field.
8636 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8637 To.get(), From.get(),
8638 /*CopyingBaseSubobject=*/false,
8639 /*Copying=*/false);
8640 if (Move.isInvalid()) {
8641 Diag(CurrentLocation, diag::note_member_synthesized_at)
8642 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8643 MoveAssignOperator->setInvalidDecl();
8644 return;
8645 }
8646
8647 // Success! Record the copy.
8648 Statements.push_back(Move.takeAs<Stmt>());
8649 }
8650
8651 if (!Invalid) {
8652 // Add a "return *this;"
8653 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8654
8655 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8656 if (Return.isInvalid())
8657 Invalid = true;
8658 else {
8659 Statements.push_back(Return.takeAs<Stmt>());
8660
8661 if (Trap.hasErrorOccurred()) {
8662 Diag(CurrentLocation, diag::note_member_synthesized_at)
8663 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8664 Invalid = true;
8665 }
8666 }
8667 }
8668
8669 if (Invalid) {
8670 MoveAssignOperator->setInvalidDecl();
8671 return;
8672 }
8673
8674 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8675 /*isStmtExpr=*/false);
8676 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8677 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8678
8679 if (ASTMutationListener *L = getASTMutationListener()) {
8680 L->CompletedImplicitDefinition(MoveAssignOperator);
8681 }
8682}
8683
Sean Hunt49634cf2011-05-13 06:10:58 +00008684std::pair<Sema::ImplicitExceptionSpecification, bool>
8685Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008686 if (ClassDecl->isInvalidDecl())
8687 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8688
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008689 // C++ [class.copy]p5:
8690 // The implicitly-declared copy constructor for a class X will
8691 // have the form
8692 //
8693 // X::X(const X&)
8694 //
8695 // if
Sean Huntc530d172011-06-10 04:44:37 +00008696 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008697 bool HasConstCopyConstructor = true;
8698
8699 // -- each direct or virtual base class B of X has a copy
8700 // constructor whose first parameter is of type const B& or
8701 // const volatile B&, and
8702 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8703 BaseEnd = ClassDecl->bases_end();
8704 HasConstCopyConstructor && Base != BaseEnd;
8705 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008706 // Virtual bases are handled below.
8707 if (Base->isVirtual())
8708 continue;
8709
Douglas Gregor22584312010-07-02 23:41:54 +00008710 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008711 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008712 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8713 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008714 }
8715
8716 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8717 BaseEnd = ClassDecl->vbases_end();
8718 HasConstCopyConstructor && Base != BaseEnd;
8719 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008720 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008721 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008722 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8723 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008724 }
8725
8726 // -- for all the nonstatic data members of X that are of a
8727 // class type M (or array thereof), each such class type
8728 // has a copy constructor whose first parameter is of type
8729 // const M& or const volatile M&.
8730 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8731 FieldEnd = ClassDecl->field_end();
8732 HasConstCopyConstructor && Field != FieldEnd;
8733 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008734 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008735 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008736 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8737 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008738 }
8739 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008740 // Otherwise, the implicitly declared copy constructor will have
8741 // the form
8742 //
8743 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008744
Douglas Gregor0d405db2010-07-01 20:59:04 +00008745 // C++ [except.spec]p14:
8746 // An implicitly declared special member function (Clause 12) shall have an
8747 // exception-specification. [...]
8748 ImplicitExceptionSpecification ExceptSpec(Context);
8749 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8750 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8751 BaseEnd = ClassDecl->bases_end();
8752 Base != BaseEnd;
8753 ++Base) {
8754 // Virtual bases are handled below.
8755 if (Base->isVirtual())
8756 continue;
8757
Douglas Gregor22584312010-07-02 23:41:54 +00008758 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008759 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008760 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008761 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008762 ExceptSpec.CalledDecl(CopyConstructor);
8763 }
8764 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8765 BaseEnd = ClassDecl->vbases_end();
8766 Base != BaseEnd;
8767 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008768 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008769 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008770 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008771 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008772 ExceptSpec.CalledDecl(CopyConstructor);
8773 }
8774 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8775 FieldEnd = ClassDecl->field_end();
8776 Field != FieldEnd;
8777 ++Field) {
8778 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008779 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8780 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008781 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008782 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008783 }
8784 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008785
Sean Hunt49634cf2011-05-13 06:10:58 +00008786 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8787}
8788
8789CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8790 CXXRecordDecl *ClassDecl) {
8791 // C++ [class.copy]p4:
8792 // If the class definition does not explicitly declare a copy
8793 // constructor, one is declared implicitly.
8794
8795 ImplicitExceptionSpecification Spec(Context);
8796 bool Const;
8797 llvm::tie(Spec, Const) =
8798 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8799
8800 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8801 QualType ArgType = ClassType;
8802 if (Const)
8803 ArgType = ArgType.withConst();
8804 ArgType = Context.getLValueReferenceType(ArgType);
8805
8806 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8807
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008808 DeclarationName Name
8809 = Context.DeclarationNames.getCXXConstructorName(
8810 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008811 SourceLocation ClassLoc = ClassDecl->getLocation();
8812 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008813
8814 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008815 // member of its class.
8816 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8817 Context, ClassDecl, ClassLoc, NameInfo,
8818 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8819 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8820 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8821 getLangOptions().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008822 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008823 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008824 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008825
Douglas Gregor22584312010-07-02 23:41:54 +00008826 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008827 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8828
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008829 // Add the parameter to the constructor.
8830 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008831 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008832 /*IdentifierInfo=*/0,
8833 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008834 SC_None,
8835 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008836 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008837
Douglas Gregor23c94db2010-07-02 17:43:08 +00008838 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008839 PushOnScopeChains(CopyConstructor, S, false);
8840 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008841
Nico Weberafcc96a2012-01-23 03:19:29 +00008842 // C++11 [class.copy]p8:
8843 // ... If the class definition does not explicitly declare a copy
8844 // constructor, there is no user-declared move constructor, and there is no
8845 // user-declared move assignment operator, a copy constructor is implicitly
8846 // declared as defaulted.
Sean Hunt1ccbc542011-06-22 01:05:13 +00008847 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weberafcc96a2012-01-23 03:19:29 +00008848 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber28976602012-01-23 04:01:33 +00008849 !getLangOptions().MicrosoftMode) ||
Sean Huntc32d6842011-10-11 04:55:36 +00008850 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008851 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008852
8853 return CopyConstructor;
8854}
8855
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008856void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008857 CXXConstructorDecl *CopyConstructor) {
8858 assert((CopyConstructor->isDefaulted() &&
8859 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008860 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008861 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008862
Anders Carlsson63010a72010-04-23 16:24:12 +00008863 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008864 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008865
Douglas Gregor39957dc2010-05-01 15:04:51 +00008866 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008867 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008868
Sean Huntcbb67482011-01-08 20:30:50 +00008869 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008870 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008871 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008872 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008873 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008874 } else {
8875 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8876 CopyConstructor->getLocation(),
8877 MultiStmtArg(*this, 0, 0),
8878 /*isStmtExpr=*/false)
8879 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008880 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008881 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008882
8883 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008884 if (ASTMutationListener *L = getASTMutationListener()) {
8885 L->CompletedImplicitDefinition(CopyConstructor);
8886 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008887}
8888
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008889Sema::ImplicitExceptionSpecification
8890Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8891 // C++ [except.spec]p14:
8892 // An implicitly declared special member function (Clause 12) shall have an
8893 // exception-specification. [...]
8894 ImplicitExceptionSpecification ExceptSpec(Context);
8895 if (ClassDecl->isInvalidDecl())
8896 return ExceptSpec;
8897
8898 // Direct base-class constructors.
8899 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8900 BEnd = ClassDecl->bases_end();
8901 B != BEnd; ++B) {
8902 if (B->isVirtual()) // Handled below.
8903 continue;
8904
8905 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8906 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8907 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8908 // If this is a deleted function, add it anyway. This might be conformant
8909 // with the standard. This might not. I'm not sure. It might not matter.
8910 if (Constructor)
8911 ExceptSpec.CalledDecl(Constructor);
8912 }
8913 }
8914
8915 // Virtual base-class constructors.
8916 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8917 BEnd = ClassDecl->vbases_end();
8918 B != BEnd; ++B) {
8919 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8920 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8921 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8922 // If this is a deleted function, add it anyway. This might be conformant
8923 // with the standard. This might not. I'm not sure. It might not matter.
8924 if (Constructor)
8925 ExceptSpec.CalledDecl(Constructor);
8926 }
8927 }
8928
8929 // Field constructors.
8930 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8931 FEnd = ClassDecl->field_end();
8932 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008933 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008934 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8935 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8936 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8937 // If this is a deleted function, add it anyway. This might be conformant
8938 // with the standard. This might not. I'm not sure. It might not matter.
8939 // In particular, the problem is that this function never gets called. It
8940 // might just be ill-formed because this function attempts to refer to
8941 // a deleted function here.
8942 if (Constructor)
8943 ExceptSpec.CalledDecl(Constructor);
8944 }
8945 }
8946
8947 return ExceptSpec;
8948}
8949
8950CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8951 CXXRecordDecl *ClassDecl) {
8952 ImplicitExceptionSpecification Spec(
8953 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8954
8955 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8956 QualType ArgType = Context.getRValueReferenceType(ClassType);
8957
8958 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8959
8960 DeclarationName Name
8961 = Context.DeclarationNames.getCXXConstructorName(
8962 Context.getCanonicalType(ClassType));
8963 SourceLocation ClassLoc = ClassDecl->getLocation();
8964 DeclarationNameInfo NameInfo(Name, ClassLoc);
8965
8966 // C++0x [class.copy]p11:
8967 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008968 // member of its class.
8969 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8970 Context, ClassDecl, ClassLoc, NameInfo,
8971 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8972 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8973 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8974 getLangOptions().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008975 MoveConstructor->setAccess(AS_public);
8976 MoveConstructor->setDefaulted();
8977 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008978
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008979 // Add the parameter to the constructor.
8980 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8981 ClassLoc, ClassLoc,
8982 /*IdentifierInfo=*/0,
8983 ArgType, /*TInfo=*/0,
8984 SC_None,
8985 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008986 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008987
8988 // C++0x [class.copy]p9:
8989 // If the definition of a class X does not explicitly declare a move
8990 // constructor, one will be implicitly declared as defaulted if and only if:
8991 // [...]
8992 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008993 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008994 // Cache this result so that we don't try to generate this over and over
8995 // on every lookup, leaking memory and wasting time.
8996 ClassDecl->setFailedImplicitMoveConstructor();
8997 return 0;
8998 }
8999
9000 // Note that we have declared this constructor.
9001 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9002
9003 if (Scope *S = getScopeForContext(ClassDecl))
9004 PushOnScopeChains(MoveConstructor, S, false);
9005 ClassDecl->addDecl(MoveConstructor);
9006
9007 return MoveConstructor;
9008}
9009
9010void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9011 CXXConstructorDecl *MoveConstructor) {
9012 assert((MoveConstructor->isDefaulted() &&
9013 MoveConstructor->isMoveConstructor() &&
9014 !MoveConstructor->doesThisDeclarationHaveABody()) &&
9015 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9016
9017 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9018 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9019
9020 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
9021 DiagnosticErrorTrap Trap(Diags);
9022
9023 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
9024 Trap.hasErrorOccurred()) {
9025 Diag(CurrentLocation, diag::note_member_synthesized_at)
9026 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9027 MoveConstructor->setInvalidDecl();
9028 } else {
9029 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9030 MoveConstructor->getLocation(),
9031 MultiStmtArg(*this, 0, 0),
9032 /*isStmtExpr=*/false)
9033 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009034 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009035 }
9036
9037 MoveConstructor->setUsed();
9038
9039 if (ASTMutationListener *L = getASTMutationListener()) {
9040 L->CompletedImplicitDefinition(MoveConstructor);
9041 }
9042}
9043
John McCall60d7b3a2010-08-24 06:29:42 +00009044ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009045Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009046 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009047 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009048 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009049 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009050 unsigned ConstructKind,
9051 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009052 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009053
Douglas Gregor2f599792010-04-02 18:24:57 +00009054 // C++0x [class.copy]p34:
9055 // When certain criteria are met, an implementation is allowed to
9056 // omit the copy/move construction of a class object, even if the
9057 // copy/move constructor and/or destructor for the object have
9058 // side effects. [...]
9059 // - when a temporary class object that has not been bound to a
9060 // reference (12.2) would be copied/moved to a class object
9061 // with the same cv-unqualified type, the copy/move operation
9062 // can be omitted by constructing the temporary object
9063 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009064 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00009065 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009066 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009067 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009068 }
Mike Stump1eb44332009-09-09 15:08:12 +00009069
9070 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009071 Elidable, move(ExprArgs), HadMultipleCandidates,
9072 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009073}
9074
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009075/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9076/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009077ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009078Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9079 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009080 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009081 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009082 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009083 unsigned ConstructKind,
9084 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009085 unsigned NumExprs = ExprArgs.size();
9086 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009087
Nick Lewycky909a70d2011-03-25 01:44:32 +00009088 for (specific_attr_iterator<NonNullAttr>
9089 i = Constructor->specific_attr_begin<NonNullAttr>(),
9090 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9091 const NonNullAttr *NonNull = *i;
9092 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9093 }
9094
Eli Friedman5f2987c2012-02-02 03:46:19 +00009095 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009096 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009097 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009098 HadMultipleCandidates, /*FIXME*/false,
9099 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009100 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9101 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009102}
9103
Mike Stump1eb44332009-09-09 15:08:12 +00009104bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009105 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009106 MultiExprArg Exprs,
9107 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009108 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009109 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009110 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009111 move(Exprs), HadMultipleCandidates, false,
9112 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009113 if (TempResult.isInvalid())
9114 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009115
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009116 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009117 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009118 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009119 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009120 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009121
Anders Carlssonfe2de492009-08-25 05:18:00 +00009122 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009123}
9124
John McCall68c6c9a2010-02-02 09:10:11 +00009125void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009126 if (VD->isInvalidDecl()) return;
9127
John McCall68c6c9a2010-02-02 09:10:11 +00009128 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009129 if (ClassDecl->isInvalidDecl()) return;
9130 if (ClassDecl->hasTrivialDestructor()) return;
9131 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009132
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009133 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009134 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009135 CheckDestructorAccess(VD->getLocation(), Destructor,
9136 PDiag(diag::err_access_dtor_var)
9137 << VD->getDeclName()
9138 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009139
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009140 if (!VD->hasGlobalStorage()) return;
9141
9142 // Emit warning for non-trivial dtor in global scope (a real global,
9143 // class-static, function-static).
9144 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9145
9146 // TODO: this should be re-enabled for static locals by !CXAAtExit
9147 if (!VD->isStaticLocal())
9148 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009149}
9150
Douglas Gregor39da0b82009-09-09 23:08:42 +00009151/// \brief Given a constructor and the set of arguments provided for the
9152/// constructor, convert the arguments and add any required default arguments
9153/// to form a proper call to this constructor.
9154///
9155/// \returns true if an error occurred, false otherwise.
9156bool
9157Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9158 MultiExprArg ArgsPtr,
9159 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00009160 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009161 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9162 unsigned NumArgs = ArgsPtr.size();
9163 Expr **Args = (Expr **)ArgsPtr.get();
9164
9165 const FunctionProtoType *Proto
9166 = Constructor->getType()->getAs<FunctionProtoType>();
9167 assert(Proto && "Constructor without a prototype?");
9168 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009169
9170 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009171 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009172 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009173 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009174 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009175
9176 VariadicCallType CallType =
9177 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009178 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009179 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9180 Proto, 0, Args, NumArgs, AllArgs,
9181 CallType);
9182 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9183 ConvertedArgs.push_back(AllArgs[i]);
9184 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009185}
9186
Anders Carlsson20d45d22009-12-12 00:32:00 +00009187static inline bool
9188CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9189 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009190 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009191 if (isa<NamespaceDecl>(DC)) {
9192 return SemaRef.Diag(FnDecl->getLocation(),
9193 diag::err_operator_new_delete_declared_in_namespace)
9194 << FnDecl->getDeclName();
9195 }
9196
9197 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009198 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009199 return SemaRef.Diag(FnDecl->getLocation(),
9200 diag::err_operator_new_delete_declared_static)
9201 << FnDecl->getDeclName();
9202 }
9203
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009204 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009205}
9206
Anders Carlsson156c78e2009-12-13 17:53:43 +00009207static inline bool
9208CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9209 CanQualType ExpectedResultType,
9210 CanQualType ExpectedFirstParamType,
9211 unsigned DependentParamTypeDiag,
9212 unsigned InvalidParamTypeDiag) {
9213 QualType ResultType =
9214 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9215
9216 // Check that the result type is not dependent.
9217 if (ResultType->isDependentType())
9218 return SemaRef.Diag(FnDecl->getLocation(),
9219 diag::err_operator_new_delete_dependent_result_type)
9220 << FnDecl->getDeclName() << ExpectedResultType;
9221
9222 // Check that the result type is what we expect.
9223 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9224 return SemaRef.Diag(FnDecl->getLocation(),
9225 diag::err_operator_new_delete_invalid_result_type)
9226 << FnDecl->getDeclName() << ExpectedResultType;
9227
9228 // A function template must have at least 2 parameters.
9229 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9230 return SemaRef.Diag(FnDecl->getLocation(),
9231 diag::err_operator_new_delete_template_too_few_parameters)
9232 << FnDecl->getDeclName();
9233
9234 // The function decl must have at least 1 parameter.
9235 if (FnDecl->getNumParams() == 0)
9236 return SemaRef.Diag(FnDecl->getLocation(),
9237 diag::err_operator_new_delete_too_few_parameters)
9238 << FnDecl->getDeclName();
9239
9240 // Check the the first parameter type is not dependent.
9241 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9242 if (FirstParamType->isDependentType())
9243 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9244 << FnDecl->getDeclName() << ExpectedFirstParamType;
9245
9246 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009247 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009248 ExpectedFirstParamType)
9249 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9250 << FnDecl->getDeclName() << ExpectedFirstParamType;
9251
9252 return false;
9253}
9254
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009255static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009256CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009257 // C++ [basic.stc.dynamic.allocation]p1:
9258 // A program is ill-formed if an allocation function is declared in a
9259 // namespace scope other than global scope or declared static in global
9260 // scope.
9261 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9262 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009263
9264 CanQualType SizeTy =
9265 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9266
9267 // C++ [basic.stc.dynamic.allocation]p1:
9268 // The return type shall be void*. The first parameter shall have type
9269 // std::size_t.
9270 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9271 SizeTy,
9272 diag::err_operator_new_dependent_param_type,
9273 diag::err_operator_new_param_type))
9274 return true;
9275
9276 // C++ [basic.stc.dynamic.allocation]p1:
9277 // The first parameter shall not have an associated default argument.
9278 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009279 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009280 diag::err_operator_new_default_arg)
9281 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9282
9283 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009284}
9285
9286static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009287CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9288 // C++ [basic.stc.dynamic.deallocation]p1:
9289 // A program is ill-formed if deallocation functions are declared in a
9290 // namespace scope other than global scope or declared static in global
9291 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009292 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9293 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009294
9295 // C++ [basic.stc.dynamic.deallocation]p2:
9296 // Each deallocation function shall return void and its first parameter
9297 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009298 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9299 SemaRef.Context.VoidPtrTy,
9300 diag::err_operator_delete_dependent_param_type,
9301 diag::err_operator_delete_param_type))
9302 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009303
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009304 return false;
9305}
9306
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009307/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9308/// of this overloaded operator is well-formed. If so, returns false;
9309/// otherwise, emits appropriate diagnostics and returns true.
9310bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009311 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009312 "Expected an overloaded operator declaration");
9313
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009314 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9315
Mike Stump1eb44332009-09-09 15:08:12 +00009316 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009317 // The allocation and deallocation functions, operator new,
9318 // operator new[], operator delete and operator delete[], are
9319 // described completely in 3.7.3. The attributes and restrictions
9320 // found in the rest of this subclause do not apply to them unless
9321 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009322 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009323 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009324
Anders Carlssona3ccda52009-12-12 00:26:23 +00009325 if (Op == OO_New || Op == OO_Array_New)
9326 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009327
9328 // C++ [over.oper]p6:
9329 // An operator function shall either be a non-static member
9330 // function or be a non-member function and have at least one
9331 // parameter whose type is a class, a reference to a class, an
9332 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009333 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9334 if (MethodDecl->isStatic())
9335 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009336 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009337 } else {
9338 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009339 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9340 ParamEnd = FnDecl->param_end();
9341 Param != ParamEnd; ++Param) {
9342 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009343 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9344 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009345 ClassOrEnumParam = true;
9346 break;
9347 }
9348 }
9349
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009350 if (!ClassOrEnumParam)
9351 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009352 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009353 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009354 }
9355
9356 // C++ [over.oper]p8:
9357 // An operator function cannot have default arguments (8.3.6),
9358 // except where explicitly stated below.
9359 //
Mike Stump1eb44332009-09-09 15:08:12 +00009360 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009361 // (C++ [over.call]p1).
9362 if (Op != OO_Call) {
9363 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9364 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009365 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009366 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009367 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009368 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009369 }
9370 }
9371
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009372 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9373 { false, false, false }
9374#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9375 , { Unary, Binary, MemberOnly }
9376#include "clang/Basic/OperatorKinds.def"
9377 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009378
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009379 bool CanBeUnaryOperator = OperatorUses[Op][0];
9380 bool CanBeBinaryOperator = OperatorUses[Op][1];
9381 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009382
9383 // C++ [over.oper]p8:
9384 // [...] Operator functions cannot have more or fewer parameters
9385 // than the number required for the corresponding operator, as
9386 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009387 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009388 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009389 if (Op != OO_Call &&
9390 ((NumParams == 1 && !CanBeUnaryOperator) ||
9391 (NumParams == 2 && !CanBeBinaryOperator) ||
9392 (NumParams < 1) || (NumParams > 2))) {
9393 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009394 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009395 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009396 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009397 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009398 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009399 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009400 assert(CanBeBinaryOperator &&
9401 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009402 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009403 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009404
Chris Lattner416e46f2008-11-21 07:57:12 +00009405 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009406 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009407 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009408
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009409 // Overloaded operators other than operator() cannot be variadic.
9410 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009411 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009412 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009413 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009414 }
9415
9416 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009417 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9418 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009419 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009420 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009421 }
9422
9423 // C++ [over.inc]p1:
9424 // The user-defined function called operator++ implements the
9425 // prefix and postfix ++ operator. If this function is a member
9426 // function with no parameters, or a non-member function with one
9427 // parameter of class or enumeration type, it defines the prefix
9428 // increment operator ++ for objects of that type. If the function
9429 // is a member function with one parameter (which shall be of type
9430 // int) or a non-member function with two parameters (the second
9431 // of which shall be of type int), it defines the postfix
9432 // increment operator ++ for objects of that type.
9433 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9434 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9435 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009436 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009437 ParamIsInt = BT->getKind() == BuiltinType::Int;
9438
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009439 if (!ParamIsInt)
9440 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009441 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009442 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009443 }
9444
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009445 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009446}
Chris Lattner5a003a42008-12-17 07:09:26 +00009447
Sean Hunta6c058d2010-01-13 09:01:02 +00009448/// CheckLiteralOperatorDeclaration - Check whether the declaration
9449/// of this literal operator function is well-formed. If so, returns
9450/// false; otherwise, emits appropriate diagnostics and returns true.
9451bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9452 DeclContext *DC = FnDecl->getDeclContext();
9453 Decl::Kind Kind = DC->getDeclKind();
9454 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9455 Kind != Decl::LinkageSpec) {
9456 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9457 << FnDecl->getDeclName();
9458 return true;
9459 }
9460
9461 bool Valid = false;
9462
Sean Hunt216c2782010-04-07 23:11:06 +00009463 // template <char...> type operator "" name() is the only valid template
9464 // signature, and the only valid signature with no parameters.
9465 if (FnDecl->param_size() == 0) {
9466 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9467 // Must have only one template parameter
9468 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9469 if (Params->size() == 1) {
9470 NonTypeTemplateParmDecl *PmDecl =
9471 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009472
Sean Hunt216c2782010-04-07 23:11:06 +00009473 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009474 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9475 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9476 Valid = true;
9477 }
9478 }
9479 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009480 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009481 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9482
Sean Hunta6c058d2010-01-13 09:01:02 +00009483 QualType T = (*Param)->getType();
9484
Sean Hunt30019c02010-04-07 22:57:35 +00009485 // unsigned long long int, long double, and any character type are allowed
9486 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009487 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9488 Context.hasSameType(T, Context.LongDoubleTy) ||
9489 Context.hasSameType(T, Context.CharTy) ||
9490 Context.hasSameType(T, Context.WCharTy) ||
9491 Context.hasSameType(T, Context.Char16Ty) ||
9492 Context.hasSameType(T, Context.Char32Ty)) {
9493 if (++Param == FnDecl->param_end())
9494 Valid = true;
9495 goto FinishedParams;
9496 }
9497
Sean Hunt30019c02010-04-07 22:57:35 +00009498 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009499 const PointerType *PT = T->getAs<PointerType>();
9500 if (!PT)
9501 goto FinishedParams;
9502 T = PT->getPointeeType();
9503 if (!T.isConstQualified())
9504 goto FinishedParams;
9505 T = T.getUnqualifiedType();
9506
9507 // Move on to the second parameter;
9508 ++Param;
9509
9510 // If there is no second parameter, the first must be a const char *
9511 if (Param == FnDecl->param_end()) {
9512 if (Context.hasSameType(T, Context.CharTy))
9513 Valid = true;
9514 goto FinishedParams;
9515 }
9516
9517 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9518 // are allowed as the first parameter to a two-parameter function
9519 if (!(Context.hasSameType(T, Context.CharTy) ||
9520 Context.hasSameType(T, Context.WCharTy) ||
9521 Context.hasSameType(T, Context.Char16Ty) ||
9522 Context.hasSameType(T, Context.Char32Ty)))
9523 goto FinishedParams;
9524
9525 // The second and final parameter must be an std::size_t
9526 T = (*Param)->getType().getUnqualifiedType();
9527 if (Context.hasSameType(T, Context.getSizeType()) &&
9528 ++Param == FnDecl->param_end())
9529 Valid = true;
9530 }
9531
9532 // FIXME: This diagnostic is absolutely terrible.
9533FinishedParams:
9534 if (!Valid) {
9535 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9536 << FnDecl->getDeclName();
9537 return true;
9538 }
9539
Douglas Gregor1155c422011-08-30 22:40:35 +00009540 StringRef LiteralName
9541 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9542 if (LiteralName[0] != '_') {
9543 // C++0x [usrlit.suffix]p1:
9544 // Literal suffix identifiers that do not start with an underscore are
9545 // reserved for future standardization.
9546 bool IsHexFloat = true;
9547 if (LiteralName.size() > 1 &&
9548 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9549 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9550 if (!isdigit(LiteralName[I])) {
9551 IsHexFloat = false;
9552 break;
9553 }
9554 }
9555 }
9556
9557 if (IsHexFloat)
9558 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9559 << LiteralName;
9560 else
9561 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9562 }
9563
Sean Hunta6c058d2010-01-13 09:01:02 +00009564 return false;
9565}
9566
Douglas Gregor074149e2009-01-05 19:45:36 +00009567/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9568/// linkage specification, including the language and (if present)
9569/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9570/// the location of the language string literal, which is provided
9571/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9572/// the '{' brace. Otherwise, this linkage specification does not
9573/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009574Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9575 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009576 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009577 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009578 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009579 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009580 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009581 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009582 Language = LinkageSpecDecl::lang_cxx;
9583 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009584 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009585 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009586 }
Mike Stump1eb44332009-09-09 15:08:12 +00009587
Chris Lattnercc98eac2008-12-17 07:13:27 +00009588 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009589
Douglas Gregor074149e2009-01-05 19:45:36 +00009590 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009591 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009592 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009593 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009594 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009595}
9596
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009597/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009598/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9599/// valid, it's the position of the closing '}' brace in a linkage
9600/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009601Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009602 Decl *LinkageSpec,
9603 SourceLocation RBraceLoc) {
9604 if (LinkageSpec) {
9605 if (RBraceLoc.isValid()) {
9606 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9607 LSDecl->setRBraceLoc(RBraceLoc);
9608 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009609 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009610 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009611 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009612}
9613
Douglas Gregord308e622009-05-18 20:51:54 +00009614/// \brief Perform semantic analysis for the variable declaration that
9615/// occurs within a C++ catch clause, returning the newly-created
9616/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009617VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009618 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009619 SourceLocation StartLoc,
9620 SourceLocation Loc,
9621 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009622 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009623 QualType ExDeclType = TInfo->getType();
9624
Sebastian Redl4b07b292008-12-22 19:15:10 +00009625 // Arrays and functions decay.
9626 if (ExDeclType->isArrayType())
9627 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9628 else if (ExDeclType->isFunctionType())
9629 ExDeclType = Context.getPointerType(ExDeclType);
9630
9631 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9632 // The exception-declaration shall not denote a pointer or reference to an
9633 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009634 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009635 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009636 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009637 Invalid = true;
9638 }
Douglas Gregord308e622009-05-18 20:51:54 +00009639
Sebastian Redl4b07b292008-12-22 19:15:10 +00009640 QualType BaseType = ExDeclType;
9641 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009642 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009643 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009644 BaseType = Ptr->getPointeeType();
9645 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009646 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009647 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009648 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009649 BaseType = Ref->getPointeeType();
9650 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009651 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009652 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009653 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009654 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009655 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009656
Mike Stump1eb44332009-09-09 15:08:12 +00009657 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009658 RequireNonAbstractType(Loc, ExDeclType,
9659 diag::err_abstract_type_in_decl,
9660 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009661 Invalid = true;
9662
John McCall5a180392010-07-24 00:37:23 +00009663 // Only the non-fragile NeXT runtime currently supports C++ catches
9664 // of ObjC types, and no runtime supports catching ObjC types by value.
9665 if (!Invalid && getLangOptions().ObjC1) {
9666 QualType T = ExDeclType;
9667 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9668 T = RT->getPointeeType();
9669
9670 if (T->isObjCObjectType()) {
9671 Diag(Loc, diag::err_objc_object_catch);
9672 Invalid = true;
9673 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009674 if (!getLangOptions().ObjCNonFragileABI)
9675 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009676 }
9677 }
9678
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009679 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9680 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009681 ExDecl->setExceptionVariable(true);
9682
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009683 // In ARC, infer 'retaining' for variables of retainable type.
9684 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9685 Invalid = true;
9686
Douglas Gregorc41b8782011-07-06 18:14:43 +00009687 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009688 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009689 // C++ [except.handle]p16:
9690 // The object declared in an exception-declaration or, if the
9691 // exception-declaration does not specify a name, a temporary (12.2) is
9692 // copy-initialized (8.5) from the exception object. [...]
9693 // The object is destroyed when the handler exits, after the destruction
9694 // of any automatic objects initialized within the handler.
9695 //
9696 // We just pretend to initialize the object with itself, then make sure
9697 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009698 QualType initType = ExDeclType;
9699
9700 InitializedEntity entity =
9701 InitializedEntity::InitializeVariable(ExDecl);
9702 InitializationKind initKind =
9703 InitializationKind::CreateCopy(Loc, SourceLocation());
9704
9705 Expr *opaqueValue =
9706 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9707 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9708 ExprResult result = sequence.Perform(*this, entity, initKind,
9709 MultiExprArg(&opaqueValue, 1));
9710 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009711 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009712 else {
9713 // If the constructor used was non-trivial, set this as the
9714 // "initializer".
9715 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9716 if (!construct->getConstructor()->isTrivial()) {
9717 Expr *init = MaybeCreateExprWithCleanups(construct);
9718 ExDecl->setInit(init);
9719 }
9720
9721 // And make sure it's destructable.
9722 FinalizeVarWithDestructor(ExDecl, recordType);
9723 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009724 }
9725 }
9726
Douglas Gregord308e622009-05-18 20:51:54 +00009727 if (Invalid)
9728 ExDecl->setInvalidDecl();
9729
9730 return ExDecl;
9731}
9732
9733/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9734/// handler.
John McCalld226f652010-08-21 09:40:31 +00009735Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009736 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009737 bool Invalid = D.isInvalidType();
9738
9739 // Check for unexpanded parameter packs.
9740 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9741 UPPC_ExceptionType)) {
9742 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9743 D.getIdentifierLoc());
9744 Invalid = true;
9745 }
9746
Sebastian Redl4b07b292008-12-22 19:15:10 +00009747 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009748 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009749 LookupOrdinaryName,
9750 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009751 // The scope should be freshly made just for us. There is just no way
9752 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009753 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009754 if (PrevDecl->isTemplateParameter()) {
9755 // Maybe we will complain about the shadowed template parameter.
9756 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009757 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009758 }
9759 }
9760
Chris Lattnereaaebc72009-04-25 08:06:05 +00009761 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009762 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9763 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009764 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009765 }
9766
Douglas Gregor83cb9422010-09-09 17:09:21 +00009767 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009768 D.getSourceRange().getBegin(),
9769 D.getIdentifierLoc(),
9770 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009771 if (Invalid)
9772 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009773
Sebastian Redl4b07b292008-12-22 19:15:10 +00009774 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009775 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009776 PushOnScopeChains(ExDecl, S);
9777 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009778 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009779
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009780 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009781 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009782}
Anders Carlssonfb311762009-03-14 00:25:26 +00009783
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009784Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009785 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009786 Expr *AssertMessageExpr_,
9787 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009788 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009789
Anders Carlssonc3082412009-03-14 00:33:21 +00009790 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009791 // In a static_assert-declaration, the constant-expression shall be a
9792 // constant expression that can be contextually converted to bool.
9793 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9794 if (Converted.isInvalid())
9795 return 0;
9796
Richard Smithdaaefc52011-12-14 23:32:26 +00009797 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009798 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9799 PDiag(diag::err_static_assert_expression_is_not_constant),
9800 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009801 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009802
Richard Smithdaaefc52011-12-14 23:32:26 +00009803 if (!Cond)
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009804 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009805 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009806 }
Mike Stump1eb44332009-09-09 15:08:12 +00009807
Douglas Gregor399ad972010-12-15 23:55:21 +00009808 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9809 return 0;
9810
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009811 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9812 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009813
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009814 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009815 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009816}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009817
Douglas Gregor1d869352010-04-07 16:53:43 +00009818/// \brief Perform semantic analysis of the given friend type declaration.
9819///
9820/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009821FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9822 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009823 TypeSourceInfo *TSInfo) {
9824 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9825
9826 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009827 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009828
Richard Smith6b130222011-10-18 21:39:00 +00009829 // C++03 [class.friend]p2:
9830 // An elaborated-type-specifier shall be used in a friend declaration
9831 // for a class.*
9832 //
9833 // * The class-key of the elaborated-type-specifier is required.
9834 if (!ActiveTemplateInstantiations.empty()) {
9835 // Do not complain about the form of friend template types during
9836 // template instantiation; we will already have complained when the
9837 // template was declared.
9838 } else if (!T->isElaboratedTypeSpecifier()) {
9839 // If we evaluated the type to a record type, suggest putting
9840 // a tag in front.
9841 if (const RecordType *RT = T->getAs<RecordType>()) {
9842 RecordDecl *RD = RT->getDecl();
9843
9844 std::string InsertionText = std::string(" ") + RD->getKindName();
9845
9846 Diag(TypeRange.getBegin(),
9847 getLangOptions().CPlusPlus0x ?
9848 diag::warn_cxx98_compat_unelaborated_friend_type :
9849 diag::ext_unelaborated_friend_type)
9850 << (unsigned) RD->getTagKind()
9851 << T
9852 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9853 InsertionText);
9854 } else {
9855 Diag(FriendLoc,
9856 getLangOptions().CPlusPlus0x ?
9857 diag::warn_cxx98_compat_nonclass_type_friend :
9858 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009859 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009860 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009861 }
Richard Smith6b130222011-10-18 21:39:00 +00009862 } else if (T->getAs<EnumType>()) {
9863 Diag(FriendLoc,
9864 getLangOptions().CPlusPlus0x ?
9865 diag::warn_cxx98_compat_enum_friend :
9866 diag::ext_enum_friend)
9867 << T
9868 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009869 }
9870
Douglas Gregor06245bf2010-04-07 17:57:12 +00009871 // C++0x [class.friend]p3:
9872 // If the type specifier in a friend declaration designates a (possibly
9873 // cv-qualified) class type, that class is declared as a friend; otherwise,
9874 // the friend declaration is ignored.
9875
9876 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9877 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009878
Abramo Bagnara0216df82011-10-29 20:52:52 +00009879 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009880}
9881
John McCall9a34edb2010-10-19 01:40:49 +00009882/// Handle a friend tag declaration where the scope specifier was
9883/// templated.
9884Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9885 unsigned TagSpec, SourceLocation TagLoc,
9886 CXXScopeSpec &SS,
9887 IdentifierInfo *Name, SourceLocation NameLoc,
9888 AttributeList *Attr,
9889 MultiTemplateParamsArg TempParamLists) {
9890 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9891
9892 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009893 bool Invalid = false;
9894
9895 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009896 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009897 TempParamLists.get(),
9898 TempParamLists.size(),
9899 /*friend*/ true,
9900 isExplicitSpecialization,
9901 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009902 if (TemplateParams->size() > 0) {
9903 // This is a declaration of a class template.
9904 if (Invalid)
9905 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009906
Eric Christopher4110e132011-07-21 05:34:24 +00009907 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9908 SS, Name, NameLoc, Attr,
9909 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009910 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009911 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009912 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009913 } else {
9914 // The "template<>" header is extraneous.
9915 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9916 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9917 isExplicitSpecialization = true;
9918 }
9919 }
9920
9921 if (Invalid) return 0;
9922
John McCall9a34edb2010-10-19 01:40:49 +00009923 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009924 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009925 if (TempParamLists.get()[I]->size()) {
9926 isAllExplicitSpecializations = false;
9927 break;
9928 }
9929 }
9930
9931 // FIXME: don't ignore attributes.
9932
9933 // If it's explicit specializations all the way down, just forget
9934 // about the template header and build an appropriate non-templated
9935 // friend. TODO: for source fidelity, remember the headers.
9936 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009937 if (SS.isEmpty()) {
9938 bool Owned = false;
9939 bool IsDependent = false;
9940 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9941 Attr, AS_public,
9942 /*ModulePrivateLoc=*/SourceLocation(),
9943 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009944 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009945 /*ScopedEnumUsesClassTag=*/false,
9946 /*UnderlyingType=*/TypeResult());
9947 }
9948
Douglas Gregor2494dd02011-03-01 01:34:45 +00009949 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009950 ElaboratedTypeKeyword Keyword
9951 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009952 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009953 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009954 if (T.isNull())
9955 return 0;
9956
9957 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9958 if (isa<DependentNameType>(T)) {
9959 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009960 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009961 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009962 TL.setNameLoc(NameLoc);
9963 } else {
9964 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009965 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009966 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009967 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9968 }
9969
9970 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9971 TSI, FriendLoc);
9972 Friend->setAccess(AS_public);
9973 CurContext->addDecl(Friend);
9974 return Friend;
9975 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009976
9977 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9978
9979
John McCall9a34edb2010-10-19 01:40:49 +00009980
9981 // Handle the case of a templated-scope friend class. e.g.
9982 // template <class T> class A<T>::B;
9983 // FIXME: we don't support these right now.
9984 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9985 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9986 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9987 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009988 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009989 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009990 TL.setNameLoc(NameLoc);
9991
9992 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9993 TSI, FriendLoc);
9994 Friend->setAccess(AS_public);
9995 Friend->setUnsupportedFriend(true);
9996 CurContext->addDecl(Friend);
9997 return Friend;
9998}
9999
10000
John McCalldd4a3b02009-09-16 22:47:08 +000010001/// Handle a friend type declaration. This works in tandem with
10002/// ActOnTag.
10003///
10004/// Notes on friend class templates:
10005///
10006/// We generally treat friend class declarations as if they were
10007/// declaring a class. So, for example, the elaborated type specifier
10008/// in a friend declaration is required to obey the restrictions of a
10009/// class-head (i.e. no typedefs in the scope chain), template
10010/// parameters are required to match up with simple template-ids, &c.
10011/// However, unlike when declaring a template specialization, it's
10012/// okay to refer to a template specialization without an empty
10013/// template parameter declaration, e.g.
10014/// friend class A<T>::B<unsigned>;
10015/// We permit this as a special case; if there are any template
10016/// parameters present at all, require proper matching, i.e.
10017/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010018Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010019 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +000010020 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +000010021
10022 assert(DS.isFriendSpecified());
10023 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10024
John McCalldd4a3b02009-09-16 22:47:08 +000010025 // Try to convert the decl specifier to a type. This works for
10026 // friend templates because ActOnTag never produces a ClassTemplateDecl
10027 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010028 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010029 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10030 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010031 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010032 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010033
Douglas Gregor6ccab972010-12-16 01:14:37 +000010034 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10035 return 0;
10036
John McCalldd4a3b02009-09-16 22:47:08 +000010037 // This is definitely an error in C++98. It's probably meant to
10038 // be forbidden in C++0x, too, but the specification is just
10039 // poorly written.
10040 //
10041 // The problem is with declarations like the following:
10042 // template <T> friend A<T>::foo;
10043 // where deciding whether a class C is a friend or not now hinges
10044 // on whether there exists an instantiation of A that causes
10045 // 'foo' to equal C. There are restrictions on class-heads
10046 // (which we declare (by fiat) elaborated friend declarations to
10047 // be) that makes this tractable.
10048 //
10049 // FIXME: handle "template <> friend class A<T>;", which
10050 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010051 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010052 Diag(Loc, diag::err_tagless_friend_type_template)
10053 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010054 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010055 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010056
John McCall02cace72009-08-28 07:59:38 +000010057 // C++98 [class.friend]p1: A friend of a class is a function
10058 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010059 // This is fixed in DR77, which just barely didn't make the C++03
10060 // deadline. It's also a very silly restriction that seriously
10061 // affects inner classes and which nobody else seems to implement;
10062 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010063 //
10064 // But note that we could warn about it: it's always useless to
10065 // friend one of your own members (it's not, however, worthless to
10066 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010067
John McCalldd4a3b02009-09-16 22:47:08 +000010068 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010069 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010070 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010071 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010072 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010073 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010074 DS.getFriendSpecLoc());
10075 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010076 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010077
10078 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010079 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010080
John McCalldd4a3b02009-09-16 22:47:08 +000010081 D->setAccess(AS_public);
10082 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010083
John McCalld226f652010-08-21 09:40:31 +000010084 return D;
John McCall02cace72009-08-28 07:59:38 +000010085}
10086
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010087Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010088 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010089 const DeclSpec &DS = D.getDeclSpec();
10090
10091 assert(DS.isFriendSpecified());
10092 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10093
10094 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010095 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010096
10097 // C++ [class.friend]p1
10098 // A friend of a class is a function or class....
10099 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010100 // It *doesn't* see through dependent types, which is correct
10101 // according to [temp.arg.type]p3:
10102 // If a declaration acquires a function type through a
10103 // type dependent on a template-parameter and this causes
10104 // a declaration that does not use the syntactic form of a
10105 // function declarator to have a function type, the program
10106 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010107 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010108 Diag(Loc, diag::err_unexpected_friend);
10109
10110 // It might be worthwhile to try to recover by creating an
10111 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010112 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010113 }
10114
10115 // C++ [namespace.memdef]p3
10116 // - If a friend declaration in a non-local class first declares a
10117 // class or function, the friend class or function is a member
10118 // of the innermost enclosing namespace.
10119 // - The name of the friend is not found by simple name lookup
10120 // until a matching declaration is provided in that namespace
10121 // scope (either before or after the class declaration granting
10122 // friendship).
10123 // - If a friend function is called, its name may be found by the
10124 // name lookup that considers functions from namespaces and
10125 // classes associated with the types of the function arguments.
10126 // - When looking for a prior declaration of a class or a function
10127 // declared as a friend, scopes outside the innermost enclosing
10128 // namespace scope are not considered.
10129
John McCall337ec3d2010-10-12 23:13:28 +000010130 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010131 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10132 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010133 assert(Name);
10134
Douglas Gregor6ccab972010-12-16 01:14:37 +000010135 // Check for unexpanded parameter packs.
10136 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10137 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10138 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10139 return 0;
10140
John McCall67d1a672009-08-06 02:15:43 +000010141 // The context we found the declaration in, or in which we should
10142 // create the declaration.
10143 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010144 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010145 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010146 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010147
John McCall337ec3d2010-10-12 23:13:28 +000010148 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010149
John McCall337ec3d2010-10-12 23:13:28 +000010150 // There are four cases here.
10151 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010152 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010153 // there as appropriate.
10154 // Recover from invalid scope qualifiers as if they just weren't there.
10155 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010156 // C++0x [namespace.memdef]p3:
10157 // If the name in a friend declaration is neither qualified nor
10158 // a template-id and the declaration is a function or an
10159 // elaborated-type-specifier, the lookup to determine whether
10160 // the entity has been previously declared shall not consider
10161 // any scopes outside the innermost enclosing namespace.
10162 // C++0x [class.friend]p11:
10163 // If a friend declaration appears in a local class and the name
10164 // specified is an unqualified name, a prior declaration is
10165 // looked up without considering scopes that are outside the
10166 // innermost enclosing non-class scope. For a friend function
10167 // declaration, if there is no prior declaration, the program is
10168 // ill-formed.
10169 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010170 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010171
John McCall29ae6e52010-10-13 05:45:15 +000010172 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010173 DC = CurContext;
10174 while (true) {
10175 // Skip class contexts. If someone can cite chapter and verse
10176 // for this behavior, that would be nice --- it's what GCC and
10177 // EDG do, and it seems like a reasonable intent, but the spec
10178 // really only says that checks for unqualified existing
10179 // declarations should stop at the nearest enclosing namespace,
10180 // not that they should only consider the nearest enclosing
10181 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010182 while (DC->isRecord())
10183 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010184
John McCall68263142009-11-18 22:49:29 +000010185 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010186
10187 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010188 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010189 break;
John McCall29ae6e52010-10-13 05:45:15 +000010190
John McCall8a407372010-10-14 22:22:28 +000010191 if (isTemplateId) {
10192 if (isa<TranslationUnitDecl>(DC)) break;
10193 } else {
10194 if (DC->isFileContext()) break;
10195 }
John McCall67d1a672009-08-06 02:15:43 +000010196 DC = DC->getParent();
10197 }
10198
10199 // C++ [class.friend]p1: A friend of a class is a function or
10200 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010201 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010202 // Most C++ 98 compilers do seem to give an error here, so
10203 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010204 if (!Previous.empty() && DC->Equals(CurContext))
10205 Diag(DS.getFriendSpecLoc(),
10206 getLangOptions().CPlusPlus0x ?
10207 diag::warn_cxx98_compat_friend_is_member :
10208 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010209
John McCall380aaa42010-10-13 06:22:15 +000010210 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010211
Douglas Gregor883af832011-10-10 01:11:59 +000010212 // C++ [class.friend]p6:
10213 // A function can be defined in a friend declaration of a class if and
10214 // only if the class is a non-local class (9.8), the function name is
10215 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010216 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010217 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10218 }
10219
John McCall337ec3d2010-10-12 23:13:28 +000010220 // - There's a non-dependent scope specifier, in which case we
10221 // compute it and do a previous lookup there for a function
10222 // or function template.
10223 } else if (!SS.getScopeRep()->isDependent()) {
10224 DC = computeDeclContext(SS);
10225 if (!DC) return 0;
10226
10227 if (RequireCompleteDeclContext(SS, DC)) return 0;
10228
10229 LookupQualifiedName(Previous, DC);
10230
10231 // Ignore things found implicitly in the wrong scope.
10232 // TODO: better diagnostics for this case. Suggesting the right
10233 // qualified scope would be nice...
10234 LookupResult::Filter F = Previous.makeFilter();
10235 while (F.hasNext()) {
10236 NamedDecl *D = F.next();
10237 if (!DC->InEnclosingNamespaceSetOf(
10238 D->getDeclContext()->getRedeclContext()))
10239 F.erase();
10240 }
10241 F.done();
10242
10243 if (Previous.empty()) {
10244 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010245 Diag(Loc, diag::err_qualified_friend_not_found)
10246 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010247 return 0;
10248 }
10249
10250 // C++ [class.friend]p1: A friend of a class is a function or
10251 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010252 if (DC->Equals(CurContext))
10253 Diag(DS.getFriendSpecLoc(),
10254 getLangOptions().CPlusPlus0x ?
10255 diag::warn_cxx98_compat_friend_is_member :
10256 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010257
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010258 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010259 // C++ [class.friend]p6:
10260 // A function can be defined in a friend declaration of a class if and
10261 // only if the class is a non-local class (9.8), the function name is
10262 // unqualified, and the function has namespace scope.
10263 SemaDiagnosticBuilder DB
10264 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10265
10266 DB << SS.getScopeRep();
10267 if (DC->isFileContext())
10268 DB << FixItHint::CreateRemoval(SS.getRange());
10269 SS.clear();
10270 }
John McCall337ec3d2010-10-12 23:13:28 +000010271
10272 // - There's a scope specifier that does not match any template
10273 // parameter lists, in which case we use some arbitrary context,
10274 // create a method or method template, and wait for instantiation.
10275 // - There's a scope specifier that does match some template
10276 // parameter lists, which we don't handle right now.
10277 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010278 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010279 // C++ [class.friend]p6:
10280 // A function can be defined in a friend declaration of a class if and
10281 // only if the class is a non-local class (9.8), the function name is
10282 // unqualified, and the function has namespace scope.
10283 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10284 << SS.getScopeRep();
10285 }
10286
John McCall337ec3d2010-10-12 23:13:28 +000010287 DC = CurContext;
10288 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010289 }
Douglas Gregor883af832011-10-10 01:11:59 +000010290
John McCall29ae6e52010-10-13 05:45:15 +000010291 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010292 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010293 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10294 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10295 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010296 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010297 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10298 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010299 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010300 }
John McCall67d1a672009-08-06 02:15:43 +000010301 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010302
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010303 // FIXME: This is an egregious hack to cope with cases where the scope stack
10304 // does not contain the declaration context, i.e., in an out-of-line
10305 // definition of a class.
10306 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10307 if (!DCScope) {
10308 FakeDCScope.setEntity(DC);
10309 DCScope = &FakeDCScope;
10310 }
10311
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010312 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010313 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10314 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010315 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010316
Douglas Gregor182ddf02009-09-28 00:08:27 +000010317 assert(ND->getDeclContext() == DC);
10318 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010319
John McCallab88d972009-08-31 22:39:49 +000010320 // Add the function declaration to the appropriate lookup tables,
10321 // adjusting the redeclarations list as necessary. We don't
10322 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010323 //
John McCallab88d972009-08-31 22:39:49 +000010324 // Also update the scope-based lookup if the target context's
10325 // lookup context is in lexical scope.
10326 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010327 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010328 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010329 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010330 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010331 }
John McCall02cace72009-08-28 07:59:38 +000010332
10333 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010334 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010335 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010336 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010337 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010338
John McCall337ec3d2010-10-12 23:13:28 +000010339 if (ND->isInvalidDecl())
10340 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010341 else {
10342 FunctionDecl *FD;
10343 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10344 FD = FTD->getTemplatedDecl();
10345 else
10346 FD = cast<FunctionDecl>(ND);
10347
10348 // Mark templated-scope function declarations as unsupported.
10349 if (FD->getNumTemplateParameterLists())
10350 FrD->setUnsupportedFriend(true);
10351 }
John McCall337ec3d2010-10-12 23:13:28 +000010352
John McCalld226f652010-08-21 09:40:31 +000010353 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010354}
10355
John McCalld226f652010-08-21 09:40:31 +000010356void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10357 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010358
Sebastian Redl50de12f2009-03-24 22:27:57 +000010359 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10360 if (!Fn) {
10361 Diag(DelLoc, diag::err_deleted_non_function);
10362 return;
10363 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010364 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010365 Diag(DelLoc, diag::err_deleted_decl_not_first);
10366 Diag(Prev->getLocation(), diag::note_previous_declaration);
10367 // If the declaration wasn't the first, we delete the function anyway for
10368 // recovery.
10369 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010370 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010371}
Sebastian Redl13e88542009-04-27 21:33:24 +000010372
Sean Hunte4246a62011-05-12 06:15:49 +000010373void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10374 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10375
10376 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010377 if (MD->getParent()->isDependentType()) {
10378 MD->setDefaulted();
10379 MD->setExplicitlyDefaulted();
10380 return;
10381 }
10382
Sean Hunte4246a62011-05-12 06:15:49 +000010383 CXXSpecialMember Member = getSpecialMember(MD);
10384 if (Member == CXXInvalid) {
10385 Diag(DefaultLoc, diag::err_default_special_members);
10386 return;
10387 }
10388
10389 MD->setDefaulted();
10390 MD->setExplicitlyDefaulted();
10391
Sean Huntcd10dec2011-05-23 23:14:04 +000010392 // If this definition appears within the record, do the checking when
10393 // the record is complete.
10394 const FunctionDecl *Primary = MD;
10395 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10396 // Find the uninstantiated declaration that actually had the '= default'
10397 // on it.
10398 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10399
10400 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010401 return;
10402
10403 switch (Member) {
10404 case CXXDefaultConstructor: {
10405 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10406 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010407 if (!CD->isInvalidDecl())
10408 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10409 break;
10410 }
10411
10412 case CXXCopyConstructor: {
10413 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10414 CheckExplicitlyDefaultedCopyConstructor(CD);
10415 if (!CD->isInvalidDecl())
10416 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010417 break;
10418 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010419
Sean Hunt2b188082011-05-14 05:23:28 +000010420 case CXXCopyAssignment: {
10421 CheckExplicitlyDefaultedCopyAssignment(MD);
10422 if (!MD->isInvalidDecl())
10423 DefineImplicitCopyAssignment(DefaultLoc, MD);
10424 break;
10425 }
10426
Sean Huntcb45a0f2011-05-12 22:46:25 +000010427 case CXXDestructor: {
10428 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10429 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010430 if (!DD->isInvalidDecl())
10431 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010432 break;
10433 }
10434
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010435 case CXXMoveConstructor: {
10436 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10437 CheckExplicitlyDefaultedMoveConstructor(CD);
10438 if (!CD->isInvalidDecl())
10439 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010440 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010441 }
Sean Hunt82713172011-05-25 23:16:36 +000010442
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010443 case CXXMoveAssignment: {
10444 CheckExplicitlyDefaultedMoveAssignment(MD);
10445 if (!MD->isInvalidDecl())
10446 DefineImplicitMoveAssignment(DefaultLoc, MD);
10447 break;
10448 }
10449
10450 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010451 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010452 }
10453 } else {
10454 Diag(DefaultLoc, diag::err_default_special_members);
10455 }
10456}
10457
Sebastian Redl13e88542009-04-27 21:33:24 +000010458static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010459 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010460 Stmt *SubStmt = *CI;
10461 if (!SubStmt)
10462 continue;
10463 if (isa<ReturnStmt>(SubStmt))
10464 Self.Diag(SubStmt->getSourceRange().getBegin(),
10465 diag::err_return_in_constructor_handler);
10466 if (!isa<Expr>(SubStmt))
10467 SearchForReturnInStmt(Self, SubStmt);
10468 }
10469}
10470
10471void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10472 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10473 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10474 SearchForReturnInStmt(*this, Handler);
10475 }
10476}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010477
Mike Stump1eb44332009-09-09 15:08:12 +000010478bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010479 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010480 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10481 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010482
Chandler Carruth73857792010-02-15 11:53:20 +000010483 if (Context.hasSameType(NewTy, OldTy) ||
10484 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010485 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010486
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010487 // Check if the return types are covariant
10488 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010489
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010490 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010491 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10492 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010493 NewClassTy = NewPT->getPointeeType();
10494 OldClassTy = OldPT->getPointeeType();
10495 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010496 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10497 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10498 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10499 NewClassTy = NewRT->getPointeeType();
10500 OldClassTy = OldRT->getPointeeType();
10501 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010502 }
10503 }
Mike Stump1eb44332009-09-09 15:08:12 +000010504
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010505 // The return types aren't either both pointers or references to a class type.
10506 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010507 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010508 diag::err_different_return_type_for_overriding_virtual_function)
10509 << New->getDeclName() << NewTy << OldTy;
10510 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010511
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010512 return true;
10513 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010514
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010515 // C++ [class.virtual]p6:
10516 // If the return type of D::f differs from the return type of B::f, the
10517 // class type in the return type of D::f shall be complete at the point of
10518 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010519 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10520 if (!RT->isBeingDefined() &&
10521 RequireCompleteType(New->getLocation(), NewClassTy,
10522 PDiag(diag::err_covariant_return_incomplete)
10523 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010524 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010525 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010526
Douglas Gregora4923eb2009-11-16 21:35:15 +000010527 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010528 // Check if the new class derives from the old class.
10529 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10530 Diag(New->getLocation(),
10531 diag::err_covariant_return_not_derived)
10532 << New->getDeclName() << NewTy << OldTy;
10533 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10534 return true;
10535 }
Mike Stump1eb44332009-09-09 15:08:12 +000010536
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010537 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010538 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010539 diag::err_covariant_return_inaccessible_base,
10540 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10541 // FIXME: Should this point to the return type?
10542 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010543 // FIXME: this note won't trigger for delayed access control
10544 // diagnostics, and it's impossible to get an undelayed error
10545 // here from access control during the original parse because
10546 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010547 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10548 return true;
10549 }
10550 }
Mike Stump1eb44332009-09-09 15:08:12 +000010551
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010552 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010553 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010554 Diag(New->getLocation(),
10555 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010556 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010557 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10558 return true;
10559 };
Mike Stump1eb44332009-09-09 15:08:12 +000010560
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010561
10562 // The new class type must have the same or less qualifiers as the old type.
10563 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10564 Diag(New->getLocation(),
10565 diag::err_covariant_return_type_class_type_more_qualified)
10566 << New->getDeclName() << NewTy << OldTy;
10567 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10568 return true;
10569 };
Mike Stump1eb44332009-09-09 15:08:12 +000010570
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010571 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010572}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010573
Douglas Gregor4ba31362009-12-01 17:24:26 +000010574/// \brief Mark the given method pure.
10575///
10576/// \param Method the method to be marked pure.
10577///
10578/// \param InitRange the source range that covers the "0" initializer.
10579bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010580 SourceLocation EndLoc = InitRange.getEnd();
10581 if (EndLoc.isValid())
10582 Method->setRangeEnd(EndLoc);
10583
Douglas Gregor4ba31362009-12-01 17:24:26 +000010584 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10585 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010586 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010587 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010588
10589 if (!Method->isInvalidDecl())
10590 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10591 << Method->getDeclName() << InitRange;
10592 return true;
10593}
10594
John McCall731ad842009-12-19 09:28:58 +000010595/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10596/// an initializer for the out-of-line declaration 'Dcl'. The scope
10597/// is a fresh scope pushed for just this purpose.
10598///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010599/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10600/// static data member of class X, names should be looked up in the scope of
10601/// class X.
John McCalld226f652010-08-21 09:40:31 +000010602void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010603 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010604 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010605
John McCall731ad842009-12-19 09:28:58 +000010606 // We should only get called for declarations with scope specifiers, like:
10607 // int foo::bar;
10608 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010609 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010610}
10611
10612/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010613/// initializer for the out-of-line declaration 'D'.
10614void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010615 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010616 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010617
John McCall731ad842009-12-19 09:28:58 +000010618 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010619 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010620}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010621
10622/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10623/// C++ if/switch/while/for statement.
10624/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010625DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010626 // C++ 6.4p2:
10627 // The declarator shall not specify a function or an array.
10628 // The type-specifier-seq shall not contain typedef and shall not declare a
10629 // new class or enumeration.
10630 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10631 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010632
10633 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010634 if (!Dcl)
10635 return true;
10636
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010637 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10638 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010639 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010640 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010641 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010642
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010643 return Dcl;
10644}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010645
Douglas Gregordfe65432011-07-28 19:11:31 +000010646void Sema::LoadExternalVTableUses() {
10647 if (!ExternalSource)
10648 return;
10649
10650 SmallVector<ExternalVTableUse, 4> VTables;
10651 ExternalSource->ReadUsedVTables(VTables);
10652 SmallVector<VTableUse, 4> NewUses;
10653 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10654 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10655 = VTablesUsed.find(VTables[I].Record);
10656 // Even if a definition wasn't required before, it may be required now.
10657 if (Pos != VTablesUsed.end()) {
10658 if (!Pos->second && VTables[I].DefinitionRequired)
10659 Pos->second = true;
10660 continue;
10661 }
10662
10663 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10664 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10665 }
10666
10667 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10668}
10669
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010670void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10671 bool DefinitionRequired) {
10672 // Ignore any vtable uses in unevaluated operands or for classes that do
10673 // not have a vtable.
10674 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10675 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010676 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010677 return;
10678
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010679 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010680 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010681 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10682 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10683 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10684 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010685 // If we already had an entry, check to see if we are promoting this vtable
10686 // to required a definition. If so, we need to reappend to the VTableUses
10687 // list, since we may have already processed the first entry.
10688 if (DefinitionRequired && !Pos.first->second) {
10689 Pos.first->second = true;
10690 } else {
10691 // Otherwise, we can early exit.
10692 return;
10693 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010694 }
10695
10696 // Local classes need to have their virtual members marked
10697 // immediately. For all other classes, we mark their virtual members
10698 // at the end of the translation unit.
10699 if (Class->isLocalClass())
10700 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010701 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010702 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010703}
10704
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010705bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010706 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010707 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010708 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010709
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010710 // Note: The VTableUses vector could grow as a result of marking
10711 // the members of a class as "used", so we check the size each
10712 // time through the loop and prefer indices (with are stable) to
10713 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010714 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010715 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010716 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010717 if (!Class)
10718 continue;
10719
10720 SourceLocation Loc = VTableUses[I].second;
10721
10722 // If this class has a key function, but that key function is
10723 // defined in another translation unit, we don't need to emit the
10724 // vtable even though we're using it.
10725 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010726 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010727 switch (KeyFunction->getTemplateSpecializationKind()) {
10728 case TSK_Undeclared:
10729 case TSK_ExplicitSpecialization:
10730 case TSK_ExplicitInstantiationDeclaration:
10731 // The key function is in another translation unit.
10732 continue;
10733
10734 case TSK_ExplicitInstantiationDefinition:
10735 case TSK_ImplicitInstantiation:
10736 // We will be instantiating the key function.
10737 break;
10738 }
10739 } else if (!KeyFunction) {
10740 // If we have a class with no key function that is the subject
10741 // of an explicit instantiation declaration, suppress the
10742 // vtable; it will live with the explicit instantiation
10743 // definition.
10744 bool IsExplicitInstantiationDeclaration
10745 = Class->getTemplateSpecializationKind()
10746 == TSK_ExplicitInstantiationDeclaration;
10747 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10748 REnd = Class->redecls_end();
10749 R != REnd; ++R) {
10750 TemplateSpecializationKind TSK
10751 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10752 if (TSK == TSK_ExplicitInstantiationDeclaration)
10753 IsExplicitInstantiationDeclaration = true;
10754 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10755 IsExplicitInstantiationDeclaration = false;
10756 break;
10757 }
10758 }
10759
10760 if (IsExplicitInstantiationDeclaration)
10761 continue;
10762 }
10763
10764 // Mark all of the virtual members of this class as referenced, so
10765 // that we can build a vtable. Then, tell the AST consumer that a
10766 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010767 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010768 MarkVirtualMembersReferenced(Loc, Class);
10769 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10770 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10771
10772 // Optionally warn if we're emitting a weak vtable.
10773 if (Class->getLinkage() == ExternalLinkage &&
10774 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010775 const FunctionDecl *KeyFunctionDef = 0;
10776 if (!KeyFunction ||
10777 (KeyFunction->hasBody(KeyFunctionDef) &&
10778 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010779 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10780 TSK_ExplicitInstantiationDefinition
10781 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10782 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010783 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010784 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010785 VTableUses.clear();
10786
Douglas Gregor78844032011-04-22 22:25:37 +000010787 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010788}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010789
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010790void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10791 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010792 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10793 e = RD->method_end(); i != e; ++i) {
10794 CXXMethodDecl *MD = *i;
10795
10796 // C++ [basic.def.odr]p2:
10797 // [...] A virtual member function is used if it is not pure. [...]
10798 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010799 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010800 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010801
10802 // Only classes that have virtual bases need a VTT.
10803 if (RD->getNumVBases() == 0)
10804 return;
10805
10806 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10807 e = RD->bases_end(); i != e; ++i) {
10808 const CXXRecordDecl *Base =
10809 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010810 if (Base->getNumVBases() == 0)
10811 continue;
10812 MarkVirtualMembersReferenced(Loc, Base);
10813 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010814}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010815
10816/// SetIvarInitializers - This routine builds initialization ASTs for the
10817/// Objective-C implementation whose ivars need be initialized.
10818void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10819 if (!getLangOptions().CPlusPlus)
10820 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010821 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010822 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010823 CollectIvarsToConstructOrDestruct(OID, ivars);
10824 if (ivars.empty())
10825 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010826 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010827 for (unsigned i = 0; i < ivars.size(); i++) {
10828 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010829 if (Field->isInvalidDecl())
10830 continue;
10831
Sean Huntcbb67482011-01-08 20:30:50 +000010832 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010833 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10834 InitializationKind InitKind =
10835 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10836
10837 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010838 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010839 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010840 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010841 // Note, MemberInit could actually come back empty if no initialization
10842 // is required (e.g., because it would call a trivial default constructor)
10843 if (!MemberInit.get() || MemberInit.isInvalid())
10844 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010845
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010846 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010847 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10848 SourceLocation(),
10849 MemberInit.takeAs<Expr>(),
10850 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010851 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010852
10853 // Be sure that the destructor is accessible and is marked as referenced.
10854 if (const RecordType *RecordTy
10855 = Context.getBaseElementType(Field->getType())
10856 ->getAs<RecordType>()) {
10857 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010858 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010859 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010860 CheckDestructorAccess(Field->getLocation(), Destructor,
10861 PDiag(diag::err_access_dtor_ivar)
10862 << Context.getBaseElementType(Field->getType()));
10863 }
10864 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010865 }
10866 ObjCImplementation->setIvarInitializers(Context,
10867 AllToInit.data(), AllToInit.size());
10868 }
10869}
Sean Huntfe57eef2011-05-04 05:57:24 +000010870
Sean Huntebcbe1d2011-05-04 23:29:54 +000010871static
10872void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10873 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10874 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10875 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10876 Sema &S) {
10877 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10878 CE = Current.end();
10879 if (Ctor->isInvalidDecl())
10880 return;
10881
10882 const FunctionDecl *FNTarget = 0;
10883 CXXConstructorDecl *Target;
10884
10885 // We ignore the result here since if we don't have a body, Target will be
10886 // null below.
10887 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10888 Target
10889= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10890
10891 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10892 // Avoid dereferencing a null pointer here.
10893 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10894
10895 if (!Current.insert(Canonical))
10896 return;
10897
10898 // We know that beyond here, we aren't chaining into a cycle.
10899 if (!Target || !Target->isDelegatingConstructor() ||
10900 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10901 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10902 Valid.insert(*CI);
10903 Current.clear();
10904 // We've hit a cycle.
10905 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10906 Current.count(TCanonical)) {
10907 // If we haven't diagnosed this cycle yet, do so now.
10908 if (!Invalid.count(TCanonical)) {
10909 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010910 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010911 << Ctor;
10912
10913 // Don't add a note for a function delegating directo to itself.
10914 if (TCanonical != Canonical)
10915 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10916
10917 CXXConstructorDecl *C = Target;
10918 while (C->getCanonicalDecl() != Canonical) {
10919 (void)C->getTargetConstructor()->hasBody(FNTarget);
10920 assert(FNTarget && "Ctor cycle through bodiless function");
10921
10922 C
10923 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10924 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10925 }
10926 }
10927
10928 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10929 Invalid.insert(*CI);
10930 Current.clear();
10931 } else {
10932 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10933 }
10934}
10935
10936
Sean Huntfe57eef2011-05-04 05:57:24 +000010937void Sema::CheckDelegatingCtorCycles() {
10938 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10939
Sean Huntebcbe1d2011-05-04 23:29:54 +000010940 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10941 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010942
Douglas Gregor0129b562011-07-27 21:57:17 +000010943 for (DelegatingCtorDeclsType::iterator
10944 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010945 E = DelegatingCtorDecls.end();
10946 I != E; ++I) {
10947 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010948 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010949
10950 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10951 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010952}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000010953
10954/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10955Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10956 // Implicitly declared functions (e.g. copy constructors) are
10957 // __host__ __device__
10958 if (D->isImplicit())
10959 return CFT_HostDevice;
10960
10961 if (D->hasAttr<CUDAGlobalAttr>())
10962 return CFT_Global;
10963
10964 if (D->hasAttr<CUDADeviceAttr>()) {
10965 if (D->hasAttr<CUDAHostAttr>())
10966 return CFT_HostDevice;
10967 else
10968 return CFT_Device;
10969 }
10970
10971 return CFT_Host;
10972}
10973
10974bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10975 CUDAFunctionTarget CalleeTarget) {
10976 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10977 // Callable from the device only."
10978 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10979 return true;
10980
10981 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10982 // Callable from the host only."
10983 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10984 // Callable from the host only."
10985 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10986 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
10987 return true;
10988
10989 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
10990 return true;
10991
10992 return false;
10993}