blob: a6d7d63b3a164ece983891d312ac22c811e54df9 [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,
David Blaikief2116622012-01-24 06:03:59 +00001771 DS, IdLoc, MultiInitializer(InitList),
1772 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 Redl6df65482011-09-24 17:48:25 +00001788 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001789 DS, IdLoc, MultiInitializer(LParenLoc, Args,
1790 NumArgs, RParenLoc),
Sebastian Redl6df65482011-09-24 17:48:25 +00001791 EllipsisLoc);
1792}
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,
1828 const MultiInitializer &Args,
1829 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 Redl6df65482011-09-24 17:48:25 +00001867 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1868
1869 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001870 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001871 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001872 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001873 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001874 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001875 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001876
1877 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001878 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001879 } else if (DS.getTypeSpecType() == TST_decltype) {
1880 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001881 } else {
1882 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1883 LookupParsedName(R, S, &SS);
1884
1885 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1886 if (!TyD) {
1887 if (R.isAmbiguous()) return true;
1888
John McCallfd225442010-04-09 19:01:14 +00001889 // We don't want access-control diagnostics here.
1890 R.suppressDiagnostics();
1891
Douglas Gregor7a886e12010-01-19 06:46:48 +00001892 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1893 bool NotUnknownSpecialization = false;
1894 DeclContext *DC = computeDeclContext(SS, false);
1895 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1896 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1897
1898 if (!NotUnknownSpecialization) {
1899 // When the scope specifier can refer to a member of an unknown
1900 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001901 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1902 SS.getWithLocInContext(Context),
1903 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001904 if (BaseType.isNull())
1905 return true;
1906
Douglas Gregor7a886e12010-01-19 06:46:48 +00001907 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001908 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001909 }
1910 }
1911
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001912 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001913 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001914 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001915 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001916 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001917 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001918 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1919 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1920 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001921 // We have found a non-static data member with a similar
1922 // name to what was typed; complain and initialize that
1923 // member.
1924 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1925 << MemberOrBase << true << CorrectedQuotedStr
1926 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1927 Diag(Member->getLocation(), diag::note_previous_decl)
1928 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001929
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001930 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001931 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001932 const CXXBaseSpecifier *DirectBaseSpec;
1933 const CXXBaseSpecifier *VirtualBaseSpec;
1934 if (FindBaseInitializer(*this, ClassDecl,
1935 Context.getTypeDeclType(Type),
1936 DirectBaseSpec, VirtualBaseSpec)) {
1937 // We have found a direct or virtual base class with a
1938 // similar name to what was typed; complain and initialize
1939 // that base class.
1940 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001941 << MemberOrBase << false << CorrectedQuotedStr
1942 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001943
1944 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1945 : VirtualBaseSpec;
1946 Diag(BaseSpec->getSourceRange().getBegin(),
1947 diag::note_base_class_specified_here)
1948 << BaseSpec->getType()
1949 << BaseSpec->getSourceRange();
1950
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001951 TyD = Type;
1952 }
1953 }
1954 }
1955
Douglas Gregor7a886e12010-01-19 06:46:48 +00001956 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001957 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl6df65482011-09-24 17:48:25 +00001958 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001959 return true;
1960 }
John McCall2b194412009-12-21 10:41:20 +00001961 }
1962
Douglas Gregor7a886e12010-01-19 06:46:48 +00001963 if (BaseType.isNull()) {
1964 BaseType = Context.getTypeDeclType(TyD);
1965 if (SS.isSet()) {
1966 NestedNameSpecifier *Qualifier =
1967 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001968
Douglas Gregor7a886e12010-01-19 06:46:48 +00001969 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001970 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001971 }
John McCall2b194412009-12-21 10:41:20 +00001972 }
1973 }
Mike Stump1eb44332009-09-09 15:08:12 +00001974
John McCalla93c9342009-12-07 02:54:59 +00001975 if (!TInfo)
1976 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001977
Sebastian Redl6df65482011-09-24 17:48:25 +00001978 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001979}
1980
Chandler Carruth81c64772011-09-03 01:14:15 +00001981/// Checks a member initializer expression for cases where reference (or
1982/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001983static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1984 Expr *Init,
1985 SourceLocation IdLoc) {
1986 QualType MemberTy = Member->getType();
1987
1988 // We only handle pointers and references currently.
1989 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1990 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1991 return;
1992
1993 const bool IsPointer = MemberTy->isPointerType();
1994 if (IsPointer) {
1995 if (const UnaryOperator *Op
1996 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1997 // The only case we're worried about with pointers requires taking the
1998 // address.
1999 if (Op->getOpcode() != UO_AddrOf)
2000 return;
2001
2002 Init = Op->getSubExpr();
2003 } else {
2004 // We only handle address-of expression initializers for pointers.
2005 return;
2006 }
2007 }
2008
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002009 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2010 // Taking the address of a temporary will be diagnosed as a hard error.
2011 if (IsPointer)
2012 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002013
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002014 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2015 << Member << Init->getSourceRange();
2016 } else if (const DeclRefExpr *DRE
2017 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2018 // We only warn when referring to a non-reference parameter declaration.
2019 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2020 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002021 return;
2022
2023 S.Diag(Init->getExprLoc(),
2024 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2025 : diag::warn_bind_ref_member_to_parameter)
2026 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002027 } else {
2028 // Other initializers are fine.
2029 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002030 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002031
2032 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2033 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002034}
2035
John McCallb4190042009-11-04 23:02:40 +00002036/// Checks an initializer expression for use of uninitialized fields, such as
2037/// containing the field that is being initialized. Returns true if there is an
2038/// uninitialized field was used an updates the SourceLocation parameter; false
2039/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002040static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002041 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002042 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002043 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2044
Nick Lewycky43ad1822010-06-15 07:32:55 +00002045 if (isa<CallExpr>(S)) {
2046 // Do not descend into function calls or constructors, as the use
2047 // of an uninitialized field may be valid. One would have to inspect
2048 // the contents of the function/ctor to determine if it is safe or not.
2049 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2050 // may be safe, depending on what the function/ctor does.
2051 return false;
2052 }
2053 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2054 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002055
2056 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2057 // The member expression points to a static data member.
2058 assert(VD->isStaticDataMember() &&
2059 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002060 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002061 return false;
2062 }
2063
2064 if (isa<EnumConstantDecl>(RhsField)) {
2065 // The member expression points to an enum.
2066 return false;
2067 }
2068
John McCallb4190042009-11-04 23:02:40 +00002069 if (RhsField == LhsField) {
2070 // Initializing a field with itself. Throw a warning.
2071 // But wait; there are exceptions!
2072 // Exception #1: The field may not belong to this record.
2073 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002074 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002075 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2076 // Even though the field matches, it does not belong to this record.
2077 return false;
2078 }
2079 // None of the exceptions triggered; return true to indicate an
2080 // uninitialized field was used.
2081 *L = ME->getMemberLoc();
2082 return true;
2083 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002084 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002085 // sizeof/alignof doesn't reference contents, do not warn.
2086 return false;
2087 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2088 // address-of doesn't reference contents (the pointer may be dereferenced
2089 // in the same expression but it would be rare; and weird).
2090 if (UOE->getOpcode() == UO_AddrOf)
2091 return false;
John McCallb4190042009-11-04 23:02:40 +00002092 }
John McCall7502c1d2011-02-13 04:07:26 +00002093 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002094 if (!*it) {
2095 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002096 continue;
2097 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002098 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2099 return true;
John McCallb4190042009-11-04 23:02:40 +00002100 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002101 return false;
John McCallb4190042009-11-04 23:02:40 +00002102}
2103
John McCallf312b1e2010-08-26 23:41:50 +00002104MemInitResult
Sebastian Redl6df65482011-09-24 17:48:25 +00002105Sema::BuildMemberInitializer(ValueDecl *Member,
2106 const MultiInitializer &Args,
2107 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
Peter Collingbournefef21892011-10-23 18:59:44 +00002113 if (Args.DiagnoseUnexpandedParameterPack(*this))
2114 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 Redl6df65482011-09-24 17:48:25 +00002123 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2124 I != E; ++I) {
John McCallb4190042009-11-04 23:02:40 +00002125 SourceLocation L;
Sebastian Redl6df65482011-09-24 17:48:25 +00002126 Expr *Arg = *I;
2127 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2128 Arg = DIE->getInit();
2129 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002130 // FIXME: Return true in the case when other fields are used before being
2131 // uninitialized. For example, let this field be the i'th field. When
2132 // initializing the i'th field, throw a warning if any of the >= i'th
2133 // fields are used, as they are not yet initialized.
2134 // Right now we are only handling the case where the i'th field uses
2135 // itself in its initializer.
2136 Diag(L, diag::warn_field_is_uninit);
2137 }
2138 }
2139
Sebastian Redl6df65482011-09-24 17:48:25 +00002140 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002141
Chandler Carruth894aed92010-12-06 09:23:57 +00002142 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00002143 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002144 // Can't check initialization for a member of dependent type or when
2145 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002146 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002147
John McCallf85e1932011-06-15 23:02:42 +00002148 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002149 } else {
2150 // Initialize the member.
2151 InitializedEntity MemberEntity =
2152 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2153 : InitializedEntity::InitializeMember(IndirectMember, 0);
2154 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002155 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2156 Args.getEndLoc());
John McCallb4eb64d2010-10-08 02:01:28 +00002157
Sebastian Redl6df65482011-09-24 17:48:25 +00002158 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruth894aed92010-12-06 09:23:57 +00002159 if (MemberInit.isInvalid())
2160 return true;
2161
Sebastian Redl6df65482011-09-24 17:48:25 +00002162 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002163
2164 // C++0x [class.base.init]p7:
2165 // The initialization of each base and member constitutes a
2166 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002167 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002168 if (MemberInit.isInvalid())
2169 return true;
2170
2171 // If we are in a dependent context, template instantiation will
2172 // perform this type-checking again. Just save the arguments that we
2173 // received in a ParenListExpr.
2174 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2175 // of the information that we have about the member
2176 // initializer. However, deconstructing the ASTs is a dicey process,
2177 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002178 if (CurContext->isDependentContext()) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002179 Init = Args.CreateInitExpr(Context,
2180 Member->getType().getNonReferenceType());
Chandler Carruth81c64772011-09-03 01:14:15 +00002181 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002182 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002183 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2184 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002185 }
2186
Chandler Carruth894aed92010-12-06 09:23:57 +00002187 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00002188 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002189 IdLoc, Args.getStartLoc(),
2190 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002191 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00002192 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002193 IdLoc, Args.getStartLoc(),
2194 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002195 }
Eli Friedman59c04372009-07-29 19:44:27 +00002196}
2197
John McCallf312b1e2010-08-26 23:41:50 +00002198MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00002199Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002200 const MultiInitializer &Args,
Sean Hunt41717662011-02-26 19:13:13 +00002201 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002202 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002203 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002204 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002205 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002206 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002207
Sean Hunt41717662011-02-26 19:13:13 +00002208 // Initialize the object.
2209 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2210 QualType(ClassDecl->getTypeForDecl(), 0));
2211 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002212 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2213 Args.getEndLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002214
Sebastian Redl6df65482011-09-24 17:48:25 +00002215 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Sean Hunt41717662011-02-26 19:13:13 +00002216 if (DelegationInit.isInvalid())
2217 return true;
2218
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002219 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2220 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002221
Sebastian Redl6df65482011-09-24 17:48:25 +00002222 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002223
2224 // C++0x [class.base.init]p7:
2225 // The initialization of each base and member constitutes a
2226 // full-expression.
2227 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2228 if (DelegationInit.isInvalid())
2229 return true;
2230
Douglas Gregor76852c22011-11-01 01:16:03 +00002231 return new (Context) CXXCtorInitializer(Context, TInfo, Args.getStartLoc(),
Sean Hunt41717662011-02-26 19:13:13 +00002232 DelegationInit.takeAs<Expr>(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002233 Args.getEndLoc());
Sean Hunt97fcc492011-01-08 19:20:43 +00002234}
2235
2236MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002237Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002238 const MultiInitializer &Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002239 CXXRecordDecl *ClassDecl,
2240 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002241 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002242
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002243 SourceLocation BaseLoc
2244 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002245
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002246 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2247 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2248 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2249
2250 // C++ [class.base.init]p2:
2251 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002252 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002253 // of that class, the mem-initializer is ill-formed. A
2254 // mem-initializer-list can initialize a base class using any
2255 // name that denotes that base class type.
2256 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2257
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002258 if (EllipsisLoc.isValid()) {
2259 // This is a pack expansion.
2260 if (!BaseType->containsUnexpandedParameterPack()) {
2261 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl6df65482011-09-24 17:48:25 +00002262 << SourceRange(BaseLoc, Args.getEndLoc());
2263
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002264 EllipsisLoc = SourceLocation();
2265 }
2266 } else {
2267 // Check for any unexpanded parameter packs.
2268 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2269 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002270
2271 if (Args.DiagnoseUnexpandedParameterPack(*this))
2272 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002273 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002274
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002275 // Check for direct and virtual base classes.
2276 const CXXBaseSpecifier *DirectBaseSpec = 0;
2277 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2278 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002279 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2280 BaseType))
Douglas Gregor76852c22011-11-01 01:16:03 +00002281 return BuildDelegatingInitializer(BaseTInfo, Args, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002282
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002283 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2284 VirtualBaseSpec);
2285
2286 // C++ [base.class.init]p2:
2287 // Unless the mem-initializer-id names a nonstatic data member of the
2288 // constructor's class or a direct or virtual base of that class, the
2289 // mem-initializer is ill-formed.
2290 if (!DirectBaseSpec && !VirtualBaseSpec) {
2291 // If the class has any dependent bases, then it's possible that
2292 // one of those types will resolve to the same type as
2293 // BaseType. Therefore, just treat this as a dependent base
2294 // class initialization. FIXME: Should we try to check the
2295 // initialization anyway? It seems odd.
2296 if (ClassDecl->hasAnyDependentBases())
2297 Dependent = true;
2298 else
2299 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2300 << BaseType << Context.getTypeDeclType(ClassDecl)
2301 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2302 }
2303 }
2304
2305 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002306 // Can't check initialization for a base of dependent type or when
2307 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002308 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman59c04372009-07-29 19:44:27 +00002309
John McCallf85e1932011-06-15 23:02:42 +00002310 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Sebastian Redl6df65482011-09-24 17:48:25 +00002312 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2313 /*IsVirtual=*/false,
2314 Args.getStartLoc(), BaseInit,
2315 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002316 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002317
2318 // C++ [base.class.init]p2:
2319 // If a mem-initializer-id is ambiguous because it designates both
2320 // a direct non-virtual base class and an inherited virtual base
2321 // class, the mem-initializer is ill-formed.
2322 if (DirectBaseSpec && VirtualBaseSpec)
2323 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002324 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002325
2326 CXXBaseSpecifier *BaseSpec
2327 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2328 if (!BaseSpec)
2329 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2330
2331 // Initialize the base.
2332 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00002333 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002334 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002335 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2336 Args.getEndLoc());
2337
2338 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002339 if (BaseInit.isInvalid())
2340 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002341
Sebastian Redl6df65482011-09-24 17:48:25 +00002342 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2343
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002344 // C++0x [class.base.init]p7:
2345 // The initialization of each base and member constitutes a
2346 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002347 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002348 if (BaseInit.isInvalid())
2349 return true;
2350
2351 // If we are in a dependent context, template instantiation will
2352 // perform this type-checking again. Just save the arguments that we
2353 // received in a ParenListExpr.
2354 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2355 // of the information that we have about the base
2356 // initializer. However, deconstructing the ASTs is a dicey process,
2357 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002358 if (CurContext->isDependentContext())
2359 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002360
Sean Huntcbb67482011-01-08 20:30:50 +00002361 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002362 BaseSpec->isVirtual(),
2363 Args.getStartLoc(),
2364 BaseInit.takeAs<Expr>(),
2365 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002366}
2367
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002368// Create a static_cast\<T&&>(expr).
2369static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2370 QualType ExprType = E->getType();
2371 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2372 SourceLocation ExprLoc = E->getLocStart();
2373 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2374 TargetType, ExprLoc);
2375
2376 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2377 SourceRange(ExprLoc, ExprLoc),
2378 E->getSourceRange()).take();
2379}
2380
Anders Carlssone5ef7402010-04-23 03:10:23 +00002381/// ImplicitInitializerKind - How an implicit base or member initializer should
2382/// initialize its base or member.
2383enum ImplicitInitializerKind {
2384 IIK_Default,
2385 IIK_Copy,
2386 IIK_Move
2387};
2388
Anders Carlssondefefd22010-04-23 02:00:02 +00002389static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002390BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002391 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002392 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002393 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002394 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002395 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002396 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2397 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002398
John McCall60d7b3a2010-08-24 06:29:42 +00002399 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002400
2401 switch (ImplicitInitKind) {
2402 case IIK_Default: {
2403 InitializationKind InitKind
2404 = InitializationKind::CreateDefault(Constructor->getLocation());
2405 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2406 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002407 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002408 break;
2409 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002410
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002411 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002412 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002413 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002414 ParmVarDecl *Param = Constructor->getParamDecl(0);
2415 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002416
Anders Carlssone5ef7402010-04-23 03:10:23 +00002417 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002418 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2419 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002420 Constructor->getLocation(), ParamType,
2421 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002422
Eli Friedman5f2987c2012-02-02 03:46:19 +00002423 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2424
Anders Carlssonc7957502010-04-24 22:02:54 +00002425 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002426 QualType ArgTy =
2427 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2428 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002429
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002430 if (Moving) {
2431 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2432 }
2433
John McCallf871d0c2010-08-07 06:22:56 +00002434 CXXCastPath BasePath;
2435 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002436 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2437 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002438 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002439 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002440
Anders Carlssone5ef7402010-04-23 03:10:23 +00002441 InitializationKind InitKind
2442 = InitializationKind::CreateDirect(Constructor->getLocation(),
2443 SourceLocation(), SourceLocation());
2444 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2445 &CopyCtorArg, 1);
2446 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002447 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002448 break;
2449 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002450 }
John McCall9ae2f072010-08-23 23:25:46 +00002451
Douglas Gregor53c374f2010-12-07 00:41:46 +00002452 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002453 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002454 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002455
Anders Carlssondefefd22010-04-23 02:00:02 +00002456 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002457 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002458 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2459 SourceLocation()),
2460 BaseSpec->isVirtual(),
2461 SourceLocation(),
2462 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002463 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002464 SourceLocation());
2465
Anders Carlssondefefd22010-04-23 02:00:02 +00002466 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002467}
2468
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002469static bool RefersToRValueRef(Expr *MemRef) {
2470 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2471 return Referenced->getType()->isRValueReferenceType();
2472}
2473
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002474static bool
2475BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002476 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002477 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002478 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002479 if (Field->isInvalidDecl())
2480 return true;
2481
Chandler Carruthf186b542010-06-29 23:50:44 +00002482 SourceLocation Loc = Constructor->getLocation();
2483
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002484 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2485 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002486 ParmVarDecl *Param = Constructor->getParamDecl(0);
2487 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002488
2489 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002490 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2491 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002492
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002493 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002494 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2495 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002496 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002497
Eli Friedman5f2987c2012-02-02 03:46:19 +00002498 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2499
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002500 if (Moving) {
2501 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2502 }
2503
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002504 // Build a reference to this field within the parameter.
2505 CXXScopeSpec SS;
2506 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2507 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002508 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2509 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002510 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002511 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002512 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002513 ParamType, Loc,
2514 /*IsArrow=*/false,
2515 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002516 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002517 /*FirstQualifierInScope=*/0,
2518 MemberLookup,
2519 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002520 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002521 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002522
2523 // C++11 [class.copy]p15:
2524 // - if a member m has rvalue reference type T&&, it is direct-initialized
2525 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002526 if (RefersToRValueRef(CtorArg.get())) {
2527 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002528 }
2529
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002530 // When the field we are copying is an array, create index variables for
2531 // each dimension of the array. We use these index variables to subscript
2532 // the source array, and other clients (e.g., CodeGen) will perform the
2533 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002534 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002535 QualType BaseType = Field->getType();
2536 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002537 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002538 while (const ConstantArrayType *Array
2539 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002540 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002541 // Create the iteration variable for this array index.
2542 IdentifierInfo *IterationVarName = 0;
2543 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002544 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002545 llvm::raw_svector_ostream OS(Str);
2546 OS << "__i" << IndexVariables.size();
2547 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2548 }
2549 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002550 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002551 IterationVarName, SizeType,
2552 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002553 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002554 IndexVariables.push_back(IterationVar);
2555
2556 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002557 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002558 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002559 assert(!IterationVarRef.isInvalid() &&
2560 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002561 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2562 assert(!IterationVarRef.isInvalid() &&
2563 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002564
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002565 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002566 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002567 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002568 Loc);
2569 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002570 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002571
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002572 BaseType = Array->getElementType();
2573 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002574
2575 // The array subscript expression is an lvalue, which is wrong for moving.
2576 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002577 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002578
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002579 // Construct the entity that we will be initializing. For an array, this
2580 // will be first element in the array, which may require several levels
2581 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002582 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002583 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002584 if (Indirect)
2585 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2586 else
2587 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002588 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2589 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2590 0,
2591 Entities.back()));
2592
2593 // Direct-initialize to use the copy constructor.
2594 InitializationKind InitKind =
2595 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2596
Sebastian Redl74e611a2011-09-04 18:14:28 +00002597 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002598 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002599 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002600
John McCall60d7b3a2010-08-24 06:29:42 +00002601 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002602 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002603 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002604 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002605 if (MemberInit.isInvalid())
2606 return true;
2607
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002608 if (Indirect) {
2609 assert(IndexVariables.size() == 0 &&
2610 "Indirect field improperly initialized");
2611 CXXMemberInit
2612 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2613 Loc, Loc,
2614 MemberInit.takeAs<Expr>(),
2615 Loc);
2616 } else
2617 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2618 Loc, MemberInit.takeAs<Expr>(),
2619 Loc,
2620 IndexVariables.data(),
2621 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002622 return false;
2623 }
2624
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002625 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2626
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002627 QualType FieldBaseElementType =
2628 SemaRef.Context.getBaseElementType(Field->getType());
2629
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002630 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002631 InitializedEntity InitEntity
2632 = Indirect? InitializedEntity::InitializeMember(Indirect)
2633 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002634 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002635 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002636
2637 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002638 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002639 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002640
Douglas Gregor53c374f2010-12-07 00:41:46 +00002641 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002642 if (MemberInit.isInvalid())
2643 return true;
2644
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002645 if (Indirect)
2646 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2647 Indirect, Loc,
2648 Loc,
2649 MemberInit.get(),
2650 Loc);
2651 else
2652 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2653 Field, Loc, Loc,
2654 MemberInit.get(),
2655 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002656 return false;
2657 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002658
Sean Hunt1f2f3842011-05-17 00:19:05 +00002659 if (!Field->getParent()->isUnion()) {
2660 if (FieldBaseElementType->isReferenceType()) {
2661 SemaRef.Diag(Constructor->getLocation(),
2662 diag::err_uninitialized_member_in_ctor)
2663 << (int)Constructor->isImplicit()
2664 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2665 << 0 << Field->getDeclName();
2666 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2667 return true;
2668 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002669
Sean Hunt1f2f3842011-05-17 00:19:05 +00002670 if (FieldBaseElementType.isConstQualified()) {
2671 SemaRef.Diag(Constructor->getLocation(),
2672 diag::err_uninitialized_member_in_ctor)
2673 << (int)Constructor->isImplicit()
2674 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2675 << 1 << Field->getDeclName();
2676 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2677 return true;
2678 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002679 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002680
John McCallf85e1932011-06-15 23:02:42 +00002681 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2682 FieldBaseElementType->isObjCRetainableType() &&
2683 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2684 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2685 // Instant objects:
2686 // Default-initialize Objective-C pointers to NULL.
2687 CXXMemberInit
2688 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2689 Loc, Loc,
2690 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2691 Loc);
2692 return false;
2693 }
2694
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002695 // Nothing to initialize.
2696 CXXMemberInit = 0;
2697 return false;
2698}
John McCallf1860e52010-05-20 23:23:51 +00002699
2700namespace {
2701struct BaseAndFieldInfo {
2702 Sema &S;
2703 CXXConstructorDecl *Ctor;
2704 bool AnyErrorsInInits;
2705 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002706 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002707 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002708
2709 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2710 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002711 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2712 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002713 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002714 else if (Generated && Ctor->isMoveConstructor())
2715 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002716 else
2717 IIK = IIK_Default;
2718 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002719
2720 bool isImplicitCopyOrMove() const {
2721 switch (IIK) {
2722 case IIK_Copy:
2723 case IIK_Move:
2724 return true;
2725
2726 case IIK_Default:
2727 return false;
2728 }
David Blaikie30263482012-01-20 21:50:17 +00002729
2730 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002731 }
John McCallf1860e52010-05-20 23:23:51 +00002732};
2733}
2734
Richard Smitha4950662011-09-19 13:34:43 +00002735/// \brief Determine whether the given indirect field declaration is somewhere
2736/// within an anonymous union.
2737static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2738 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2739 CEnd = F->chain_end();
2740 C != CEnd; ++C)
2741 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2742 if (Record->isUnion())
2743 return true;
2744
2745 return false;
2746}
2747
Douglas Gregorddb21472011-11-02 23:04:16 +00002748/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2749/// array type.
2750static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2751 if (T->isIncompleteArrayType())
2752 return true;
2753
2754 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2755 if (!ArrayT->getSize())
2756 return true;
2757
2758 T = ArrayT->getElementType();
2759 }
2760
2761 return false;
2762}
2763
Richard Smith7a614d82011-06-11 17:19:42 +00002764static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002765 FieldDecl *Field,
2766 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002767
Chandler Carruthe861c602010-06-30 02:59:29 +00002768 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002769 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002770 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002771 return false;
2772 }
2773
Richard Smith7a614d82011-06-11 17:19:42 +00002774 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2775 // has a brace-or-equal-initializer, the entity is initialized as specified
2776 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002777 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002778 CXXCtorInitializer *Init;
2779 if (Indirect)
2780 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2781 SourceLocation(),
2782 SourceLocation(), 0,
2783 SourceLocation());
2784 else
2785 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2786 SourceLocation(),
2787 SourceLocation(), 0,
2788 SourceLocation());
2789 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002790 return false;
2791 }
2792
Richard Smithc115f632011-09-18 11:14:50 +00002793 // Don't build an implicit initializer for union members if none was
2794 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002795 if (Field->getParent()->isUnion() ||
2796 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002797 return false;
2798
Douglas Gregorddb21472011-11-02 23:04:16 +00002799 // Don't initialize incomplete or zero-length arrays.
2800 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2801 return false;
2802
John McCallf1860e52010-05-20 23:23:51 +00002803 // Don't try to build an implicit initializer if there were semantic
2804 // errors in any of the initializers (and therefore we might be
2805 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002806 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002807 return false;
2808
Sean Huntcbb67482011-01-08 20:30:50 +00002809 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002810 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2811 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002812 return true;
John McCallf1860e52010-05-20 23:23:51 +00002813
Francois Pichet00eb3f92010-12-04 09:14:42 +00002814 if (Init)
2815 Info.AllToInit.push_back(Init);
2816
John McCallf1860e52010-05-20 23:23:51 +00002817 return false;
2818}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002819
2820bool
2821Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2822 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002823 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002824 Constructor->setNumCtorInitializers(1);
2825 CXXCtorInitializer **initializer =
2826 new (Context) CXXCtorInitializer*[1];
2827 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2828 Constructor->setCtorInitializers(initializer);
2829
Sean Huntb76af9c2011-05-03 23:05:34 +00002830 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002831 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002832 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2833 }
2834
Sean Huntc1598702011-05-05 00:05:47 +00002835 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002836
Sean Hunt059ce0d2011-05-01 07:04:31 +00002837 return false;
2838}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002839
John McCallb77115d2011-06-17 00:18:42 +00002840bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2841 CXXCtorInitializer **Initializers,
2842 unsigned NumInitializers,
2843 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002844 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002845 // Just store the initializers as written, they will be checked during
2846 // instantiation.
2847 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002848 Constructor->setNumCtorInitializers(NumInitializers);
2849 CXXCtorInitializer **baseOrMemberInitializers =
2850 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002851 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002852 NumInitializers * sizeof(CXXCtorInitializer*));
2853 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002854 }
2855
2856 return false;
2857 }
2858
John McCallf1860e52010-05-20 23:23:51 +00002859 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002860
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002861 // We need to build the initializer AST according to order of construction
2862 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002863 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002864 if (!ClassDecl)
2865 return true;
2866
Eli Friedman80c30da2009-11-09 19:20:36 +00002867 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002868
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002869 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002870 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002871
2872 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002873 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002874 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002875 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002876 }
2877
Anders Carlsson711f34a2010-04-21 19:52:01 +00002878 // Keep track of the direct virtual bases.
2879 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2880 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2881 E = ClassDecl->bases_end(); I != E; ++I) {
2882 if (I->isVirtual())
2883 DirectVBases.insert(I);
2884 }
2885
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002886 // Push virtual bases before others.
2887 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2888 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2889
Sean Huntcbb67482011-01-08 20:30:50 +00002890 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002891 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2892 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002893 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002894 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002895 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002896 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002897 VBase, IsInheritedVirtualBase,
2898 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002899 HadError = true;
2900 continue;
2901 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002902
John McCallf1860e52010-05-20 23:23:51 +00002903 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002904 }
2905 }
Mike Stump1eb44332009-09-09 15:08:12 +00002906
John McCallf1860e52010-05-20 23:23:51 +00002907 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002908 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2909 E = ClassDecl->bases_end(); Base != E; ++Base) {
2910 // Virtuals are in the virtual base list and already constructed.
2911 if (Base->isVirtual())
2912 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002913
Sean Huntcbb67482011-01-08 20:30:50 +00002914 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002915 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2916 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002917 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002918 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002919 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002920 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002921 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002922 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002923 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002924 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002925
John McCallf1860e52010-05-20 23:23:51 +00002926 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002927 }
2928 }
Mike Stump1eb44332009-09-09 15:08:12 +00002929
John McCallf1860e52010-05-20 23:23:51 +00002930 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002931 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2932 MemEnd = ClassDecl->decls_end();
2933 Mem != MemEnd; ++Mem) {
2934 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002935 // C++ [class.bit]p2:
2936 // A declaration for a bit-field that omits the identifier declares an
2937 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2938 // initialized.
2939 if (F->isUnnamedBitfield())
2940 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002941
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002942 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002943 // handle anonymous struct/union fields based on their individual
2944 // indirect fields.
2945 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2946 continue;
2947
2948 if (CollectFieldInitializer(*this, Info, F))
2949 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002950 continue;
2951 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002952
2953 // Beyond this point, we only consider default initialization.
2954 if (Info.IIK != IIK_Default)
2955 continue;
2956
2957 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2958 if (F->getType()->isIncompleteArrayType()) {
2959 assert(ClassDecl->hasFlexibleArrayMember() &&
2960 "Incomplete array type is not valid");
2961 continue;
2962 }
2963
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002964 // Initialize each field of an anonymous struct individually.
2965 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2966 HadError = true;
2967
2968 continue;
2969 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002970 }
Mike Stump1eb44332009-09-09 15:08:12 +00002971
John McCallf1860e52010-05-20 23:23:51 +00002972 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002973 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002974 Constructor->setNumCtorInitializers(NumInitializers);
2975 CXXCtorInitializer **baseOrMemberInitializers =
2976 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002977 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002978 NumInitializers * sizeof(CXXCtorInitializer*));
2979 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002980
John McCallef027fe2010-03-16 21:39:52 +00002981 // Constructors implicitly reference the base and member
2982 // destructors.
2983 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2984 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002985 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002986
2987 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002988}
2989
Eli Friedman6347f422009-07-21 19:28:10 +00002990static void *GetKeyForTopLevelField(FieldDecl *Field) {
2991 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002992 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002993 if (RT->getDecl()->isAnonymousStructOrUnion())
2994 return static_cast<void *>(RT->getDecl());
2995 }
2996 return static_cast<void *>(Field);
2997}
2998
Anders Carlssonea356fb2010-04-02 05:42:15 +00002999static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003000 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003001}
3002
Anders Carlssonea356fb2010-04-02 05:42:15 +00003003static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003004 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003005 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003006 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003007
Eli Friedman6347f422009-07-21 19:28:10 +00003008 // For fields injected into the class via declaration of an anonymous union,
3009 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003010 FieldDecl *Field = Member->getAnyMember();
3011
John McCall3c3ccdb2010-04-10 09:28:51 +00003012 // If the field is a member of an anonymous struct or union, our key
3013 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003014 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003015 if (RD->isAnonymousStructOrUnion()) {
3016 while (true) {
3017 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3018 if (Parent->isAnonymousStructOrUnion())
3019 RD = Parent;
3020 else
3021 break;
3022 }
3023
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003024 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003025 }
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003027 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003028}
3029
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003030static void
3031DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003032 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003033 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003034 unsigned NumInits) {
3035 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003036 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003037
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003038 // Don't check initializers order unless the warning is enabled at the
3039 // location of at least one initializer.
3040 bool ShouldCheckOrder = false;
3041 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003042 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003043 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3044 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003045 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003046 ShouldCheckOrder = true;
3047 break;
3048 }
3049 }
3050 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003051 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003052
John McCalld6ca8da2010-04-10 07:37:23 +00003053 // Build the list of bases and members in the order that they'll
3054 // actually be initialized. The explicit initializers should be in
3055 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003056 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003057
Anders Carlsson071d6102010-04-02 03:38:04 +00003058 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3059
John McCalld6ca8da2010-04-10 07:37:23 +00003060 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003061 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003062 ClassDecl->vbases_begin(),
3063 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003064 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003065
John McCalld6ca8da2010-04-10 07:37:23 +00003066 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003067 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003068 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003069 if (Base->isVirtual())
3070 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003071 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003072 }
Mike Stump1eb44332009-09-09 15:08:12 +00003073
John McCalld6ca8da2010-04-10 07:37:23 +00003074 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003075 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003076 E = ClassDecl->field_end(); Field != E; ++Field) {
3077 if (Field->isUnnamedBitfield())
3078 continue;
3079
John McCalld6ca8da2010-04-10 07:37:23 +00003080 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003081 }
3082
John McCalld6ca8da2010-04-10 07:37:23 +00003083 unsigned NumIdealInits = IdealInitKeys.size();
3084 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003085
Sean Huntcbb67482011-01-08 20:30:50 +00003086 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003087 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003088 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003089 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003090
3091 // Scan forward to try to find this initializer in the idealized
3092 // initializers list.
3093 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3094 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003095 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003096
3097 // If we didn't find this initializer, it must be because we
3098 // scanned past it on a previous iteration. That can only
3099 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003100 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003101 Sema::SemaDiagnosticBuilder D =
3102 SemaRef.Diag(PrevInit->getSourceLocation(),
3103 diag::warn_initializer_out_of_order);
3104
Francois Pichet00eb3f92010-12-04 09:14:42 +00003105 if (PrevInit->isAnyMemberInitializer())
3106 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003107 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003108 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003109
Francois Pichet00eb3f92010-12-04 09:14:42 +00003110 if (Init->isAnyMemberInitializer())
3111 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003112 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003113 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003114
3115 // Move back to the initializer's location in the ideal list.
3116 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3117 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003118 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003119
3120 assert(IdealIndex != NumIdealInits &&
3121 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003122 }
John McCalld6ca8da2010-04-10 07:37:23 +00003123
3124 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003125 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003126}
3127
John McCall3c3ccdb2010-04-10 09:28:51 +00003128namespace {
3129bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003130 CXXCtorInitializer *Init,
3131 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003132 if (!PrevInit) {
3133 PrevInit = Init;
3134 return false;
3135 }
3136
3137 if (FieldDecl *Field = Init->getMember())
3138 S.Diag(Init->getSourceLocation(),
3139 diag::err_multiple_mem_initialization)
3140 << Field->getDeclName()
3141 << Init->getSourceRange();
3142 else {
John McCallf4c73712011-01-19 06:33:43 +00003143 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003144 assert(BaseClass && "neither field nor base");
3145 S.Diag(Init->getSourceLocation(),
3146 diag::err_multiple_base_initialization)
3147 << QualType(BaseClass, 0)
3148 << Init->getSourceRange();
3149 }
3150 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3151 << 0 << PrevInit->getSourceRange();
3152
3153 return true;
3154}
3155
Sean Huntcbb67482011-01-08 20:30:50 +00003156typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003157typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3158
3159bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003160 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003161 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003162 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003163 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003164 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003165
3166 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003167 if (Parent->isUnion()) {
3168 UnionEntry &En = Unions[Parent];
3169 if (En.first && En.first != Child) {
3170 S.Diag(Init->getSourceLocation(),
3171 diag::err_multiple_mem_union_initialization)
3172 << Field->getDeclName()
3173 << Init->getSourceRange();
3174 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3175 << 0 << En.second->getSourceRange();
3176 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003177 }
3178 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003179 En.first = Child;
3180 En.second = Init;
3181 }
David Blaikie6fe29652011-11-17 06:01:57 +00003182 if (!Parent->isAnonymousStructOrUnion())
3183 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003184 }
3185
3186 Child = Parent;
3187 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003188 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003189
3190 return false;
3191}
3192}
3193
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003194/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003195void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003196 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003197 CXXCtorInitializer **meminits,
3198 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003199 bool AnyErrors) {
3200 if (!ConstructorDecl)
3201 return;
3202
3203 AdjustDeclIfTemplate(ConstructorDecl);
3204
3205 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003206 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003207
3208 if (!Constructor) {
3209 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3210 return;
3211 }
3212
Sean Huntcbb67482011-01-08 20:30:50 +00003213 CXXCtorInitializer **MemInits =
3214 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003215
3216 // Mapping for the duplicate initializers check.
3217 // For member initializers, this is keyed with a FieldDecl*.
3218 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003219 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003220
3221 // Mapping for the inconsistent anonymous-union initializers check.
3222 RedundantUnionMap MemberUnions;
3223
Anders Carlssonea356fb2010-04-02 05:42:15 +00003224 bool HadError = false;
3225 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003226 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003227
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003228 // Set the source order index.
3229 Init->setSourceOrder(i);
3230
Francois Pichet00eb3f92010-12-04 09:14:42 +00003231 if (Init->isAnyMemberInitializer()) {
3232 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003233 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3234 CheckRedundantUnionInit(*this, Init, MemberUnions))
3235 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003236 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003237 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3238 if (CheckRedundantInit(*this, Init, Members[Key]))
3239 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003240 } else {
3241 assert(Init->isDelegatingInitializer());
3242 // This must be the only initializer
3243 if (i != 0 || NumMemInits > 1) {
3244 Diag(MemInits[0]->getSourceLocation(),
3245 diag::err_delegating_initializer_alone)
3246 << MemInits[0]->getSourceRange();
3247 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003248 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003249 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003250 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003251 // Return immediately as the initializer is set.
3252 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003253 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003254 }
3255
Anders Carlssonea356fb2010-04-02 05:42:15 +00003256 if (HadError)
3257 return;
3258
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003259 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003260
Sean Huntcbb67482011-01-08 20:30:50 +00003261 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003262}
3263
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003264void
John McCallef027fe2010-03-16 21:39:52 +00003265Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3266 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003267 // Ignore dependent contexts. Also ignore unions, since their members never
3268 // have destructors implicitly called.
3269 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003270 return;
John McCall58e6f342010-03-16 05:22:47 +00003271
3272 // FIXME: all the access-control diagnostics are positioned on the
3273 // field/base declaration. That's probably good; that said, the
3274 // user might reasonably want to know why the destructor is being
3275 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003276
Anders Carlsson9f853df2009-11-17 04:44:12 +00003277 // Non-static data members.
3278 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3279 E = ClassDecl->field_end(); I != E; ++I) {
3280 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003281 if (Field->isInvalidDecl())
3282 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003283
3284 // Don't destroy incomplete or zero-length arrays.
3285 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3286 continue;
3287
Anders Carlsson9f853df2009-11-17 04:44:12 +00003288 QualType FieldType = Context.getBaseElementType(Field->getType());
3289
3290 const RecordType* RT = FieldType->getAs<RecordType>();
3291 if (!RT)
3292 continue;
3293
3294 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003295 if (FieldClassDecl->isInvalidDecl())
3296 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003297 if (FieldClassDecl->hasTrivialDestructor())
3298 continue;
3299
Douglas Gregordb89f282010-07-01 22:47:18 +00003300 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003301 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003302 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003303 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003304 << Field->getDeclName()
3305 << FieldType);
3306
Eli Friedman5f2987c2012-02-02 03:46:19 +00003307 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003308 }
3309
John McCall58e6f342010-03-16 05:22:47 +00003310 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3311
Anders Carlsson9f853df2009-11-17 04:44:12 +00003312 // Bases.
3313 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3314 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003315 // Bases are always records in a well-formed non-dependent class.
3316 const RecordType *RT = Base->getType()->getAs<RecordType>();
3317
3318 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003319 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003320 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003321
John McCall58e6f342010-03-16 05:22:47 +00003322 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003323 // If our base class is invalid, we probably can't get its dtor anyway.
3324 if (BaseClassDecl->isInvalidDecl())
3325 continue;
3326 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003327 if (BaseClassDecl->hasTrivialDestructor())
3328 continue;
John McCall58e6f342010-03-16 05:22:47 +00003329
Douglas Gregordb89f282010-07-01 22:47:18 +00003330 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003331 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003332
3333 // FIXME: caret should be on the start of the class name
3334 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003335 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003336 << Base->getType()
3337 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003338
Eli Friedman5f2987c2012-02-02 03:46:19 +00003339 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003340 }
3341
3342 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003343 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3344 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003345
3346 // Bases are always records in a well-formed non-dependent class.
3347 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3348
3349 // Ignore direct virtual bases.
3350 if (DirectVirtualBases.count(RT))
3351 continue;
3352
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.
Fariborz Jahanian34374e62009-09-03 23:18:17 +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 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003364 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003365 << VBase->getType());
3366
Eli Friedman5f2987c2012-02-02 03:46:19 +00003367 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003368 }
3369}
3370
John McCalld226f652010-08-21 09:40:31 +00003371void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003372 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003373 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003374
Mike Stump1eb44332009-09-09 15:08:12 +00003375 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003376 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003377 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003378}
3379
Mike Stump1eb44332009-09-09 15:08:12 +00003380bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003381 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003382 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003383 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003384 else
John McCall94c3b562010-08-18 09:41:07 +00003385 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003386}
3387
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003388bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003389 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003390 if (!getLangOptions().CPlusPlus)
3391 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003392
Anders Carlsson11f21a02009-03-23 19:10:31 +00003393 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003394 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003395
Ted Kremenek6217b802009-07-29 21:53:49 +00003396 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003397 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003398 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003399 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003400
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003401 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003402 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003403 }
Mike Stump1eb44332009-09-09 15:08:12 +00003404
Ted Kremenek6217b802009-07-29 21:53:49 +00003405 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003406 if (!RT)
3407 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003408
John McCall86ff3082010-02-04 22:26:26 +00003409 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003410
John McCall94c3b562010-08-18 09:41:07 +00003411 // We can't answer whether something is abstract until it has a
3412 // definition. If it's currently being defined, we'll walk back
3413 // over all the declarations when we have a full definition.
3414 const CXXRecordDecl *Def = RD->getDefinition();
3415 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003416 return false;
3417
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003418 if (!RD->isAbstract())
3419 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003420
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003421 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003422 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003423
John McCall94c3b562010-08-18 09:41:07 +00003424 return true;
3425}
3426
3427void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3428 // Check if we've already emitted the list of pure virtual functions
3429 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003430 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003431 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003432
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003433 CXXFinalOverriderMap FinalOverriders;
3434 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003436 // Keep a set of seen pure methods so we won't diagnose the same method
3437 // more than once.
3438 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3439
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003440 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3441 MEnd = FinalOverriders.end();
3442 M != MEnd;
3443 ++M) {
3444 for (OverridingMethods::iterator SO = M->second.begin(),
3445 SOEnd = M->second.end();
3446 SO != SOEnd; ++SO) {
3447 // C++ [class.abstract]p4:
3448 // A class is abstract if it contains or inherits at least one
3449 // pure virtual function for which the final overrider is pure
3450 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003452 //
3453 if (SO->second.size() != 1)
3454 continue;
3455
3456 if (!SO->second.front().Method->isPure())
3457 continue;
3458
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003459 if (!SeenPureMethods.insert(SO->second.front().Method))
3460 continue;
3461
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003462 Diag(SO->second.front().Method->getLocation(),
3463 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003464 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003465 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003466 }
3467
3468 if (!PureVirtualClassDiagSet)
3469 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3470 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003471}
3472
Anders Carlsson8211eff2009-03-24 01:19:16 +00003473namespace {
John McCall94c3b562010-08-18 09:41:07 +00003474struct AbstractUsageInfo {
3475 Sema &S;
3476 CXXRecordDecl *Record;
3477 CanQualType AbstractType;
3478 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003479
John McCall94c3b562010-08-18 09:41:07 +00003480 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3481 : S(S), Record(Record),
3482 AbstractType(S.Context.getCanonicalType(
3483 S.Context.getTypeDeclType(Record))),
3484 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003485
John McCall94c3b562010-08-18 09:41:07 +00003486 void DiagnoseAbstractType() {
3487 if (Invalid) return;
3488 S.DiagnoseAbstractType(Record);
3489 Invalid = true;
3490 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003491
John McCall94c3b562010-08-18 09:41:07 +00003492 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3493};
3494
3495struct CheckAbstractUsage {
3496 AbstractUsageInfo &Info;
3497 const NamedDecl *Ctx;
3498
3499 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3500 : Info(Info), Ctx(Ctx) {}
3501
3502 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3503 switch (TL.getTypeLocClass()) {
3504#define ABSTRACT_TYPELOC(CLASS, PARENT)
3505#define TYPELOC(CLASS, PARENT) \
3506 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3507#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003508 }
John McCall94c3b562010-08-18 09:41:07 +00003509 }
Mike Stump1eb44332009-09-09 15:08:12 +00003510
John McCall94c3b562010-08-18 09:41:07 +00003511 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3512 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3513 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003514 if (!TL.getArg(I))
3515 continue;
3516
John McCall94c3b562010-08-18 09:41:07 +00003517 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3518 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003519 }
John McCall94c3b562010-08-18 09:41:07 +00003520 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003521
John McCall94c3b562010-08-18 09:41:07 +00003522 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3523 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3524 }
Mike Stump1eb44332009-09-09 15:08:12 +00003525
John McCall94c3b562010-08-18 09:41:07 +00003526 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3527 // Visit the type parameters from a permissive context.
3528 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3529 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3530 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3531 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3532 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3533 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003534 }
John McCall94c3b562010-08-18 09:41:07 +00003535 }
Mike Stump1eb44332009-09-09 15:08:12 +00003536
John McCall94c3b562010-08-18 09:41:07 +00003537 // Visit pointee types from a permissive context.
3538#define CheckPolymorphic(Type) \
3539 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3540 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3541 }
3542 CheckPolymorphic(PointerTypeLoc)
3543 CheckPolymorphic(ReferenceTypeLoc)
3544 CheckPolymorphic(MemberPointerTypeLoc)
3545 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003546 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003547
John McCall94c3b562010-08-18 09:41:07 +00003548 /// Handle all the types we haven't given a more specific
3549 /// implementation for above.
3550 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3551 // Every other kind of type that we haven't called out already
3552 // that has an inner type is either (1) sugar or (2) contains that
3553 // inner type in some way as a subobject.
3554 if (TypeLoc Next = TL.getNextTypeLoc())
3555 return Visit(Next, Sel);
3556
3557 // If there's no inner type and we're in a permissive context,
3558 // don't diagnose.
3559 if (Sel == Sema::AbstractNone) return;
3560
3561 // Check whether the type matches the abstract type.
3562 QualType T = TL.getType();
3563 if (T->isArrayType()) {
3564 Sel = Sema::AbstractArrayType;
3565 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003566 }
John McCall94c3b562010-08-18 09:41:07 +00003567 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3568 if (CT != Info.AbstractType) return;
3569
3570 // It matched; do some magic.
3571 if (Sel == Sema::AbstractArrayType) {
3572 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3573 << T << TL.getSourceRange();
3574 } else {
3575 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3576 << Sel << T << TL.getSourceRange();
3577 }
3578 Info.DiagnoseAbstractType();
3579 }
3580};
3581
3582void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3583 Sema::AbstractDiagSelID Sel) {
3584 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3585}
3586
3587}
3588
3589/// Check for invalid uses of an abstract type in a method declaration.
3590static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3591 CXXMethodDecl *MD) {
3592 // No need to do the check on definitions, which require that
3593 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003594 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003595 return;
3596
3597 // For safety's sake, just ignore it if we don't have type source
3598 // information. This should never happen for non-implicit methods,
3599 // but...
3600 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3601 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3602}
3603
3604/// Check for invalid uses of an abstract type within a class definition.
3605static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3606 CXXRecordDecl *RD) {
3607 for (CXXRecordDecl::decl_iterator
3608 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3609 Decl *D = *I;
3610 if (D->isImplicit()) continue;
3611
3612 // Methods and method templates.
3613 if (isa<CXXMethodDecl>(D)) {
3614 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3615 } else if (isa<FunctionTemplateDecl>(D)) {
3616 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3617 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3618
3619 // Fields and static variables.
3620 } else if (isa<FieldDecl>(D)) {
3621 FieldDecl *FD = cast<FieldDecl>(D);
3622 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3623 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3624 } else if (isa<VarDecl>(D)) {
3625 VarDecl *VD = cast<VarDecl>(D);
3626 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3627 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3628
3629 // Nested classes and class templates.
3630 } else if (isa<CXXRecordDecl>(D)) {
3631 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3632 } else if (isa<ClassTemplateDecl>(D)) {
3633 CheckAbstractClassUsage(Info,
3634 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3635 }
3636 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003637}
3638
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003639/// \brief Perform semantic checks on a class definition that has been
3640/// completing, introducing implicitly-declared members, checking for
3641/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003642void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003643 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003644 return;
3645
John McCall94c3b562010-08-18 09:41:07 +00003646 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3647 AbstractUsageInfo Info(*this, Record);
3648 CheckAbstractClassUsage(Info, Record);
3649 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003650
3651 // If this is not an aggregate type and has no user-declared constructor,
3652 // complain about any non-static data members of reference or const scalar
3653 // type, since they will never get initializers.
3654 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003655 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3656 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003657 bool Complained = false;
3658 for (RecordDecl::field_iterator F = Record->field_begin(),
3659 FEnd = Record->field_end();
3660 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003661 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003662 continue;
3663
Douglas Gregor325e5932010-04-15 00:00:53 +00003664 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003665 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003666 if (!Complained) {
3667 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3668 << Record->getTagKind() << Record;
3669 Complained = true;
3670 }
3671
3672 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3673 << F->getType()->isReferenceType()
3674 << F->getDeclName();
3675 }
3676 }
3677 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003678
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003679 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003680 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003681
3682 if (Record->getIdentifier()) {
3683 // C++ [class.mem]p13:
3684 // If T is the name of a class, then each of the following shall have a
3685 // name different from T:
3686 // - every member of every anonymous union that is a member of class T.
3687 //
3688 // C++ [class.mem]p14:
3689 // In addition, if class T has a user-declared constructor (12.1), every
3690 // non-static data member of class T shall have a name different from T.
3691 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003692 R.first != R.second; ++R.first) {
3693 NamedDecl *D = *R.first;
3694 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3695 isa<IndirectFieldDecl>(D)) {
3696 Diag(D->getLocation(), diag::err_member_name_of_class)
3697 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003698 break;
3699 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003700 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003701 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003702
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003703 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003704 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003705 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003706 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003707 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3708 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3709 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003710
3711 // See if a method overloads virtual methods in a base
3712 /// class without overriding any.
3713 if (!Record->isDependentType()) {
3714 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3715 MEnd = Record->method_end();
3716 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003717 if (!(*M)->isStatic())
3718 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003719 }
3720 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003721
Richard Smith9f569cc2011-10-01 02:31:28 +00003722 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3723 // function that is not a constructor declares that member function to be
3724 // const. [...] The class of which that function is a member shall be
3725 // a literal type.
3726 //
3727 // It's fine to diagnose constructors here too: such constructors cannot
3728 // produce a constant expression, so are ill-formed (no diagnostic required).
3729 //
3730 // If the class has virtual bases, any constexpr members will already have
3731 // been diagnosed by the checks performed on the member declaration, so
3732 // suppress this (less useful) diagnostic.
3733 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3734 !Record->isLiteral() && !Record->getNumVBases()) {
3735 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3736 MEnd = Record->method_end();
3737 M != MEnd; ++M) {
Eli Friedman9ec0ef32012-01-13 02:31:53 +00003738 if (M->isConstexpr() && M->isInstance()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003739 switch (Record->getTemplateSpecializationKind()) {
3740 case TSK_ImplicitInstantiation:
3741 case TSK_ExplicitInstantiationDeclaration:
3742 case TSK_ExplicitInstantiationDefinition:
3743 // If a template instantiates to a non-literal type, but its members
3744 // instantiate to constexpr functions, the template is technically
3745 // ill-formed, but we allow it for sanity. Such members are treated as
3746 // non-constexpr.
3747 (*M)->setConstexpr(false);
3748 continue;
3749
3750 case TSK_Undeclared:
3751 case TSK_ExplicitSpecialization:
3752 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3753 PDiag(diag::err_constexpr_method_non_literal));
3754 break;
3755 }
3756
3757 // Only produce one error per class.
3758 break;
3759 }
3760 }
3761 }
3762
Sebastian Redlf677ea32011-02-05 19:23:19 +00003763 // Declare inherited constructors. We do this eagerly here because:
3764 // - The standard requires an eager diagnostic for conflicting inherited
3765 // constructors from different classes.
3766 // - The lazy declaration of the other implicit constructors is so as to not
3767 // waste space and performance on classes that are not meant to be
3768 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3769 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003770 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003771
Sean Hunteb88ae52011-05-23 21:07:59 +00003772 if (!Record->isDependentType())
3773 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003774}
3775
3776void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003777 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3778 ME = Record->method_end();
3779 MI != ME; ++MI) {
3780 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3781 switch (getSpecialMember(*MI)) {
3782 case CXXDefaultConstructor:
3783 CheckExplicitlyDefaultedDefaultConstructor(
3784 cast<CXXConstructorDecl>(*MI));
3785 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003786
Sean Huntcb45a0f2011-05-12 22:46:25 +00003787 case CXXDestructor:
3788 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3789 break;
3790
3791 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003792 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3793 break;
3794
Sean Huntcb45a0f2011-05-12 22:46:25 +00003795 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003796 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003797 break;
3798
Sean Hunt82713172011-05-25 23:16:36 +00003799 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003800 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003801 break;
3802
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003803 case CXXMoveAssignment:
3804 CheckExplicitlyDefaultedMoveAssignment(*MI);
3805 break;
3806
3807 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003808 llvm_unreachable("non-special member explicitly defaulted!");
3809 }
Sean Hunt001cad92011-05-10 00:49:42 +00003810 }
3811 }
3812
Sean Hunt001cad92011-05-10 00:49:42 +00003813}
3814
3815void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3816 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3817
3818 // Whether this was the first-declared instance of the constructor.
3819 // This affects whether we implicitly add an exception spec (and, eventually,
3820 // constexpr). It is also ill-formed to explicitly default a constructor such
3821 // that it would be deleted. (C++0x [decl.fct.def.default])
3822 bool First = CD == CD->getCanonicalDecl();
3823
Sean Hunt49634cf2011-05-13 06:10:58 +00003824 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003825 if (CD->getNumParams() != 0) {
3826 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3827 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003828 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003829 }
3830
3831 ImplicitExceptionSpecification Spec
3832 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3833 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003834 if (EPI.ExceptionSpecType == EST_Delayed) {
3835 // Exception specification depends on some deferred part of the class. We'll
3836 // try again when the class's definition has been fully processed.
3837 return;
3838 }
Sean Hunt001cad92011-05-10 00:49:42 +00003839 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3840 *ExceptionType = Context.getFunctionType(
3841 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3842
Richard Smith61802452011-12-22 02:22:31 +00003843 // C++11 [dcl.fct.def.default]p2:
3844 // An explicitly-defaulted function may be declared constexpr only if it
3845 // would have been implicitly declared as constexpr,
3846 if (CD->isConstexpr()) {
3847 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3848 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3849 << CXXDefaultConstructor;
3850 HadError = true;
3851 }
3852 }
3853 // and may have an explicit exception-specification only if it is compatible
3854 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003855 if (CtorType->hasExceptionSpec()) {
3856 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003857 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003858 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003859 PDiag(),
3860 ExceptionType, SourceLocation(),
3861 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003862 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003863 }
Richard Smith61802452011-12-22 02:22:31 +00003864 }
3865
3866 // If a function is explicitly defaulted on its first declaration,
3867 if (First) {
3868 // -- it is implicitly considered to be constexpr if the implicit
3869 // definition would be,
3870 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3871
3872 // -- it is implicitly considered to have the same
3873 // exception-specification as if it had been implicitly declared
3874 //
3875 // FIXME: a compatible, but different, explicit exception specification
3876 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003877 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003878 }
Sean Huntca46d132011-05-12 03:51:48 +00003879
Sean Hunt49634cf2011-05-13 06:10:58 +00003880 if (HadError) {
3881 CD->setInvalidDecl();
3882 return;
3883 }
3884
Sean Hunte16da072011-10-10 06:18:57 +00003885 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003886 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003887 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003888 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003889 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003890 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003891 CD->setInvalidDecl();
3892 }
3893 }
3894}
3895
3896void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3897 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3898
3899 // Whether this was the first-declared instance of the constructor.
3900 bool First = CD == CD->getCanonicalDecl();
3901
3902 bool HadError = false;
3903 if (CD->getNumParams() != 1) {
3904 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3905 << CD->getSourceRange();
3906 HadError = true;
3907 }
3908
3909 ImplicitExceptionSpecification Spec(Context);
3910 bool Const;
3911 llvm::tie(Spec, Const) =
3912 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3913
3914 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3915 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3916 *ExceptionType = Context.getFunctionType(
3917 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3918
3919 // Check for parameter type matching.
3920 // This is a copy ctor so we know it's a cv-qualified reference to T.
3921 QualType ArgType = CtorType->getArgType(0);
3922 if (ArgType->getPointeeType().isVolatileQualified()) {
3923 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3924 HadError = true;
3925 }
3926 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3927 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3928 HadError = true;
3929 }
3930
Richard Smith61802452011-12-22 02:22:31 +00003931 // C++11 [dcl.fct.def.default]p2:
3932 // An explicitly-defaulted function may be declared constexpr only if it
3933 // would have been implicitly declared as constexpr,
3934 if (CD->isConstexpr()) {
3935 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3936 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3937 << CXXCopyConstructor;
3938 HadError = true;
3939 }
3940 }
3941 // and may have an explicit exception-specification only if it is compatible
3942 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003943 if (CtorType->hasExceptionSpec()) {
3944 if (CheckEquivalentExceptionSpec(
3945 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003946 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003947 PDiag(),
3948 ExceptionType, SourceLocation(),
3949 CtorType, CD->getLocation())) {
3950 HadError = true;
3951 }
Richard Smith61802452011-12-22 02:22:31 +00003952 }
3953
3954 // If a function is explicitly defaulted on its first declaration,
3955 if (First) {
3956 // -- it is implicitly considered to be constexpr if the implicit
3957 // definition would be,
3958 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3959
3960 // -- it is implicitly considered to have the same
3961 // exception-specification as if it had been implicitly declared, and
3962 //
3963 // FIXME: a compatible, but different, explicit exception specification
3964 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003965 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003966
3967 // -- [...] it shall have the same parameter type as if it had been
3968 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003969 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3970 }
3971
3972 if (HadError) {
3973 CD->setInvalidDecl();
3974 return;
3975 }
3976
Sean Huntc32d6842011-10-11 04:55:36 +00003977 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003978 if (First) {
3979 CD->setDeletedAsWritten();
3980 } else {
3981 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003982 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003983 CD->setInvalidDecl();
3984 }
Sean Huntca46d132011-05-12 03:51:48 +00003985 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003986}
Sean Hunt001cad92011-05-10 00:49:42 +00003987
Sean Hunt2b188082011-05-14 05:23:28 +00003988void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3989 assert(MD->isExplicitlyDefaulted());
3990
3991 // Whether this was the first-declared instance of the operator
3992 bool First = MD == MD->getCanonicalDecl();
3993
3994 bool HadError = false;
3995 if (MD->getNumParams() != 1) {
3996 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3997 << MD->getSourceRange();
3998 HadError = true;
3999 }
4000
4001 QualType ReturnType =
4002 MD->getType()->getAs<FunctionType>()->getResultType();
4003 if (!ReturnType->isLValueReferenceType() ||
4004 !Context.hasSameType(
4005 Context.getCanonicalType(ReturnType->getPointeeType()),
4006 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4007 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
4008 HadError = true;
4009 }
4010
4011 ImplicitExceptionSpecification Spec(Context);
4012 bool Const;
4013 llvm::tie(Spec, Const) =
4014 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4015
4016 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4017 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4018 *ExceptionType = Context.getFunctionType(
4019 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4020
Sean Hunt2b188082011-05-14 05:23:28 +00004021 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004022 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00004023 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004024 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00004025 } else {
4026 if (ArgType->getPointeeType().isVolatileQualified()) {
4027 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4028 HadError = true;
4029 }
4030 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4031 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4032 HadError = true;
4033 }
Sean Hunt2b188082011-05-14 05:23:28 +00004034 }
Sean Huntbe631222011-05-17 20:44:43 +00004035
Sean Hunt2b188082011-05-14 05:23:28 +00004036 if (OperType->getTypeQuals()) {
4037 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4038 HadError = true;
4039 }
4040
4041 if (OperType->hasExceptionSpec()) {
4042 if (CheckEquivalentExceptionSpec(
4043 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004044 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004045 PDiag(),
4046 ExceptionType, SourceLocation(),
4047 OperType, MD->getLocation())) {
4048 HadError = true;
4049 }
Richard Smith61802452011-12-22 02:22:31 +00004050 }
4051 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004052 // We set the declaration to have the computed exception spec here.
4053 // We duplicate the one parameter type.
4054 EPI.RefQualifier = OperType->getRefQualifier();
4055 EPI.ExtInfo = OperType->getExtInfo();
4056 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4057 }
4058
4059 if (HadError) {
4060 MD->setInvalidDecl();
4061 return;
4062 }
4063
4064 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4065 if (First) {
4066 MD->setDeletedAsWritten();
4067 } else {
4068 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004069 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004070 MD->setInvalidDecl();
4071 }
4072 }
4073}
4074
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004075void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4076 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4077
4078 // Whether this was the first-declared instance of the constructor.
4079 bool First = CD == CD->getCanonicalDecl();
4080
4081 bool HadError = false;
4082 if (CD->getNumParams() != 1) {
4083 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4084 << CD->getSourceRange();
4085 HadError = true;
4086 }
4087
4088 ImplicitExceptionSpecification Spec(
4089 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4090
4091 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4092 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4093 *ExceptionType = Context.getFunctionType(
4094 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4095
4096 // Check for parameter type matching.
4097 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4098 QualType ArgType = CtorType->getArgType(0);
4099 if (ArgType->getPointeeType().isVolatileQualified()) {
4100 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4101 HadError = true;
4102 }
4103 if (ArgType->getPointeeType().isConstQualified()) {
4104 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4105 HadError = true;
4106 }
4107
Richard Smith61802452011-12-22 02:22:31 +00004108 // C++11 [dcl.fct.def.default]p2:
4109 // An explicitly-defaulted function may be declared constexpr only if it
4110 // would have been implicitly declared as constexpr,
4111 if (CD->isConstexpr()) {
4112 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4113 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4114 << CXXMoveConstructor;
4115 HadError = true;
4116 }
4117 }
4118 // and may have an explicit exception-specification only if it is compatible
4119 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004120 if (CtorType->hasExceptionSpec()) {
4121 if (CheckEquivalentExceptionSpec(
4122 PDiag(diag::err_incorrect_defaulted_exception_spec)
4123 << CXXMoveConstructor,
4124 PDiag(),
4125 ExceptionType, SourceLocation(),
4126 CtorType, CD->getLocation())) {
4127 HadError = true;
4128 }
Richard Smith61802452011-12-22 02:22:31 +00004129 }
4130
4131 // If a function is explicitly defaulted on its first declaration,
4132 if (First) {
4133 // -- it is implicitly considered to be constexpr if the implicit
4134 // definition would be,
4135 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4136
4137 // -- it is implicitly considered to have the same
4138 // exception-specification as if it had been implicitly declared, and
4139 //
4140 // FIXME: a compatible, but different, explicit exception specification
4141 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004142 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004143
4144 // -- [...] it shall have the same parameter type as if it had been
4145 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004146 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4147 }
4148
4149 if (HadError) {
4150 CD->setInvalidDecl();
4151 return;
4152 }
4153
Sean Hunt769bb2d2011-10-11 06:43:29 +00004154 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004155 if (First) {
4156 CD->setDeletedAsWritten();
4157 } else {
4158 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4159 << CXXMoveConstructor;
4160 CD->setInvalidDecl();
4161 }
4162 }
4163}
4164
4165void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4166 assert(MD->isExplicitlyDefaulted());
4167
4168 // Whether this was the first-declared instance of the operator
4169 bool First = MD == MD->getCanonicalDecl();
4170
4171 bool HadError = false;
4172 if (MD->getNumParams() != 1) {
4173 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4174 << MD->getSourceRange();
4175 HadError = true;
4176 }
4177
4178 QualType ReturnType =
4179 MD->getType()->getAs<FunctionType>()->getResultType();
4180 if (!ReturnType->isLValueReferenceType() ||
4181 !Context.hasSameType(
4182 Context.getCanonicalType(ReturnType->getPointeeType()),
4183 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4184 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4185 HadError = true;
4186 }
4187
4188 ImplicitExceptionSpecification Spec(
4189 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4190
4191 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4192 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4193 *ExceptionType = Context.getFunctionType(
4194 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4195
4196 QualType ArgType = OperType->getArgType(0);
4197 if (!ArgType->isRValueReferenceType()) {
4198 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4199 HadError = true;
4200 } else {
4201 if (ArgType->getPointeeType().isVolatileQualified()) {
4202 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4203 HadError = true;
4204 }
4205 if (ArgType->getPointeeType().isConstQualified()) {
4206 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4207 HadError = true;
4208 }
4209 }
4210
4211 if (OperType->getTypeQuals()) {
4212 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4213 HadError = true;
4214 }
4215
4216 if (OperType->hasExceptionSpec()) {
4217 if (CheckEquivalentExceptionSpec(
4218 PDiag(diag::err_incorrect_defaulted_exception_spec)
4219 << CXXMoveAssignment,
4220 PDiag(),
4221 ExceptionType, SourceLocation(),
4222 OperType, MD->getLocation())) {
4223 HadError = true;
4224 }
Richard Smith61802452011-12-22 02:22:31 +00004225 }
4226 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004227 // We set the declaration to have the computed exception spec here.
4228 // We duplicate the one parameter type.
4229 EPI.RefQualifier = OperType->getRefQualifier();
4230 EPI.ExtInfo = OperType->getExtInfo();
4231 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4232 }
4233
4234 if (HadError) {
4235 MD->setInvalidDecl();
4236 return;
4237 }
4238
4239 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4240 if (First) {
4241 MD->setDeletedAsWritten();
4242 } else {
4243 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4244 << CXXMoveAssignment;
4245 MD->setInvalidDecl();
4246 }
4247 }
4248}
4249
Sean Huntcb45a0f2011-05-12 22:46:25 +00004250void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4251 assert(DD->isExplicitlyDefaulted());
4252
4253 // Whether this was the first-declared instance of the destructor.
4254 bool First = DD == DD->getCanonicalDecl();
4255
4256 ImplicitExceptionSpecification Spec
4257 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4258 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4259 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4260 *ExceptionType = Context.getFunctionType(
4261 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4262
4263 if (DtorType->hasExceptionSpec()) {
4264 if (CheckEquivalentExceptionSpec(
4265 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004266 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004267 PDiag(),
4268 ExceptionType, SourceLocation(),
4269 DtorType, DD->getLocation())) {
4270 DD->setInvalidDecl();
4271 return;
4272 }
Richard Smith61802452011-12-22 02:22:31 +00004273 }
4274 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004275 // We set the declaration to have the computed exception spec here.
4276 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004277 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004278 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4279 }
4280
4281 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004282 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004283 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004284 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004285 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004286 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004287 DD->setInvalidDecl();
4288 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004289 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004290}
4291
Sean Hunte16da072011-10-10 06:18:57 +00004292/// This function implements the following C++0x paragraphs:
4293/// - [class.ctor]/5
Sean Huntc32d6842011-10-11 04:55:36 +00004294/// - [class.copy]/11
Sean Hunte16da072011-10-10 06:18:57 +00004295bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4296 assert(!MD->isInvalidDecl());
4297 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004298 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004299 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004300 return false;
4301
Sean Hunte16da072011-10-10 06:18:57 +00004302 bool IsUnion = RD->isUnion();
4303 bool IsConstructor = false;
4304 bool IsAssignment = false;
4305 bool IsMove = false;
4306
4307 bool ConstArg = false;
4308
4309 switch (CSM) {
4310 case CXXDefaultConstructor:
4311 IsConstructor = true;
4312 break;
Sean Huntc32d6842011-10-11 04:55:36 +00004313 case CXXCopyConstructor:
4314 IsConstructor = true;
4315 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4316 break;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004317 case CXXMoveConstructor:
4318 IsConstructor = true;
4319 IsMove = true;
4320 break;
Sean Hunte16da072011-10-10 06:18:57 +00004321 default:
4322 llvm_unreachable("function only currently implemented for default ctors");
4323 }
4324
4325 SourceLocation Loc = MD->getLocation();
Sean Hunt71a682f2011-05-18 03:41:58 +00004326
Sean Huntc32d6842011-10-11 04:55:36 +00004327 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004328 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004329
Sean Huntcdee3fe2011-05-11 22:34:38 +00004330 bool AllConst = true;
4331
Sean Huntcdee3fe2011-05-11 22:34:38 +00004332 // We do this because we should never actually use an anonymous
4333 // union's constructor.
Sean Hunte16da072011-10-10 06:18:57 +00004334 if (IsUnion && RD->isAnonymousStructOrUnion())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004335 return false;
4336
4337 // FIXME: We should put some diagnostic logic right into this function.
4338
Sean Huntcdee3fe2011-05-11 22:34:38 +00004339 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4340 BE = RD->bases_end();
4341 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004342 // We'll handle this one later
4343 if (BI->isVirtual())
4344 continue;
4345
Sean Huntcdee3fe2011-05-11 22:34:38 +00004346 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4347 assert(BaseDecl && "base isn't a CXXRecordDecl");
4348
Sean Hunte16da072011-10-10 06:18:57 +00004349 // Unless we have an assignment operator, the base's destructor must
4350 // be accessible and not deleted.
4351 if (!IsAssignment) {
4352 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4353 if (BaseDtor->isDeleted())
4354 return true;
4355 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4356 AR_accessible)
4357 return true;
4358 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004359
Sean Hunte16da072011-10-10 06:18:57 +00004360 // Finding the corresponding member in the base should lead to a
Sean Huntc32d6842011-10-11 04:55:36 +00004361 // unique, accessible, non-deleted function. If we are doing
4362 // a destructor, we have already checked this case.
Sean Hunte16da072011-10-10 06:18:57 +00004363 if (CSM != CXXDestructor) {
4364 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004365 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004366 false);
4367 if (!SMOR->hasSuccess())
4368 return true;
4369 CXXMethodDecl *BaseMember = SMOR->getMethod();
4370 if (IsConstructor) {
4371 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4372 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4373 PDiag()) != AR_accessible)
4374 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004375
4376 // For a move operation, the corresponding operation must actually
4377 // be a move operation (and not a copy selected by overload
4378 // resolution) unless we are working on a trivially copyable class.
4379 if (IsMove && !BaseCtor->isMoveConstructor() &&
4380 !BaseDecl->isTriviallyCopyable())
4381 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004382 }
4383 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004384 }
4385
4386 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4387 BE = RD->vbases_end();
4388 BI != BE; ++BI) {
4389 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4390 assert(BaseDecl && "base isn't a CXXRecordDecl");
4391
Sean Hunte16da072011-10-10 06:18:57 +00004392 // Unless we have an assignment operator, the base's destructor must
4393 // be accessible and not deleted.
4394 if (!IsAssignment) {
4395 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4396 if (BaseDtor->isDeleted())
4397 return true;
4398 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4399 AR_accessible)
4400 return true;
4401 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004402
Sean Hunte16da072011-10-10 06:18:57 +00004403 // Finding the corresponding member in the base should lead to a
4404 // unique, accessible, non-deleted function.
4405 if (CSM != CXXDestructor) {
4406 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004407 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004408 false);
4409 if (!SMOR->hasSuccess())
4410 return true;
4411 CXXMethodDecl *BaseMember = SMOR->getMethod();
4412 if (IsConstructor) {
4413 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4414 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4415 PDiag()) != AR_accessible)
4416 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004417
4418 // For a move operation, the corresponding operation must actually
4419 // be a move operation (and not a copy selected by overload
4420 // resolution) unless we are working on a trivially copyable class.
4421 if (IsMove && !BaseCtor->isMoveConstructor() &&
4422 !BaseDecl->isTriviallyCopyable())
4423 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004424 }
4425 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004426 }
4427
4428 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4429 FE = RD->field_end();
4430 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004431 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004432 continue;
4433
Sean Huntcdee3fe2011-05-11 22:34:38 +00004434 QualType FieldType = Context.getBaseElementType(FI->getType());
4435 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00004436
Sean Hunte16da072011-10-10 06:18:57 +00004437 // For a default constructor, all references must be initialized in-class
4438 // and, if a union, it must have a non-const member.
4439 if (CSM == CXXDefaultConstructor) {
4440 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4441 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004442
Sean Hunte16da072011-10-10 06:18:57 +00004443 if (IsUnion && !FieldType.isConstQualified())
4444 AllConst = false;
Sean Huntc32d6842011-10-11 04:55:36 +00004445 // For a copy constructor, data members must not be of rvalue reference
4446 // type.
4447 } else if (CSM == CXXCopyConstructor) {
4448 if (FieldType->isRValueReferenceType())
4449 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004450 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004451
4452 if (FieldRecord) {
Sean Hunte16da072011-10-10 06:18:57 +00004453 // For a default constructor, a const member must have a user-provided
4454 // default constructor or else be explicitly initialized.
4455 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00004456 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004457 !FieldRecord->hasUserProvidedDefaultConstructor())
4458 return true;
4459
Sean Huntc32d6842011-10-11 04:55:36 +00004460 // Some additional restrictions exist on the variant members.
4461 if (!IsUnion && FieldRecord->isUnion() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004462 FieldRecord->isAnonymousStructOrUnion()) {
4463 // We're okay to reuse AllConst here since we only care about the
4464 // value otherwise if we're in a union.
4465 AllConst = true;
4466
4467 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4468 UE = FieldRecord->field_end();
4469 UI != UE; ++UI) {
4470 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4471 CXXRecordDecl *UnionFieldRecord =
4472 UnionFieldType->getAsCXXRecordDecl();
4473
4474 if (!UnionFieldType.isConstQualified())
4475 AllConst = false;
4476
Sean Huntc32d6842011-10-11 04:55:36 +00004477 if (UnionFieldRecord) {
4478 // FIXME: Checking for accessibility and validity of this
4479 // destructor is technically going beyond the
4480 // standard, but this is believed to be a defect.
4481 if (!IsAssignment) {
4482 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4483 if (FieldDtor->isDeleted())
4484 return true;
4485 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4486 AR_accessible)
4487 return true;
4488 if (!FieldDtor->isTrivial())
4489 return true;
4490 }
4491
4492 if (CSM != CXXDestructor) {
4493 SpecialMemberOverloadResult *SMOR =
4494 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Sean Hunt769bb2d2011-10-11 06:43:29 +00004495 false, false, false);
Sean Huntc32d6842011-10-11 04:55:36 +00004496 // FIXME: Checking for accessibility and validity of this
4497 // corresponding member is technically going beyond the
4498 // standard, but this is believed to be a defect.
4499 if (!SMOR->hasSuccess())
4500 return true;
4501
4502 CXXMethodDecl *FieldMember = SMOR->getMethod();
4503 // A member of a union must have a trivial corresponding
4504 // constructor.
4505 if (!FieldMember->isTrivial())
4506 return true;
4507
4508 if (IsConstructor) {
4509 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4510 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4511 PDiag()) != AR_accessible)
4512 return true;
4513 }
4514 }
4515 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004516 }
Sean Hunt2be7e902011-05-12 22:46:29 +00004517
Sean Huntc32d6842011-10-11 04:55:36 +00004518 // At least one member in each anonymous union must be non-const
4519 if (CSM == CXXDefaultConstructor && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004520 return true;
4521
4522 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00004523 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00004524 continue;
4525 }
Sean Huntb320e0c2011-06-10 03:50:41 +00004526
Sean Huntc32d6842011-10-11 04:55:36 +00004527 // Unless we're doing assignment, the field's destructor must be
4528 // accessible and not deleted.
4529 if (!IsAssignment) {
4530 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4531 if (FieldDtor->isDeleted())
4532 return true;
4533 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4534 AR_accessible)
4535 return true;
4536 }
4537
Sean Hunte16da072011-10-10 06:18:57 +00004538 // Check that the corresponding member of the field is accessible,
4539 // unique, and non-deleted. We don't do this if it has an explicit
4540 // initialization when default-constructing.
4541 if (CSM != CXXDestructor &&
4542 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4543 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004544 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004545 false);
4546 if (!SMOR->hasSuccess())
Richard Smith7a614d82011-06-11 17:19:42 +00004547 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004548
4549 CXXMethodDecl *FieldMember = SMOR->getMethod();
4550 if (IsConstructor) {
4551 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4552 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4553 PDiag()) != AR_accessible)
4554 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004555
4556 // For a move operation, the corresponding operation must actually
4557 // be a move operation (and not a copy selected by overload
4558 // resolution) unless we are working on a trivially copyable class.
4559 if (IsMove && !FieldCtor->isMoveConstructor() &&
4560 !FieldRecord->isTriviallyCopyable())
4561 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004562 }
4563
4564 // We need the corresponding member of a union to be trivial so that
4565 // we can safely copy them all simultaneously.
4566 // FIXME: Note that performing the check here (where we rely on the lack
4567 // of an in-class initializer) is technically ill-formed. However, this
4568 // seems most obviously to be a bug in the standard.
4569 if (IsUnion && !FieldMember->isTrivial())
Richard Smith7a614d82011-06-11 17:19:42 +00004570 return true;
4571 }
Sean Hunte16da072011-10-10 06:18:57 +00004572 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4573 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4574 // We can't initialize a const member of non-class type to any value.
Sean Hunte3406822011-05-20 21:43:47 +00004575 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004576 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004577 }
4578
Sean Hunte16da072011-10-10 06:18:57 +00004579 // We can't have all const members in a union when default-constructing,
4580 // or else they're all nonsensical garbage values that can't be changed.
4581 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004582 return true;
4583
4584 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004585}
4586
Sean Hunt7f410192011-05-14 05:23:24 +00004587bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4588 CXXRecordDecl *RD = MD->getParent();
4589 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004590 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004591 return false;
4592
Sean Hunt71a682f2011-05-18 03:41:58 +00004593 SourceLocation Loc = MD->getLocation();
4594
Sean Hunt7f410192011-05-14 05:23:24 +00004595 // Do access control from the constructor
4596 ContextRAII MethodContext(*this, MD);
4597
4598 bool Union = RD->isUnion();
4599
Sean Hunt661c67a2011-06-21 23:42:56 +00004600 unsigned ArgQuals =
4601 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4602 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004603
4604 // We do this because we should never actually use an anonymous
4605 // union's constructor.
4606 if (Union && RD->isAnonymousStructOrUnion())
4607 return false;
4608
Sean Hunt7f410192011-05-14 05:23:24 +00004609 // FIXME: We should put some diagnostic logic right into this function.
4610
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004611 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004612 // A defaulted [copy] assignment operator for class X is defined as deleted
4613 // if X has:
4614
4615 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4616 BE = RD->bases_end();
4617 BI != BE; ++BI) {
4618 // We'll handle this one later
4619 if (BI->isVirtual())
4620 continue;
4621
4622 QualType BaseType = BI->getType();
4623 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4624 assert(BaseDecl && "base isn't a CXXRecordDecl");
4625
4626 // -- a [direct base class] B that cannot be [copied] because overload
4627 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004628 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004629 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004630 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4631 0);
4632 if (!CopyOper || CopyOper->isDeleted())
4633 return true;
4634 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004635 return true;
4636 }
4637
4638 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4639 BE = RD->vbases_end();
4640 BI != BE; ++BI) {
4641 QualType BaseType = BI->getType();
4642 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4643 assert(BaseDecl && "base isn't a CXXRecordDecl");
4644
Sean Hunt7f410192011-05-14 05:23:24 +00004645 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004646 // resolution, as applied to B's [copy] assignment operator, results in
4647 // an ambiguity or a function that is deleted or inaccessible from the
4648 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004649 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4650 0);
4651 if (!CopyOper || CopyOper->isDeleted())
4652 return true;
4653 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004654 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004655 }
4656
4657 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4658 FE = RD->field_end();
4659 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004660 if (FI->isUnnamedBitfield())
4661 continue;
4662
Sean Hunt7f410192011-05-14 05:23:24 +00004663 QualType FieldType = Context.getBaseElementType(FI->getType());
4664
4665 // -- a non-static data member of reference type
4666 if (FieldType->isReferenceType())
4667 return true;
4668
4669 // -- a non-static data member of const non-class type (or array thereof)
4670 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4671 return true;
4672
4673 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4674
4675 if (FieldRecord) {
4676 // This is an anonymous union
4677 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4678 // Anonymous unions inside unions do not variant members create
4679 if (!Union) {
4680 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4681 UE = FieldRecord->field_end();
4682 UI != UE; ++UI) {
4683 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4684 CXXRecordDecl *UnionFieldRecord =
4685 UnionFieldType->getAsCXXRecordDecl();
4686
4687 // -- a variant member with a non-trivial [copy] assignment operator
4688 // and X is a union-like class
4689 if (UnionFieldRecord &&
4690 !UnionFieldRecord->hasTrivialCopyAssignment())
4691 return true;
4692 }
4693 }
4694
4695 // Don't try to initalize an anonymous union
4696 continue;
4697 // -- a variant member with a non-trivial [copy] assignment operator
4698 // and X is a union-like class
4699 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4700 return true;
4701 }
Sean Hunt7f410192011-05-14 05:23:24 +00004702
Sean Hunt661c67a2011-06-21 23:42:56 +00004703 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4704 false, 0);
4705 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004706 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004707 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004708 return true;
4709 }
4710 }
4711
4712 return false;
4713}
4714
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004715bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4716 CXXRecordDecl *RD = MD->getParent();
4717 assert(!RD->isDependentType() && "do deletion after instantiation");
4718 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4719 return false;
4720
4721 SourceLocation Loc = MD->getLocation();
4722
4723 // Do access control from the constructor
4724 ContextRAII MethodContext(*this, MD);
4725
4726 bool Union = RD->isUnion();
4727
4728 // We do this because we should never actually use an anonymous
4729 // union's constructor.
4730 if (Union && RD->isAnonymousStructOrUnion())
4731 return false;
4732
4733 // C++0x [class.copy]/20
4734 // A defaulted [move] assignment operator for class X is defined as deleted
4735 // if X has:
4736
4737 // -- for the move constructor, [...] any direct or indirect virtual base
4738 // class.
4739 if (RD->getNumVBases() != 0)
4740 return true;
4741
4742 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4743 BE = RD->bases_end();
4744 BI != BE; ++BI) {
4745
4746 QualType BaseType = BI->getType();
4747 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4748 assert(BaseDecl && "base isn't a CXXRecordDecl");
4749
4750 // -- a [direct base class] B that cannot be [moved] because overload
4751 // resolution, as applied to B's [move] assignment operator, results in
4752 // an ambiguity or a function that is deleted or inaccessible from the
4753 // assignment operator
4754 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4755 if (!MoveOper || MoveOper->isDeleted())
4756 return true;
4757 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4758 return true;
4759
4760 // -- for the move assignment operator, a [direct base class] with a type
4761 // that does not have a move assignment operator and is not trivially
4762 // copyable.
4763 if (!MoveOper->isMoveAssignmentOperator() &&
4764 !BaseDecl->isTriviallyCopyable())
4765 return true;
4766 }
4767
4768 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4769 FE = RD->field_end();
4770 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004771 if (FI->isUnnamedBitfield())
4772 continue;
4773
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004774 QualType FieldType = Context.getBaseElementType(FI->getType());
4775
4776 // -- a non-static data member of reference type
4777 if (FieldType->isReferenceType())
4778 return true;
4779
4780 // -- a non-static data member of const non-class type (or array thereof)
4781 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4782 return true;
4783
4784 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4785
4786 if (FieldRecord) {
4787 // This is an anonymous union
4788 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4789 // Anonymous unions inside unions do not variant members create
4790 if (!Union) {
4791 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4792 UE = FieldRecord->field_end();
4793 UI != UE; ++UI) {
4794 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4795 CXXRecordDecl *UnionFieldRecord =
4796 UnionFieldType->getAsCXXRecordDecl();
4797
4798 // -- a variant member with a non-trivial [move] assignment operator
4799 // and X is a union-like class
4800 if (UnionFieldRecord &&
4801 !UnionFieldRecord->hasTrivialMoveAssignment())
4802 return true;
4803 }
4804 }
4805
4806 // Don't try to initalize an anonymous union
4807 continue;
4808 // -- a variant member with a non-trivial [move] assignment operator
4809 // and X is a union-like class
4810 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4811 return true;
4812 }
4813
4814 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4815 if (!MoveOper || MoveOper->isDeleted())
4816 return true;
4817 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4818 return true;
4819
4820 // -- for the move assignment operator, a [non-static data member] with a
4821 // type that does not have a move assignment operator and is not
4822 // trivially copyable.
4823 if (!MoveOper->isMoveAssignmentOperator() &&
4824 !FieldRecord->isTriviallyCopyable())
4825 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004826 }
Sean Hunt7f410192011-05-14 05:23:24 +00004827 }
4828
4829 return false;
4830}
4831
Sean Huntcb45a0f2011-05-12 22:46:25 +00004832bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4833 CXXRecordDecl *RD = DD->getParent();
4834 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004835 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004836 return false;
4837
Sean Hunt71a682f2011-05-18 03:41:58 +00004838 SourceLocation Loc = DD->getLocation();
4839
Sean Huntcb45a0f2011-05-12 22:46:25 +00004840 // Do access control from the destructor
4841 ContextRAII CtorContext(*this, DD);
4842
4843 bool Union = RD->isUnion();
4844
Sean Hunt49634cf2011-05-13 06:10:58 +00004845 // We do this because we should never actually use an anonymous
4846 // union's destructor.
4847 if (Union && RD->isAnonymousStructOrUnion())
4848 return false;
4849
Sean Huntcb45a0f2011-05-12 22:46:25 +00004850 // C++0x [class.dtor]p5
4851 // A defaulted destructor for a class X is defined as deleted if:
4852 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4853 BE = RD->bases_end();
4854 BI != BE; ++BI) {
4855 // We'll handle this one later
4856 if (BI->isVirtual())
4857 continue;
4858
4859 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4860 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4861 assert(BaseDtor && "base has no destructor");
4862
4863 // -- any direct or virtual base class has a deleted destructor or
4864 // a destructor that is inaccessible from the defaulted destructor
4865 if (BaseDtor->isDeleted())
4866 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004867 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004868 AR_accessible)
4869 return true;
4870 }
4871
4872 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4873 BE = RD->vbases_end();
4874 BI != BE; ++BI) {
4875 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4876 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4877 assert(BaseDtor && "base has no destructor");
4878
4879 // -- any direct or virtual base class has a deleted destructor or
4880 // a destructor that is inaccessible from the defaulted destructor
4881 if (BaseDtor->isDeleted())
4882 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004883 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004884 AR_accessible)
4885 return true;
4886 }
4887
4888 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4889 FE = RD->field_end();
4890 FI != FE; ++FI) {
4891 QualType FieldType = Context.getBaseElementType(FI->getType());
4892 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4893 if (FieldRecord) {
4894 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4895 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4896 UE = FieldRecord->field_end();
4897 UI != UE; ++UI) {
4898 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4899 CXXRecordDecl *UnionFieldRecord =
4900 UnionFieldType->getAsCXXRecordDecl();
4901
4902 // -- X is a union-like class that has a variant member with a non-
4903 // trivial destructor.
4904 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4905 return true;
4906 }
4907 // Technically we are supposed to do this next check unconditionally.
4908 // But that makes absolutely no sense.
4909 } else {
4910 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4911
4912 // -- any of the non-static data members has class type M (or array
4913 // thereof) and M has a deleted destructor or a destructor that is
4914 // inaccessible from the defaulted destructor
4915 if (FieldDtor->isDeleted())
4916 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004917 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004918 AR_accessible)
4919 return true;
4920
4921 // -- X is a union-like class that has a variant member with a non-
4922 // trivial destructor.
4923 if (Union && !FieldDtor->isTrivial())
4924 return true;
4925 }
4926 }
4927 }
4928
4929 if (DD->isVirtual()) {
4930 FunctionDecl *OperatorDelete = 0;
4931 DeclarationName Name =
4932 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004933 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004934 false))
4935 return true;
4936 }
4937
4938
4939 return false;
4940}
4941
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004942/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004943namespace {
4944 struct FindHiddenVirtualMethodData {
4945 Sema *S;
4946 CXXMethodDecl *Method;
4947 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004948 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004949 };
4950}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004951
4952/// \brief Member lookup function that determines whether a given C++
4953/// method overloads virtual methods in a base class without overriding any,
4954/// to be used with CXXRecordDecl::lookupInBases().
4955static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4956 CXXBasePath &Path,
4957 void *UserData) {
4958 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4959
4960 FindHiddenVirtualMethodData &Data
4961 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4962
4963 DeclarationName Name = Data.Method->getDeclName();
4964 assert(Name.getNameKind() == DeclarationName::Identifier);
4965
4966 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004967 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004968 for (Path.Decls = BaseRecord->lookup(Name);
4969 Path.Decls.first != Path.Decls.second;
4970 ++Path.Decls.first) {
4971 NamedDecl *D = *Path.Decls.first;
4972 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004973 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004974 foundSameNameMethod = true;
4975 // Interested only in hidden virtual methods.
4976 if (!MD->isVirtual())
4977 continue;
4978 // If the method we are checking overrides a method from its base
4979 // don't warn about the other overloaded methods.
4980 if (!Data.S->IsOverload(Data.Method, MD, false))
4981 return true;
4982 // Collect the overload only if its hidden.
4983 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4984 overloadedMethods.push_back(MD);
4985 }
4986 }
4987
4988 if (foundSameNameMethod)
4989 Data.OverloadedMethods.append(overloadedMethods.begin(),
4990 overloadedMethods.end());
4991 return foundSameNameMethod;
4992}
4993
4994/// \brief See if a method overloads virtual methods in a base class without
4995/// overriding any.
4996void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4997 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004998 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004999 return;
5000 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
5001 return;
5002
5003 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5004 /*bool RecordPaths=*/false,
5005 /*bool DetectVirtual=*/false);
5006 FindHiddenVirtualMethodData Data;
5007 Data.Method = MD;
5008 Data.S = this;
5009
5010 // Keep the base methods that were overriden or introduced in the subclass
5011 // by 'using' in a set. A base method not in this set is hidden.
5012 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5013 res.first != res.second; ++res.first) {
5014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
5015 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5016 E = MD->end_overridden_methods();
5017 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005018 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005019 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5020 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005021 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005022 }
5023
5024 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5025 !Data.OverloadedMethods.empty()) {
5026 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5027 << MD << (Data.OverloadedMethods.size() > 1);
5028
5029 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5030 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5031 Diag(overloadedMD->getLocation(),
5032 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5033 }
5034 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005035}
5036
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005037void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005038 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005039 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005040 SourceLocation RBrac,
5041 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005042 if (!TagDecl)
5043 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005044
Douglas Gregor42af25f2009-05-11 19:58:34 +00005045 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005046
David Blaikie77b6de02011-09-22 02:58:26 +00005047 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005048 // strict aliasing violation!
5049 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005050 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005051
Douglas Gregor23c94db2010-07-02 17:43:08 +00005052 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005053 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005054}
5055
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005056/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5057/// special functions, such as the default constructor, copy
5058/// constructor, or destructor, to the given C++ class (C++
5059/// [special]p1). This routine can only be executed just before the
5060/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005061void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005062 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005063 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005064
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005065 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00005066 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005067
Richard Smithb701d3d2011-12-24 21:56:24 +00005068 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5069 ++ASTContext::NumImplicitMoveConstructors;
5070
Douglas Gregora376d102010-07-02 21:50:04 +00005071 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5072 ++ASTContext::NumImplicitCopyAssignmentOperators;
5073
5074 // If we have a dynamic class, then the copy assignment operator may be
5075 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5076 // it shows up in the right place in the vtable and that we diagnose
5077 // problems with the implicit exception specification.
5078 if (ClassDecl->isDynamicClass())
5079 DeclareImplicitCopyAssignment(ClassDecl);
5080 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005081
Richard Smithb701d3d2011-12-24 21:56:24 +00005082 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5083 ++ASTContext::NumImplicitMoveAssignmentOperators;
5084
5085 // Likewise for the move assignment operator.
5086 if (ClassDecl->isDynamicClass())
5087 DeclareImplicitMoveAssignment(ClassDecl);
5088 }
5089
Douglas Gregor4923aa22010-07-02 20:37:36 +00005090 if (!ClassDecl->hasUserDeclaredDestructor()) {
5091 ++ASTContext::NumImplicitDestructors;
5092
5093 // If we have a dynamic class, then the destructor may be virtual, so we
5094 // have to declare the destructor immediately. This ensures that, e.g., it
5095 // shows up in the right place in the vtable and that we diagnose problems
5096 // with the implicit exception specification.
5097 if (ClassDecl->isDynamicClass())
5098 DeclareImplicitDestructor(ClassDecl);
5099 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005100}
5101
Francois Pichet8387e2a2011-04-22 22:18:13 +00005102void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5103 if (!D)
5104 return;
5105
5106 int NumParamList = D->getNumTemplateParameterLists();
5107 for (int i = 0; i < NumParamList; i++) {
5108 TemplateParameterList* Params = D->getTemplateParameterList(i);
5109 for (TemplateParameterList::iterator Param = Params->begin(),
5110 ParamEnd = Params->end();
5111 Param != ParamEnd; ++Param) {
5112 NamedDecl *Named = cast<NamedDecl>(*Param);
5113 if (Named->getDeclName()) {
5114 S->AddDecl(Named);
5115 IdResolver.AddDecl(Named);
5116 }
5117 }
5118 }
5119}
5120
John McCalld226f652010-08-21 09:40:31 +00005121void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005122 if (!D)
5123 return;
5124
5125 TemplateParameterList *Params = 0;
5126 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5127 Params = Template->getTemplateParameters();
5128 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5129 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5130 Params = PartialSpec->getTemplateParameters();
5131 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005132 return;
5133
Douglas Gregor6569d682009-05-27 23:11:45 +00005134 for (TemplateParameterList::iterator Param = Params->begin(),
5135 ParamEnd = Params->end();
5136 Param != ParamEnd; ++Param) {
5137 NamedDecl *Named = cast<NamedDecl>(*Param);
5138 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005139 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005140 IdResolver.AddDecl(Named);
5141 }
5142 }
5143}
5144
John McCalld226f652010-08-21 09:40:31 +00005145void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005146 if (!RecordD) return;
5147 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005148 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005149 PushDeclContext(S, Record);
5150}
5151
John McCalld226f652010-08-21 09:40:31 +00005152void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005153 if (!RecordD) return;
5154 PopDeclContext();
5155}
5156
Douglas Gregor72b505b2008-12-16 21:30:33 +00005157/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5158/// parsing a top-level (non-nested) C++ class, and we are now
5159/// parsing those parts of the given Method declaration that could
5160/// not be parsed earlier (C++ [class.mem]p2), such as default
5161/// arguments. This action should enter the scope of the given
5162/// Method declaration as if we had just parsed the qualified method
5163/// name. However, it should not bring the parameters into scope;
5164/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005165void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005166}
5167
5168/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5169/// C++ method declaration. We're (re-)introducing the given
5170/// function parameter into scope for use in parsing later parts of
5171/// the method declaration. For example, we could see an
5172/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005173void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005174 if (!ParamD)
5175 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005176
John McCalld226f652010-08-21 09:40:31 +00005177 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005178
5179 // If this parameter has an unparsed default argument, clear it out
5180 // to make way for the parsed default argument.
5181 if (Param->hasUnparsedDefaultArg())
5182 Param->setDefaultArg(0);
5183
John McCalld226f652010-08-21 09:40:31 +00005184 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005185 if (Param->getDeclName())
5186 IdResolver.AddDecl(Param);
5187}
5188
5189/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5190/// processing the delayed method declaration for Method. The method
5191/// declaration is now considered finished. There may be a separate
5192/// ActOnStartOfFunctionDef action later (not necessarily
5193/// immediately!) for this method, if it was also defined inside the
5194/// class body.
John McCalld226f652010-08-21 09:40:31 +00005195void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005196 if (!MethodD)
5197 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005198
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005199 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005200
John McCalld226f652010-08-21 09:40:31 +00005201 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005202
5203 // Now that we have our default arguments, check the constructor
5204 // again. It could produce additional diagnostics or affect whether
5205 // the class has implicitly-declared destructors, among other
5206 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005207 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5208 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005209
5210 // Check the default arguments, which we may have added.
5211 if (!Method->isInvalidDecl())
5212 CheckCXXDefaultArguments(Method);
5213}
5214
Douglas Gregor42a552f2008-11-05 20:51:48 +00005215/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005216/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005217/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005218/// emit diagnostics and set the invalid bit to true. In any case, the type
5219/// will be updated to reflect a well-formed type for the constructor and
5220/// returned.
5221QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005222 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005223 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005224
5225 // C++ [class.ctor]p3:
5226 // A constructor shall not be virtual (10.3) or static (9.4). A
5227 // constructor can be invoked for a const, volatile or const
5228 // volatile object. A constructor shall not be declared const,
5229 // volatile, or const volatile (9.3.2).
5230 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005231 if (!D.isInvalidType())
5232 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5233 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5234 << SourceRange(D.getIdentifierLoc());
5235 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005236 }
John McCalld931b082010-08-26 03:08:43 +00005237 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005238 if (!D.isInvalidType())
5239 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5240 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5241 << SourceRange(D.getIdentifierLoc());
5242 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005243 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005244 }
Mike Stump1eb44332009-09-09 15:08:12 +00005245
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005246 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005247 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005248 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005249 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5250 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005251 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005252 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5253 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005254 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005255 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5256 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005257 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005258 }
Mike Stump1eb44332009-09-09 15:08:12 +00005259
Douglas Gregorc938c162011-01-26 05:01:58 +00005260 // C++0x [class.ctor]p4:
5261 // A constructor shall not be declared with a ref-qualifier.
5262 if (FTI.hasRefQualifier()) {
5263 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5264 << FTI.RefQualifierIsLValueRef
5265 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5266 D.setInvalidType();
5267 }
5268
Douglas Gregor42a552f2008-11-05 20:51:48 +00005269 // Rebuild the function type "R" without any type qualifiers (in
5270 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005271 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005272 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005273 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5274 return R;
5275
5276 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5277 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005278 EPI.RefQualifier = RQ_None;
5279
Chris Lattner65401802009-04-25 08:28:21 +00005280 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005281 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005282}
5283
Douglas Gregor72b505b2008-12-16 21:30:33 +00005284/// CheckConstructor - Checks a fully-formed constructor for
5285/// well-formedness, issuing any diagnostics required. Returns true if
5286/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005287void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005288 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005289 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5290 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005291 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005292
5293 // C++ [class.copy]p3:
5294 // A declaration of a constructor for a class X is ill-formed if
5295 // its first parameter is of type (optionally cv-qualified) X and
5296 // either there are no other parameters or else all other
5297 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005298 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005299 ((Constructor->getNumParams() == 1) ||
5300 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005301 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5302 Constructor->getTemplateSpecializationKind()
5303 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005304 QualType ParamType = Constructor->getParamDecl(0)->getType();
5305 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5306 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005307 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005308 const char *ConstRef
5309 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5310 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005311 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005312 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005313
5314 // FIXME: Rather that making the constructor invalid, we should endeavor
5315 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005316 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005317 }
5318 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005319}
5320
John McCall15442822010-08-04 01:04:25 +00005321/// CheckDestructor - Checks a fully-formed destructor definition for
5322/// well-formedness, issuing any diagnostics required. Returns true
5323/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005324bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005325 CXXRecordDecl *RD = Destructor->getParent();
5326
5327 if (Destructor->isVirtual()) {
5328 SourceLocation Loc;
5329
5330 if (!Destructor->isImplicit())
5331 Loc = Destructor->getLocation();
5332 else
5333 Loc = RD->getLocation();
5334
5335 // If we have a virtual destructor, look up the deallocation function
5336 FunctionDecl *OperatorDelete = 0;
5337 DeclarationName Name =
5338 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005339 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005340 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005341
Eli Friedman5f2987c2012-02-02 03:46:19 +00005342 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005343
5344 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005345 }
Anders Carlsson37909802009-11-30 21:24:50 +00005346
5347 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005348}
5349
Mike Stump1eb44332009-09-09 15:08:12 +00005350static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005351FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5352 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5353 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005354 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005355}
5356
Douglas Gregor42a552f2008-11-05 20:51:48 +00005357/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5358/// the well-formednes of the destructor declarator @p D with type @p
5359/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005360/// emit diagnostics and set the declarator to invalid. Even if this happens,
5361/// will be updated to reflect a well-formed type for the destructor and
5362/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005363QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005364 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005365 // C++ [class.dtor]p1:
5366 // [...] A typedef-name that names a class is a class-name
5367 // (7.1.3); however, a typedef-name that names a class shall not
5368 // be used as the identifier in the declarator for a destructor
5369 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005370 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005371 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005372 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005373 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005374 else if (const TemplateSpecializationType *TST =
5375 DeclaratorType->getAs<TemplateSpecializationType>())
5376 if (TST->isTypeAlias())
5377 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5378 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005379
5380 // C++ [class.dtor]p2:
5381 // A destructor is used to destroy objects of its class type. A
5382 // destructor takes no parameters, and no return type can be
5383 // specified for it (not even void). The address of a destructor
5384 // shall not be taken. A destructor shall not be static. A
5385 // destructor can be invoked for a const, volatile or const
5386 // volatile object. A destructor shall not be declared const,
5387 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005388 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005389 if (!D.isInvalidType())
5390 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5391 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005392 << SourceRange(D.getIdentifierLoc())
5393 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5394
John McCalld931b082010-08-26 03:08:43 +00005395 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005396 }
Chris Lattner65401802009-04-25 08:28:21 +00005397 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005398 // Destructors don't have return types, but the parser will
5399 // happily parse something like:
5400 //
5401 // class X {
5402 // float ~X();
5403 // };
5404 //
5405 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005406 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5407 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5408 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005409 }
Mike Stump1eb44332009-09-09 15:08:12 +00005410
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005411 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005412 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005413 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005414 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5415 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005416 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005417 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5418 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005419 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005420 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5421 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005422 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005423 }
5424
Douglas Gregorc938c162011-01-26 05:01:58 +00005425 // C++0x [class.dtor]p2:
5426 // A destructor shall not be declared with a ref-qualifier.
5427 if (FTI.hasRefQualifier()) {
5428 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5429 << FTI.RefQualifierIsLValueRef
5430 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5431 D.setInvalidType();
5432 }
5433
Douglas Gregor42a552f2008-11-05 20:51:48 +00005434 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005435 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005436 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5437
5438 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005439 FTI.freeArgs();
5440 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005441 }
5442
Mike Stump1eb44332009-09-09 15:08:12 +00005443 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005444 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005445 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005446 D.setInvalidType();
5447 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005448
5449 // Rebuild the function type "R" without any type qualifiers or
5450 // parameters (in case any of the errors above fired) and with
5451 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005452 // types.
John McCalle23cf432010-12-14 08:05:40 +00005453 if (!D.isInvalidType())
5454 return R;
5455
Douglas Gregord92ec472010-07-01 05:10:53 +00005456 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005457 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5458 EPI.Variadic = false;
5459 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005460 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005461 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005462}
5463
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005464/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5465/// well-formednes of the conversion function declarator @p D with
5466/// type @p R. If there are any errors in the declarator, this routine
5467/// will emit diagnostics and return true. Otherwise, it will return
5468/// false. Either way, the type @p R will be updated to reflect a
5469/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005470void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005471 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005472 // C++ [class.conv.fct]p1:
5473 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005474 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005475 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005476 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005477 if (!D.isInvalidType())
5478 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5479 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5480 << SourceRange(D.getIdentifierLoc());
5481 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005482 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005483 }
John McCalla3f81372010-04-13 00:04:31 +00005484
5485 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5486
Chris Lattner6e475012009-04-25 08:35:12 +00005487 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005488 // Conversion functions don't have return types, but the parser will
5489 // happily parse something like:
5490 //
5491 // class X {
5492 // float operator bool();
5493 // };
5494 //
5495 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005496 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5497 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5498 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005499 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005500 }
5501
John McCalla3f81372010-04-13 00:04:31 +00005502 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5503
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005504 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005505 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005506 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5507
5508 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005509 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005510 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005511 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005512 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005513 D.setInvalidType();
5514 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005515
John McCalla3f81372010-04-13 00:04:31 +00005516 // Diagnose "&operator bool()" and other such nonsense. This
5517 // is actually a gcc extension which we don't support.
5518 if (Proto->getResultType() != ConvType) {
5519 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5520 << Proto->getResultType();
5521 D.setInvalidType();
5522 ConvType = Proto->getResultType();
5523 }
5524
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005525 // C++ [class.conv.fct]p4:
5526 // The conversion-type-id shall not represent a function type nor
5527 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005528 if (ConvType->isArrayType()) {
5529 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5530 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005531 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005532 } else if (ConvType->isFunctionType()) {
5533 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5534 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005535 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005536 }
5537
5538 // Rebuild the function type "R" without any parameters (in case any
5539 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005540 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005541 if (D.isInvalidType())
5542 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005543
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005544 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005545 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005546 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005547 getLangOptions().CPlusPlus0x ?
5548 diag::warn_cxx98_compat_explicit_conversion_functions :
5549 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005550 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005551}
5552
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005553/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5554/// the declaration of the given C++ conversion function. This routine
5555/// is responsible for recording the conversion function in the C++
5556/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005557Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005558 assert(Conversion && "Expected to receive a conversion function declaration");
5559
Douglas Gregor9d350972008-12-12 08:25:50 +00005560 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005561
5562 // Make sure we aren't redeclaring the conversion function.
5563 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005564
5565 // C++ [class.conv.fct]p1:
5566 // [...] A conversion function is never used to convert a
5567 // (possibly cv-qualified) object to the (possibly cv-qualified)
5568 // same object type (or a reference to it), to a (possibly
5569 // cv-qualified) base class of that type (or a reference to it),
5570 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005571 // FIXME: Suppress this warning if the conversion function ends up being a
5572 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005573 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005574 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005575 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005576 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005577 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5578 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005579 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005580 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005581 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5582 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005583 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005584 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005585 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005586 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005587 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005588 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005589 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005590 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005591 }
5592
Douglas Gregore80622f2010-09-29 04:25:11 +00005593 if (FunctionTemplateDecl *ConversionTemplate
5594 = Conversion->getDescribedFunctionTemplate())
5595 return ConversionTemplate;
5596
John McCalld226f652010-08-21 09:40:31 +00005597 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005598}
5599
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005600//===----------------------------------------------------------------------===//
5601// Namespace Handling
5602//===----------------------------------------------------------------------===//
5603
John McCallea318642010-08-26 09:15:37 +00005604
5605
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005606/// ActOnStartNamespaceDef - This is called at the start of a namespace
5607/// definition.
John McCalld226f652010-08-21 09:40:31 +00005608Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005609 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005610 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005611 SourceLocation IdentLoc,
5612 IdentifierInfo *II,
5613 SourceLocation LBrace,
5614 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005615 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5616 // For anonymous namespace, take the location of the left brace.
5617 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005618 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005619 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005620 bool IsStd = false;
5621 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005622 Scope *DeclRegionScope = NamespcScope->getParent();
5623
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005624 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005625 if (II) {
5626 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005627 // The identifier in an original-namespace-definition shall not
5628 // have been previously defined in the declarative region in
5629 // which the original-namespace-definition appears. The
5630 // identifier in an original-namespace-definition is the name of
5631 // the namespace. Subsequently in that declarative region, it is
5632 // treated as an original-namespace-name.
5633 //
5634 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005635 // look through using directives, just look for any ordinary names.
5636
5637 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005638 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5639 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005640 NamedDecl *PrevDecl = 0;
5641 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005642 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005643 R.first != R.second; ++R.first) {
5644 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5645 PrevDecl = *R.first;
5646 break;
5647 }
5648 }
5649
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005650 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5651
5652 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005653 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005654 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005655 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005656 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005657 // The user probably just forgot the 'inline', so suggest that it
5658 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005659 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005660 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5661 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005662 Diag(Loc, diag::err_inline_namespace_mismatch)
5663 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005664 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005665 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5666
5667 IsInline = PrevNS->isInline();
5668 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005669 } else if (PrevDecl) {
5670 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005671 Diag(Loc, diag::err_redefinition_different_kind)
5672 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005673 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005674 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005675 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005676 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005677 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005678 // This is the first "real" definition of the namespace "std", so update
5679 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005680 PrevNS = getStdNamespace();
5681 IsStd = true;
5682 AddToKnown = !IsInline;
5683 } else {
5684 // We've seen this namespace for the first time.
5685 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005686 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005687 } else {
John McCall9aeed322009-10-01 00:25:31 +00005688 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005689
5690 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005691 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005692 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005693 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005694 } else {
5695 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005696 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005697 }
5698
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005699 if (PrevNS && IsInline != PrevNS->isInline()) {
5700 // inline-ness must match
5701 Diag(Loc, diag::err_inline_namespace_mismatch)
5702 << IsInline;
5703 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005704
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005705 // Recover by ignoring the new namespace's inline status.
5706 IsInline = PrevNS->isInline();
5707 }
5708 }
5709
5710 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5711 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005712 if (IsInvalid)
5713 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005714
5715 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005716
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005717 // FIXME: Should we be merging attributes?
5718 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005719 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005720
5721 if (IsStd)
5722 StdNamespace = Namespc;
5723 if (AddToKnown)
5724 KnownNamespaces[Namespc] = false;
5725
5726 if (II) {
5727 PushOnScopeChains(Namespc, DeclRegionScope);
5728 } else {
5729 // Link the anonymous namespace into its parent.
5730 DeclContext *Parent = CurContext->getRedeclContext();
5731 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5732 TU->setAnonymousNamespace(Namespc);
5733 } else {
5734 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005735 }
John McCall9aeed322009-10-01 00:25:31 +00005736
Douglas Gregora4181472010-03-24 00:46:35 +00005737 CurContext->addDecl(Namespc);
5738
John McCall9aeed322009-10-01 00:25:31 +00005739 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5740 // behaves as if it were replaced by
5741 // namespace unique { /* empty body */ }
5742 // using namespace unique;
5743 // namespace unique { namespace-body }
5744 // where all occurrences of 'unique' in a translation unit are
5745 // replaced by the same identifier and this identifier differs
5746 // from all other identifiers in the entire program.
5747
5748 // We just create the namespace with an empty name and then add an
5749 // implicit using declaration, just like the standard suggests.
5750 //
5751 // CodeGen enforces the "universally unique" aspect by giving all
5752 // declarations semantically contained within an anonymous
5753 // namespace internal linkage.
5754
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005755 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005756 UsingDirectiveDecl* UD
5757 = UsingDirectiveDecl::Create(Context, CurContext,
5758 /* 'using' */ LBrace,
5759 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005760 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005761 /* identifier */ SourceLocation(),
5762 Namespc,
5763 /* Ancestor */ CurContext);
5764 UD->setImplicit();
5765 CurContext->addDecl(UD);
5766 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005767 }
5768
5769 // Although we could have an invalid decl (i.e. the namespace name is a
5770 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005771 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5772 // for the namespace has the declarations that showed up in that particular
5773 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005774 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005775 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005776}
5777
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005778/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5779/// is a namespace alias, returns the namespace it points to.
5780static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5781 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5782 return AD->getNamespace();
5783 return dyn_cast_or_null<NamespaceDecl>(D);
5784}
5785
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005786/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5787/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005788void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005789 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5790 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005791 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005792 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005793 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005794 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005795}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005796
John McCall384aff82010-08-25 07:42:41 +00005797CXXRecordDecl *Sema::getStdBadAlloc() const {
5798 return cast_or_null<CXXRecordDecl>(
5799 StdBadAlloc.get(Context.getExternalSource()));
5800}
5801
5802NamespaceDecl *Sema::getStdNamespace() const {
5803 return cast_or_null<NamespaceDecl>(
5804 StdNamespace.get(Context.getExternalSource()));
5805}
5806
Douglas Gregor66992202010-06-29 17:53:46 +00005807/// \brief Retrieve the special "std" namespace, which may require us to
5808/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005809NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005810 if (!StdNamespace) {
5811 // The "std" namespace has not yet been defined, so build one implicitly.
5812 StdNamespace = NamespaceDecl::Create(Context,
5813 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005814 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005815 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005816 &PP.getIdentifierTable().get("std"),
5817 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005818 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005819 }
5820
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005821 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005822}
5823
Sebastian Redl395e04d2012-01-17 22:49:33 +00005824bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5825 assert(getLangOptions().CPlusPlus &&
5826 "Looking for std::initializer_list outside of C++.");
5827
5828 // We're looking for implicit instantiations of
5829 // template <typename E> class std::initializer_list.
5830
5831 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5832 return false;
5833
Sebastian Redl84760e32012-01-17 22:49:58 +00005834 ClassTemplateDecl *Template = 0;
5835 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005836
Sebastian Redl84760e32012-01-17 22:49:58 +00005837 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005838
Sebastian Redl84760e32012-01-17 22:49:58 +00005839 ClassTemplateSpecializationDecl *Specialization =
5840 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5841 if (!Specialization)
5842 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005843
Sebastian Redl84760e32012-01-17 22:49:58 +00005844 Template = Specialization->getSpecializedTemplate();
5845 Arguments = Specialization->getTemplateArgs().data();
5846 } else if (const TemplateSpecializationType *TST =
5847 Ty->getAs<TemplateSpecializationType>()) {
5848 Template = dyn_cast_or_null<ClassTemplateDecl>(
5849 TST->getTemplateName().getAsTemplateDecl());
5850 Arguments = TST->getArgs();
5851 }
5852 if (!Template)
5853 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005854
5855 if (!StdInitializerList) {
5856 // Haven't recognized std::initializer_list yet, maybe this is it.
5857 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5858 if (TemplateClass->getIdentifier() !=
5859 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005860 !getStdNamespace()->InEnclosingNamespaceSetOf(
5861 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005862 return false;
5863 // This is a template called std::initializer_list, but is it the right
5864 // template?
5865 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005866 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005867 return false;
5868 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5869 return false;
5870
5871 // It's the right template.
5872 StdInitializerList = Template;
5873 }
5874
5875 if (Template != StdInitializerList)
5876 return false;
5877
5878 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005879 if (Element)
5880 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005881 return true;
5882}
5883
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005884static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5885 NamespaceDecl *Std = S.getStdNamespace();
5886 if (!Std) {
5887 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5888 return 0;
5889 }
5890
5891 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5892 Loc, Sema::LookupOrdinaryName);
5893 if (!S.LookupQualifiedName(Result, Std)) {
5894 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5895 return 0;
5896 }
5897 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5898 if (!Template) {
5899 Result.suppressDiagnostics();
5900 // We found something weird. Complain about the first thing we found.
5901 NamedDecl *Found = *Result.begin();
5902 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5903 return 0;
5904 }
5905
5906 // We found some template called std::initializer_list. Now verify that it's
5907 // correct.
5908 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005909 if (Params->getMinRequiredArguments() != 1 ||
5910 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005911 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5912 return 0;
5913 }
5914
5915 return Template;
5916}
5917
5918QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5919 if (!StdInitializerList) {
5920 StdInitializerList = LookupStdInitializerList(*this, Loc);
5921 if (!StdInitializerList)
5922 return QualType();
5923 }
5924
5925 TemplateArgumentListInfo Args(Loc, Loc);
5926 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5927 Context.getTrivialTypeSourceInfo(Element,
5928 Loc)));
5929 return Context.getCanonicalType(
5930 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5931}
5932
Sebastian Redl98d36062012-01-17 22:50:14 +00005933bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5934 // C++ [dcl.init.list]p2:
5935 // A constructor is an initializer-list constructor if its first parameter
5936 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5937 // std::initializer_list<E> for some type E, and either there are no other
5938 // parameters or else all other parameters have default arguments.
5939 if (Ctor->getNumParams() < 1 ||
5940 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5941 return false;
5942
5943 QualType ArgType = Ctor->getParamDecl(0)->getType();
5944 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5945 ArgType = RT->getPointeeType().getUnqualifiedType();
5946
5947 return isStdInitializerList(ArgType, 0);
5948}
5949
Douglas Gregor9172aa62011-03-26 22:25:30 +00005950/// \brief Determine whether a using statement is in a context where it will be
5951/// apply in all contexts.
5952static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5953 switch (CurContext->getDeclKind()) {
5954 case Decl::TranslationUnit:
5955 return true;
5956 case Decl::LinkageSpec:
5957 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5958 default:
5959 return false;
5960 }
5961}
5962
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005963namespace {
5964
5965// Callback to only accept typo corrections that are namespaces.
5966class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5967 public:
5968 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5969 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5970 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5971 }
5972 return false;
5973 }
5974};
5975
5976}
5977
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005978static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5979 CXXScopeSpec &SS,
5980 SourceLocation IdentLoc,
5981 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005982 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005983 R.clear();
5984 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005985 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005986 Validator)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005987 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5988 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5989 if (DeclContext *DC = S.computeDeclContext(SS, false))
5990 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5991 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5992 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5993 else
5994 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5995 << Ident << CorrectedQuotedStr
5996 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005997
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005998 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5999 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006000
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006001 Ident = Corrected.getCorrectionAsIdentifierInfo();
6002 R.addDecl(Corrected.getCorrectionDecl());
6003 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006004 }
6005 return false;
6006}
6007
John McCalld226f652010-08-21 09:40:31 +00006008Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006009 SourceLocation UsingLoc,
6010 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006011 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006012 SourceLocation IdentLoc,
6013 IdentifierInfo *NamespcName,
6014 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006015 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6016 assert(NamespcName && "Invalid NamespcName.");
6017 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006018
6019 // This can only happen along a recovery path.
6020 while (S->getFlags() & Scope::TemplateParamScope)
6021 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006022 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006023
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006024 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006025 NestedNameSpecifier *Qualifier = 0;
6026 if (SS.isSet())
6027 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6028
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006029 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006030 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6031 LookupParsedName(R, S, &SS);
6032 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006033 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006034
Douglas Gregor66992202010-06-29 17:53:46 +00006035 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006036 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006037 // Allow "using namespace std;" or "using namespace ::std;" even if
6038 // "std" hasn't been defined yet, for GCC compatibility.
6039 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6040 NamespcName->isStr("std")) {
6041 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006042 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006043 R.resolveKind();
6044 }
6045 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006046 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006047 }
6048
John McCallf36e02d2009-10-09 21:13:30 +00006049 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006050 NamedDecl *Named = R.getFoundDecl();
6051 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6052 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006053 // C++ [namespace.udir]p1:
6054 // A using-directive specifies that the names in the nominated
6055 // namespace can be used in the scope in which the
6056 // using-directive appears after the using-directive. During
6057 // unqualified name lookup (3.4.1), the names appear as if they
6058 // were declared in the nearest enclosing namespace which
6059 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006060 // namespace. [Note: in this context, "contains" means "contains
6061 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006062
6063 // Find enclosing context containing both using-directive and
6064 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006065 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006066 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6067 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6068 CommonAncestor = CommonAncestor->getParent();
6069
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006070 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006071 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006072 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006073
Douglas Gregor9172aa62011-03-26 22:25:30 +00006074 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006075 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006076 Diag(IdentLoc, diag::warn_using_directive_in_header);
6077 }
6078
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006079 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006080 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006081 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006082 }
6083
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006084 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006085 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006086}
6087
6088void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6089 // If scope has associated entity, then using directive is at namespace
6090 // or translation unit scope. We add UsingDirectiveDecls, into
6091 // it's lookup structure.
6092 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006093 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006094 else
6095 // Otherwise it is block-sope. using-directives will affect lookup
6096 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00006097 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006098}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006099
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006100
John McCalld226f652010-08-21 09:40:31 +00006101Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006102 AccessSpecifier AS,
6103 bool HasUsingKeyword,
6104 SourceLocation UsingLoc,
6105 CXXScopeSpec &SS,
6106 UnqualifiedId &Name,
6107 AttributeList *AttrList,
6108 bool IsTypeName,
6109 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006110 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006111
Douglas Gregor12c118a2009-11-04 16:30:06 +00006112 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006113 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006114 case UnqualifiedId::IK_Identifier:
6115 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006116 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006117 case UnqualifiedId::IK_ConversionFunctionId:
6118 break;
6119
6120 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006121 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00006122 // C++0x inherited constructors.
Richard Smithebaf0e62011-10-18 20:49:44 +00006123 Diag(Name.getSourceRange().getBegin(),
6124 getLangOptions().CPlusPlus0x ?
6125 diag::warn_cxx98_compat_using_decl_constructor :
6126 diag::err_using_decl_constructor)
6127 << SS.getRange();
6128
John McCall604e7f12009-12-08 07:46:18 +00006129 if (getLangOptions().CPlusPlus0x) break;
6130
John McCalld226f652010-08-21 09:40:31 +00006131 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006132
6133 case UnqualifiedId::IK_DestructorName:
6134 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6135 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006136 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006137
6138 case UnqualifiedId::IK_TemplateId:
6139 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6140 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006141 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006142 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006143
6144 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6145 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006146 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006147 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006148
John McCall60fa3cf2009-12-11 02:10:03 +00006149 // Warn about using declarations.
6150 // TODO: store that the declaration was written without 'using' and
6151 // talk about access decls instead of using decls in the
6152 // diagnostics.
6153 if (!HasUsingKeyword) {
6154 UsingLoc = Name.getSourceRange().getBegin();
6155
6156 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006157 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006158 }
6159
Douglas Gregor56c04582010-12-16 00:46:58 +00006160 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6161 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6162 return 0;
6163
John McCall9488ea12009-11-17 05:59:44 +00006164 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006165 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006166 /* IsInstantiation */ false,
6167 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006168 if (UD)
6169 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006170
John McCalld226f652010-08-21 09:40:31 +00006171 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006172}
6173
Douglas Gregor09acc982010-07-07 23:08:52 +00006174/// \brief Determine whether a using declaration considers the given
6175/// declarations as "equivalent", e.g., if they are redeclarations of
6176/// the same entity or are both typedefs of the same type.
6177static bool
6178IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6179 bool &SuppressRedeclaration) {
6180 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6181 SuppressRedeclaration = false;
6182 return true;
6183 }
6184
Richard Smith162e1c12011-04-15 14:24:37 +00006185 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6186 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006187 SuppressRedeclaration = true;
6188 return Context.hasSameType(TD1->getUnderlyingType(),
6189 TD2->getUnderlyingType());
6190 }
6191
6192 return false;
6193}
6194
6195
John McCall9f54ad42009-12-10 09:41:52 +00006196/// Determines whether to create a using shadow decl for a particular
6197/// decl, given the set of decls existing prior to this using lookup.
6198bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6199 const LookupResult &Previous) {
6200 // Diagnose finding a decl which is not from a base class of the
6201 // current class. We do this now because there are cases where this
6202 // function will silently decide not to build a shadow decl, which
6203 // will pre-empt further diagnostics.
6204 //
6205 // We don't need to do this in C++0x because we do the check once on
6206 // the qualifier.
6207 //
6208 // FIXME: diagnose the following if we care enough:
6209 // struct A { int foo; };
6210 // struct B : A { using A::foo; };
6211 // template <class T> struct C : A {};
6212 // template <class T> struct D : C<T> { using B::foo; } // <---
6213 // This is invalid (during instantiation) in C++03 because B::foo
6214 // resolves to the using decl in B, which is not a base class of D<T>.
6215 // We can't diagnose it immediately because C<T> is an unknown
6216 // specialization. The UsingShadowDecl in D<T> then points directly
6217 // to A::foo, which will look well-formed when we instantiate.
6218 // The right solution is to not collapse the shadow-decl chain.
6219 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6220 DeclContext *OrigDC = Orig->getDeclContext();
6221
6222 // Handle enums and anonymous structs.
6223 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6224 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6225 while (OrigRec->isAnonymousStructOrUnion())
6226 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6227
6228 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6229 if (OrigDC == CurContext) {
6230 Diag(Using->getLocation(),
6231 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006232 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006233 Diag(Orig->getLocation(), diag::note_using_decl_target);
6234 return true;
6235 }
6236
Douglas Gregordc355712011-02-25 00:36:19 +00006237 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006238 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006239 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006240 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006241 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006242 Diag(Orig->getLocation(), diag::note_using_decl_target);
6243 return true;
6244 }
6245 }
6246
6247 if (Previous.empty()) return false;
6248
6249 NamedDecl *Target = Orig;
6250 if (isa<UsingShadowDecl>(Target))
6251 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6252
John McCalld7533ec2009-12-11 02:33:26 +00006253 // If the target happens to be one of the previous declarations, we
6254 // don't have a conflict.
6255 //
6256 // FIXME: but we might be increasing its access, in which case we
6257 // should redeclare it.
6258 NamedDecl *NonTag = 0, *Tag = 0;
6259 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6260 I != E; ++I) {
6261 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006262 bool Result;
6263 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6264 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006265
6266 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6267 }
6268
John McCall9f54ad42009-12-10 09:41:52 +00006269 if (Target->isFunctionOrFunctionTemplate()) {
6270 FunctionDecl *FD;
6271 if (isa<FunctionTemplateDecl>(Target))
6272 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6273 else
6274 FD = cast<FunctionDecl>(Target);
6275
6276 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006277 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006278 case Ovl_Overload:
6279 return false;
6280
6281 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006282 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006283 break;
6284
6285 // We found a decl with the exact signature.
6286 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006287 // If we're in a record, we want to hide the target, so we
6288 // return true (without a diagnostic) to tell the caller not to
6289 // build a shadow decl.
6290 if (CurContext->isRecord())
6291 return true;
6292
6293 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006294 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006295 break;
6296 }
6297
6298 Diag(Target->getLocation(), diag::note_using_decl_target);
6299 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6300 return true;
6301 }
6302
6303 // Target is not a function.
6304
John McCall9f54ad42009-12-10 09:41:52 +00006305 if (isa<TagDecl>(Target)) {
6306 // No conflict between a tag and a non-tag.
6307 if (!Tag) return false;
6308
John McCall41ce66f2009-12-10 19:51:03 +00006309 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006310 Diag(Target->getLocation(), diag::note_using_decl_target);
6311 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6312 return true;
6313 }
6314
6315 // No conflict between a tag and a non-tag.
6316 if (!NonTag) return false;
6317
John McCall41ce66f2009-12-10 19:51:03 +00006318 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006319 Diag(Target->getLocation(), diag::note_using_decl_target);
6320 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6321 return true;
6322}
6323
John McCall9488ea12009-11-17 05:59:44 +00006324/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006325UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006326 UsingDecl *UD,
6327 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006328
6329 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006330 NamedDecl *Target = Orig;
6331 if (isa<UsingShadowDecl>(Target)) {
6332 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6333 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006334 }
6335
6336 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006337 = UsingShadowDecl::Create(Context, CurContext,
6338 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006339 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006340
6341 Shadow->setAccess(UD->getAccess());
6342 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6343 Shadow->setInvalidDecl();
6344
John McCall9488ea12009-11-17 05:59:44 +00006345 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006346 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006347 else
John McCall604e7f12009-12-08 07:46:18 +00006348 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006349
John McCall604e7f12009-12-08 07:46:18 +00006350
John McCall9f54ad42009-12-10 09:41:52 +00006351 return Shadow;
6352}
John McCall604e7f12009-12-08 07:46:18 +00006353
John McCall9f54ad42009-12-10 09:41:52 +00006354/// Hides a using shadow declaration. This is required by the current
6355/// using-decl implementation when a resolvable using declaration in a
6356/// class is followed by a declaration which would hide or override
6357/// one or more of the using decl's targets; for example:
6358///
6359/// struct Base { void foo(int); };
6360/// struct Derived : Base {
6361/// using Base::foo;
6362/// void foo(int);
6363/// };
6364///
6365/// The governing language is C++03 [namespace.udecl]p12:
6366///
6367/// When a using-declaration brings names from a base class into a
6368/// derived class scope, member functions in the derived class
6369/// override and/or hide member functions with the same name and
6370/// parameter types in a base class (rather than conflicting).
6371///
6372/// There are two ways to implement this:
6373/// (1) optimistically create shadow decls when they're not hidden
6374/// by existing declarations, or
6375/// (2) don't create any shadow decls (or at least don't make them
6376/// visible) until we've fully parsed/instantiated the class.
6377/// The problem with (1) is that we might have to retroactively remove
6378/// a shadow decl, which requires several O(n) operations because the
6379/// decl structures are (very reasonably) not designed for removal.
6380/// (2) avoids this but is very fiddly and phase-dependent.
6381void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006382 if (Shadow->getDeclName().getNameKind() ==
6383 DeclarationName::CXXConversionFunctionName)
6384 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6385
John McCall9f54ad42009-12-10 09:41:52 +00006386 // Remove it from the DeclContext...
6387 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006388
John McCall9f54ad42009-12-10 09:41:52 +00006389 // ...and the scope, if applicable...
6390 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006391 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006392 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006393 }
6394
John McCall9f54ad42009-12-10 09:41:52 +00006395 // ...and the using decl.
6396 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6397
6398 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006399 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006400}
6401
John McCall7ba107a2009-11-18 02:36:19 +00006402/// Builds a using declaration.
6403///
6404/// \param IsInstantiation - Whether this call arises from an
6405/// instantiation of an unresolved using declaration. We treat
6406/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006407NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6408 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006409 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006410 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006411 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006412 bool IsInstantiation,
6413 bool IsTypeName,
6414 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006415 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006416 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006417 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006418
Anders Carlsson550b14b2009-08-28 05:49:21 +00006419 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006420
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006421 if (SS.isEmpty()) {
6422 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006423 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006424 }
Mike Stump1eb44332009-09-09 15:08:12 +00006425
John McCall9f54ad42009-12-10 09:41:52 +00006426 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006427 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006428 ForRedeclaration);
6429 Previous.setHideTags(false);
6430 if (S) {
6431 LookupName(Previous, S);
6432
6433 // It is really dumb that we have to do this.
6434 LookupResult::Filter F = Previous.makeFilter();
6435 while (F.hasNext()) {
6436 NamedDecl *D = F.next();
6437 if (!isDeclInScope(D, CurContext, S))
6438 F.erase();
6439 }
6440 F.done();
6441 } else {
6442 assert(IsInstantiation && "no scope in non-instantiation");
6443 assert(CurContext->isRecord() && "scope not record in instantiation");
6444 LookupQualifiedName(Previous, CurContext);
6445 }
6446
John McCall9f54ad42009-12-10 09:41:52 +00006447 // Check for invalid redeclarations.
6448 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6449 return 0;
6450
6451 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006452 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6453 return 0;
6454
John McCallaf8e6ed2009-11-12 03:15:40 +00006455 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006456 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006457 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006458 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006459 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006460 // FIXME: not all declaration name kinds are legal here
6461 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6462 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006463 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006464 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006465 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006466 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6467 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006468 }
John McCalled976492009-12-04 22:46:56 +00006469 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006470 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6471 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006472 }
John McCalled976492009-12-04 22:46:56 +00006473 D->setAccess(AS);
6474 CurContext->addDecl(D);
6475
6476 if (!LookupContext) return D;
6477 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006478
John McCall77bb1aa2010-05-01 00:40:08 +00006479 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006480 UD->setInvalidDecl();
6481 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006482 }
6483
Sebastian Redlf677ea32011-02-05 19:23:19 +00006484 // Constructor inheriting using decls get special treatment.
6485 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006486 if (CheckInheritedConstructorUsingDecl(UD))
6487 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006488 return UD;
6489 }
6490
6491 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006492
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006493 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006494
John McCall604e7f12009-12-08 07:46:18 +00006495 // Unlike most lookups, we don't always want to hide tag
6496 // declarations: tag names are visible through the using declaration
6497 // even if hidden by ordinary names, *except* in a dependent context
6498 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006499 if (!IsInstantiation)
6500 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006501
John McCalla24dc2e2009-11-17 02:14:36 +00006502 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006503
John McCallf36e02d2009-10-09 21:13:30 +00006504 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006505 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006506 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006507 UD->setInvalidDecl();
6508 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006509 }
6510
John McCalled976492009-12-04 22:46:56 +00006511 if (R.isAmbiguous()) {
6512 UD->setInvalidDecl();
6513 return UD;
6514 }
Mike Stump1eb44332009-09-09 15:08:12 +00006515
John McCall7ba107a2009-11-18 02:36:19 +00006516 if (IsTypeName) {
6517 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006518 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006519 Diag(IdentLoc, diag::err_using_typename_non_type);
6520 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6521 Diag((*I)->getUnderlyingDecl()->getLocation(),
6522 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006523 UD->setInvalidDecl();
6524 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006525 }
6526 } else {
6527 // If we asked for a non-typename and we got a type, error out,
6528 // but only if this is an instantiation of an unresolved using
6529 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006530 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006531 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6532 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006533 UD->setInvalidDecl();
6534 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006535 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006536 }
6537
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006538 // C++0x N2914 [namespace.udecl]p6:
6539 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006540 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006541 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6542 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006543 UD->setInvalidDecl();
6544 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006545 }
Mike Stump1eb44332009-09-09 15:08:12 +00006546
John McCall9f54ad42009-12-10 09:41:52 +00006547 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6548 if (!CheckUsingShadowDecl(UD, *I, Previous))
6549 BuildUsingShadowDecl(S, UD, *I);
6550 }
John McCall9488ea12009-11-17 05:59:44 +00006551
6552 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006553}
6554
Sebastian Redlf677ea32011-02-05 19:23:19 +00006555/// Additional checks for a using declaration referring to a constructor name.
6556bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6557 if (UD->isTypeName()) {
6558 // FIXME: Cannot specify typename when specifying constructor
6559 return true;
6560 }
6561
Douglas Gregordc355712011-02-25 00:36:19 +00006562 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006563 assert(SourceType &&
6564 "Using decl naming constructor doesn't have type in scope spec.");
6565 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6566
6567 // Check whether the named type is a direct base class.
6568 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6569 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6570 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6571 BaseIt != BaseE; ++BaseIt) {
6572 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6573 if (CanonicalSourceType == BaseType)
6574 break;
6575 }
6576
6577 if (BaseIt == BaseE) {
6578 // Did not find SourceType in the bases.
6579 Diag(UD->getUsingLocation(),
6580 diag::err_using_decl_constructor_not_in_direct_base)
6581 << UD->getNameInfo().getSourceRange()
6582 << QualType(SourceType, 0) << TargetClass;
6583 return true;
6584 }
6585
6586 BaseIt->setInheritConstructors();
6587
6588 return false;
6589}
6590
John McCall9f54ad42009-12-10 09:41:52 +00006591/// Checks that the given using declaration is not an invalid
6592/// redeclaration. Note that this is checking only for the using decl
6593/// itself, not for any ill-formedness among the UsingShadowDecls.
6594bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6595 bool isTypeName,
6596 const CXXScopeSpec &SS,
6597 SourceLocation NameLoc,
6598 const LookupResult &Prev) {
6599 // C++03 [namespace.udecl]p8:
6600 // C++0x [namespace.udecl]p10:
6601 // A using-declaration is a declaration and can therefore be used
6602 // repeatedly where (and only where) multiple declarations are
6603 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006604 //
John McCall8a726212010-11-29 18:01:58 +00006605 // That's in non-member contexts.
6606 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006607 return false;
6608
6609 NestedNameSpecifier *Qual
6610 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6611
6612 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6613 NamedDecl *D = *I;
6614
6615 bool DTypename;
6616 NestedNameSpecifier *DQual;
6617 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6618 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006619 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006620 } else if (UnresolvedUsingValueDecl *UD
6621 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6622 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006623 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006624 } else if (UnresolvedUsingTypenameDecl *UD
6625 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6626 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006627 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006628 } else continue;
6629
6630 // using decls differ if one says 'typename' and the other doesn't.
6631 // FIXME: non-dependent using decls?
6632 if (isTypeName != DTypename) continue;
6633
6634 // using decls differ if they name different scopes (but note that
6635 // template instantiation can cause this check to trigger when it
6636 // didn't before instantiation).
6637 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6638 Context.getCanonicalNestedNameSpecifier(DQual))
6639 continue;
6640
6641 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006642 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006643 return true;
6644 }
6645
6646 return false;
6647}
6648
John McCall604e7f12009-12-08 07:46:18 +00006649
John McCalled976492009-12-04 22:46:56 +00006650/// Checks that the given nested-name qualifier used in a using decl
6651/// in the current context is appropriately related to the current
6652/// scope. If an error is found, diagnoses it and returns true.
6653bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6654 const CXXScopeSpec &SS,
6655 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006656 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006657
John McCall604e7f12009-12-08 07:46:18 +00006658 if (!CurContext->isRecord()) {
6659 // C++03 [namespace.udecl]p3:
6660 // C++0x [namespace.udecl]p8:
6661 // A using-declaration for a class member shall be a member-declaration.
6662
6663 // If we weren't able to compute a valid scope, it must be a
6664 // dependent class scope.
6665 if (!NamedContext || NamedContext->isRecord()) {
6666 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6667 << SS.getRange();
6668 return true;
6669 }
6670
6671 // Otherwise, everything is known to be fine.
6672 return false;
6673 }
6674
6675 // The current scope is a record.
6676
6677 // If the named context is dependent, we can't decide much.
6678 if (!NamedContext) {
6679 // FIXME: in C++0x, we can diagnose if we can prove that the
6680 // nested-name-specifier does not refer to a base class, which is
6681 // still possible in some cases.
6682
6683 // Otherwise we have to conservatively report that things might be
6684 // okay.
6685 return false;
6686 }
6687
6688 if (!NamedContext->isRecord()) {
6689 // Ideally this would point at the last name in the specifier,
6690 // but we don't have that level of source info.
6691 Diag(SS.getRange().getBegin(),
6692 diag::err_using_decl_nested_name_specifier_is_not_class)
6693 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6694 return true;
6695 }
6696
Douglas Gregor6fb07292010-12-21 07:41:49 +00006697 if (!NamedContext->isDependentContext() &&
6698 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6699 return true;
6700
John McCall604e7f12009-12-08 07:46:18 +00006701 if (getLangOptions().CPlusPlus0x) {
6702 // C++0x [namespace.udecl]p3:
6703 // In a using-declaration used as a member-declaration, the
6704 // nested-name-specifier shall name a base class of the class
6705 // being defined.
6706
6707 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6708 cast<CXXRecordDecl>(NamedContext))) {
6709 if (CurContext == NamedContext) {
6710 Diag(NameLoc,
6711 diag::err_using_decl_nested_name_specifier_is_current_class)
6712 << SS.getRange();
6713 return true;
6714 }
6715
6716 Diag(SS.getRange().getBegin(),
6717 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6718 << (NestedNameSpecifier*) SS.getScopeRep()
6719 << cast<CXXRecordDecl>(CurContext)
6720 << SS.getRange();
6721 return true;
6722 }
6723
6724 return false;
6725 }
6726
6727 // C++03 [namespace.udecl]p4:
6728 // A using-declaration used as a member-declaration shall refer
6729 // to a member of a base class of the class being defined [etc.].
6730
6731 // Salient point: SS doesn't have to name a base class as long as
6732 // lookup only finds members from base classes. Therefore we can
6733 // diagnose here only if we can prove that that can't happen,
6734 // i.e. if the class hierarchies provably don't intersect.
6735
6736 // TODO: it would be nice if "definitely valid" results were cached
6737 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6738 // need to be repeated.
6739
6740 struct UserData {
6741 llvm::DenseSet<const CXXRecordDecl*> Bases;
6742
6743 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6744 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6745 Data->Bases.insert(Base);
6746 return true;
6747 }
6748
6749 bool hasDependentBases(const CXXRecordDecl *Class) {
6750 return !Class->forallBases(collect, this);
6751 }
6752
6753 /// Returns true if the base is dependent or is one of the
6754 /// accumulated base classes.
6755 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6756 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6757 return !Data->Bases.count(Base);
6758 }
6759
6760 bool mightShareBases(const CXXRecordDecl *Class) {
6761 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6762 }
6763 };
6764
6765 UserData Data;
6766
6767 // Returns false if we find a dependent base.
6768 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6769 return false;
6770
6771 // Returns false if the class has a dependent base or if it or one
6772 // of its bases is present in the base set of the current context.
6773 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6774 return false;
6775
6776 Diag(SS.getRange().getBegin(),
6777 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6778 << (NestedNameSpecifier*) SS.getScopeRep()
6779 << cast<CXXRecordDecl>(CurContext)
6780 << SS.getRange();
6781
6782 return true;
John McCalled976492009-12-04 22:46:56 +00006783}
6784
Richard Smith162e1c12011-04-15 14:24:37 +00006785Decl *Sema::ActOnAliasDeclaration(Scope *S,
6786 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006787 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006788 SourceLocation UsingLoc,
6789 UnqualifiedId &Name,
6790 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006791 // Skip up to the relevant declaration scope.
6792 while (S->getFlags() & Scope::TemplateParamScope)
6793 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006794 assert((S->getFlags() & Scope::DeclScope) &&
6795 "got alias-declaration outside of declaration scope");
6796
6797 if (Type.isInvalid())
6798 return 0;
6799
6800 bool Invalid = false;
6801 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6802 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006803 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006804
6805 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6806 return 0;
6807
6808 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006809 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006810 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006811 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6812 TInfo->getTypeLoc().getBeginLoc());
6813 }
Richard Smith162e1c12011-04-15 14:24:37 +00006814
6815 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6816 LookupName(Previous, S);
6817
6818 // Warn about shadowing the name of a template parameter.
6819 if (Previous.isSingleResult() &&
6820 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006821 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006822 Previous.clear();
6823 }
6824
6825 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6826 "name in alias declaration must be an identifier");
6827 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6828 Name.StartLocation,
6829 Name.Identifier, TInfo);
6830
6831 NewTD->setAccess(AS);
6832
6833 if (Invalid)
6834 NewTD->setInvalidDecl();
6835
Richard Smith3e4c6c42011-05-05 21:57:07 +00006836 CheckTypedefForVariablyModifiedType(S, NewTD);
6837 Invalid |= NewTD->isInvalidDecl();
6838
Richard Smith162e1c12011-04-15 14:24:37 +00006839 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006840
6841 NamedDecl *NewND;
6842 if (TemplateParamLists.size()) {
6843 TypeAliasTemplateDecl *OldDecl = 0;
6844 TemplateParameterList *OldTemplateParams = 0;
6845
6846 if (TemplateParamLists.size() != 1) {
6847 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6848 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6849 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6850 }
6851 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6852
6853 // Only consider previous declarations in the same scope.
6854 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6855 /*ExplicitInstantiationOrSpecialization*/false);
6856 if (!Previous.empty()) {
6857 Redeclaration = true;
6858
6859 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6860 if (!OldDecl && !Invalid) {
6861 Diag(UsingLoc, diag::err_redefinition_different_kind)
6862 << Name.Identifier;
6863
6864 NamedDecl *OldD = Previous.getRepresentativeDecl();
6865 if (OldD->getLocation().isValid())
6866 Diag(OldD->getLocation(), diag::note_previous_definition);
6867
6868 Invalid = true;
6869 }
6870
6871 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6872 if (TemplateParameterListsAreEqual(TemplateParams,
6873 OldDecl->getTemplateParameters(),
6874 /*Complain=*/true,
6875 TPL_TemplateMatch))
6876 OldTemplateParams = OldDecl->getTemplateParameters();
6877 else
6878 Invalid = true;
6879
6880 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6881 if (!Invalid &&
6882 !Context.hasSameType(OldTD->getUnderlyingType(),
6883 NewTD->getUnderlyingType())) {
6884 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6885 // but we can't reasonably accept it.
6886 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6887 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6888 if (OldTD->getLocation().isValid())
6889 Diag(OldTD->getLocation(), diag::note_previous_definition);
6890 Invalid = true;
6891 }
6892 }
6893 }
6894
6895 // Merge any previous default template arguments into our parameters,
6896 // and check the parameter list.
6897 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6898 TPC_TypeAliasTemplate))
6899 return 0;
6900
6901 TypeAliasTemplateDecl *NewDecl =
6902 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6903 Name.Identifier, TemplateParams,
6904 NewTD);
6905
6906 NewDecl->setAccess(AS);
6907
6908 if (Invalid)
6909 NewDecl->setInvalidDecl();
6910 else if (OldDecl)
6911 NewDecl->setPreviousDeclaration(OldDecl);
6912
6913 NewND = NewDecl;
6914 } else {
6915 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6916 NewND = NewTD;
6917 }
Richard Smith162e1c12011-04-15 14:24:37 +00006918
6919 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006920 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006921
Richard Smith3e4c6c42011-05-05 21:57:07 +00006922 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006923}
6924
John McCalld226f652010-08-21 09:40:31 +00006925Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006926 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006927 SourceLocation AliasLoc,
6928 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006929 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006930 SourceLocation IdentLoc,
6931 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006932
Anders Carlsson81c85c42009-03-28 23:53:49 +00006933 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006934 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6935 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006936
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006937 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006938 NamedDecl *PrevDecl
6939 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6940 ForRedeclaration);
6941 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6942 PrevDecl = 0;
6943
6944 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006945 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006946 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006947 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006948 // FIXME: At some point, we'll want to create the (redundant)
6949 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006950 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006951 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006952 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006953 }
Mike Stump1eb44332009-09-09 15:08:12 +00006954
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006955 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6956 diag::err_redefinition_different_kind;
6957 Diag(AliasLoc, DiagID) << Alias;
6958 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006959 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006960 }
6961
John McCalla24dc2e2009-11-17 02:14:36 +00006962 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006963 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006964
John McCallf36e02d2009-10-09 21:13:30 +00006965 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006966 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006967 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006968 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006969 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006970 }
Mike Stump1eb44332009-09-09 15:08:12 +00006971
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006972 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006973 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006974 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006975 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006976
John McCall3dbd3d52010-02-16 06:53:13 +00006977 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006978 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006979}
6980
Douglas Gregor39957dc2010-05-01 15:04:51 +00006981namespace {
6982 /// \brief Scoped object used to handle the state changes required in Sema
6983 /// to implicitly define the body of a C++ member function;
6984 class ImplicitlyDefinedFunctionScope {
6985 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006986 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006987
6988 public:
6989 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006990 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006991 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006992 S.PushFunctionScope();
6993 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6994 }
6995
6996 ~ImplicitlyDefinedFunctionScope() {
6997 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006998 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006999 }
7000 };
7001}
7002
Sean Hunt001cad92011-05-10 00:49:42 +00007003Sema::ImplicitExceptionSpecification
7004Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007005 // C++ [except.spec]p14:
7006 // An implicitly declared special member function (Clause 12) shall have an
7007 // exception-specification. [...]
7008 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007009 if (ClassDecl->isInvalidDecl())
7010 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007011
Sebastian Redl60618fa2011-03-12 11:50:43 +00007012 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007013 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7014 BEnd = ClassDecl->bases_end();
7015 B != BEnd; ++B) {
7016 if (B->isVirtual()) // Handled below.
7017 continue;
7018
Douglas Gregor18274032010-07-03 00:47:00 +00007019 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7020 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007021 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7022 // If this is a deleted function, add it anyway. This might be conformant
7023 // with the standard. This might not. I'm not sure. It might not matter.
7024 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007025 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007026 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007027 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007028
7029 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007030 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7031 BEnd = ClassDecl->vbases_end();
7032 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007033 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7034 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007035 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7036 // If this is a deleted function, add it anyway. This might be conformant
7037 // with the standard. This might not. I'm not sure. It might not matter.
7038 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007039 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007040 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007041 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007042
7043 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007044 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7045 FEnd = ClassDecl->field_end();
7046 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007047 if (F->hasInClassInitializer()) {
7048 if (Expr *E = F->getInClassInitializer())
7049 ExceptSpec.CalledExpr(E);
7050 else if (!F->isInvalidDecl())
7051 ExceptSpec.SetDelayed();
7052 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007053 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007054 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7055 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7056 // If this is a deleted function, add it anyway. This might be conformant
7057 // with the standard. This might not. I'm not sure. It might not matter.
7058 // In particular, the problem is that this function never gets called. It
7059 // might just be ill-formed because this function attempts to refer to
7060 // a deleted function here.
7061 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007062 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007063 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007064 }
John McCalle23cf432010-12-14 08:05:40 +00007065
Sean Hunt001cad92011-05-10 00:49:42 +00007066 return ExceptSpec;
7067}
7068
7069CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7070 CXXRecordDecl *ClassDecl) {
7071 // C++ [class.ctor]p5:
7072 // A default constructor for a class X is a constructor of class X
7073 // that can be called without an argument. If there is no
7074 // user-declared constructor for class X, a default constructor is
7075 // implicitly declared. An implicitly-declared default constructor
7076 // is an inline public member of its class.
7077 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7078 "Should not build implicit default constructor!");
7079
7080 ImplicitExceptionSpecification Spec =
7081 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7082 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00007083
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007084 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007085 CanQualType ClassType
7086 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007087 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007088 DeclarationName Name
7089 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007090 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007091 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7092 Context, ClassDecl, ClassLoc, NameInfo,
7093 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7094 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7095 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7096 getLangOptions().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007097 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007098 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007099 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00007100 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00007101
7102 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007103 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7104
Douglas Gregor23c94db2010-07-02 17:43:08 +00007105 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007106 PushOnScopeChains(DefaultCon, S, false);
7107 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007108
Sean Hunte16da072011-10-10 06:18:57 +00007109 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00007110 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00007111
Douglas Gregor32df23e2010-07-01 22:02:46 +00007112 return DefaultCon;
7113}
7114
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007115void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7116 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007117 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007118 !Constructor->doesThisDeclarationHaveABody() &&
7119 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007120 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007121
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007122 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007123 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007124
Douglas Gregor39957dc2010-05-01 15:04:51 +00007125 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007126 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007127 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007128 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007129 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007130 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007131 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007132 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007133 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007134
7135 SourceLocation Loc = Constructor->getLocation();
7136 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7137
7138 Constructor->setUsed();
7139 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007140
7141 if (ASTMutationListener *L = getASTMutationListener()) {
7142 L->CompletedImplicitDefinition(Constructor);
7143 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007144}
7145
Richard Smith7a614d82011-06-11 17:19:42 +00007146/// Get any existing defaulted default constructor for the given class. Do not
7147/// implicitly define one if it does not exist.
7148static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7149 CXXRecordDecl *D) {
7150 ASTContext &Context = Self.Context;
7151 QualType ClassType = Context.getTypeDeclType(D);
7152 DeclarationName ConstructorName
7153 = Context.DeclarationNames.getCXXConstructorName(
7154 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7155
7156 DeclContext::lookup_const_iterator Con, ConEnd;
7157 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7158 Con != ConEnd; ++Con) {
7159 // A function template cannot be defaulted.
7160 if (isa<FunctionTemplateDecl>(*Con))
7161 continue;
7162
7163 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7164 if (Constructor->isDefaultConstructor())
7165 return Constructor->isDefaulted() ? Constructor : 0;
7166 }
7167 return 0;
7168}
7169
7170void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7171 if (!D) return;
7172 AdjustDeclIfTemplate(D);
7173
7174 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7175 CXXConstructorDecl *CtorDecl
7176 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7177
7178 if (!CtorDecl) return;
7179
7180 // Compute the exception specification for the default constructor.
7181 const FunctionProtoType *CtorTy =
7182 CtorDecl->getType()->castAs<FunctionProtoType>();
7183 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7184 ImplicitExceptionSpecification Spec =
7185 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7186 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7187 assert(EPI.ExceptionSpecType != EST_Delayed);
7188
7189 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7190 }
7191
7192 // If the default constructor is explicitly defaulted, checking the exception
7193 // specification is deferred until now.
7194 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7195 !ClassDecl->isDependentType())
7196 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7197}
7198
Sebastian Redlf677ea32011-02-05 19:23:19 +00007199void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7200 // We start with an initial pass over the base classes to collect those that
7201 // inherit constructors from. If there are none, we can forgo all further
7202 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007203 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007204 BasesVector BasesToInheritFrom;
7205 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7206 BaseE = ClassDecl->bases_end();
7207 BaseIt != BaseE; ++BaseIt) {
7208 if (BaseIt->getInheritConstructors()) {
7209 QualType Base = BaseIt->getType();
7210 if (Base->isDependentType()) {
7211 // If we inherit constructors from anything that is dependent, just
7212 // abort processing altogether. We'll get another chance for the
7213 // instantiations.
7214 return;
7215 }
7216 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7217 }
7218 }
7219 if (BasesToInheritFrom.empty())
7220 return;
7221
7222 // Now collect the constructors that we already have in the current class.
7223 // Those take precedence over inherited constructors.
7224 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7225 // unless there is a user-declared constructor with the same signature in
7226 // the class where the using-declaration appears.
7227 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7228 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7229 CtorE = ClassDecl->ctor_end();
7230 CtorIt != CtorE; ++CtorIt) {
7231 ExistingConstructors.insert(
7232 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7233 }
7234
7235 Scope *S = getScopeForContext(ClassDecl);
7236 DeclarationName CreatedCtorName =
7237 Context.DeclarationNames.getCXXConstructorName(
7238 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7239
7240 // Now comes the true work.
7241 // First, we keep a map from constructor types to the base that introduced
7242 // them. Needed for finding conflicting constructors. We also keep the
7243 // actually inserted declarations in there, for pretty diagnostics.
7244 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7245 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7246 ConstructorToSourceMap InheritedConstructors;
7247 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7248 BaseE = BasesToInheritFrom.end();
7249 BaseIt != BaseE; ++BaseIt) {
7250 const RecordType *Base = *BaseIt;
7251 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7252 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7253 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7254 CtorE = BaseDecl->ctor_end();
7255 CtorIt != CtorE; ++CtorIt) {
7256 // Find the using declaration for inheriting this base's constructors.
7257 DeclarationName Name =
7258 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7259 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7260 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7261 SourceLocation UsingLoc = UD ? UD->getLocation() :
7262 ClassDecl->getLocation();
7263
7264 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7265 // from the class X named in the using-declaration consists of actual
7266 // constructors and notional constructors that result from the
7267 // transformation of defaulted parameters as follows:
7268 // - all non-template default constructors of X, and
7269 // - for each non-template constructor of X that has at least one
7270 // parameter with a default argument, the set of constructors that
7271 // results from omitting any ellipsis parameter specification and
7272 // successively omitting parameters with a default argument from the
7273 // end of the parameter-type-list.
7274 CXXConstructorDecl *BaseCtor = *CtorIt;
7275 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7276 const FunctionProtoType *BaseCtorType =
7277 BaseCtor->getType()->getAs<FunctionProtoType>();
7278
7279 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7280 maxParams = BaseCtor->getNumParams();
7281 params <= maxParams; ++params) {
7282 // Skip default constructors. They're never inherited.
7283 if (params == 0)
7284 continue;
7285 // Skip copy and move constructors for the same reason.
7286 if (CanBeCopyOrMove && params == 1)
7287 continue;
7288
7289 // Build up a function type for this particular constructor.
7290 // FIXME: The working paper does not consider that the exception spec
7291 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007292 // source. This code doesn't yet, either. When it does, this code will
7293 // need to be delayed until after exception specifications and in-class
7294 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007295 const Type *NewCtorType;
7296 if (params == maxParams)
7297 NewCtorType = BaseCtorType;
7298 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007299 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007300 for (unsigned i = 0; i < params; ++i) {
7301 Args.push_back(BaseCtorType->getArgType(i));
7302 }
7303 FunctionProtoType::ExtProtoInfo ExtInfo =
7304 BaseCtorType->getExtProtoInfo();
7305 ExtInfo.Variadic = false;
7306 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7307 Args.data(), params, ExtInfo)
7308 .getTypePtr();
7309 }
7310 const Type *CanonicalNewCtorType =
7311 Context.getCanonicalType(NewCtorType);
7312
7313 // Now that we have the type, first check if the class already has a
7314 // constructor with this signature.
7315 if (ExistingConstructors.count(CanonicalNewCtorType))
7316 continue;
7317
7318 // Then we check if we have already declared an inherited constructor
7319 // with this signature.
7320 std::pair<ConstructorToSourceMap::iterator, bool> result =
7321 InheritedConstructors.insert(std::make_pair(
7322 CanonicalNewCtorType,
7323 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7324 if (!result.second) {
7325 // Already in the map. If it came from a different class, that's an
7326 // error. Not if it's from the same.
7327 CanQualType PreviousBase = result.first->second.first;
7328 if (CanonicalBase != PreviousBase) {
7329 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7330 const CXXConstructorDecl *PrevBaseCtor =
7331 PrevCtor->getInheritedConstructor();
7332 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7333
7334 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7335 Diag(BaseCtor->getLocation(),
7336 diag::note_using_decl_constructor_conflict_current_ctor);
7337 Diag(PrevBaseCtor->getLocation(),
7338 diag::note_using_decl_constructor_conflict_previous_ctor);
7339 Diag(PrevCtor->getLocation(),
7340 diag::note_using_decl_constructor_conflict_previous_using);
7341 }
7342 continue;
7343 }
7344
7345 // OK, we're there, now add the constructor.
7346 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007347 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007348 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7349 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007350 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7351 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007352 /*ImplicitlyDeclared=*/true,
7353 // FIXME: Due to a defect in the standard, we treat inherited
7354 // constructors as constexpr even if that makes them ill-formed.
7355 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007356 NewCtor->setAccess(BaseCtor->getAccess());
7357
7358 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007359 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007360 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007361 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7362 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007363 /*IdentifierInfo=*/0,
7364 BaseCtorType->getArgType(i),
7365 /*TInfo=*/0, SC_None,
7366 SC_None, /*DefaultArg=*/0));
7367 }
David Blaikie4278c652011-09-21 18:16:56 +00007368 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007369 NewCtor->setInheritedConstructor(BaseCtor);
7370
7371 PushOnScopeChains(NewCtor, S, false);
7372 ClassDecl->addDecl(NewCtor);
7373 result.first->second.second = NewCtor;
7374 }
7375 }
7376 }
7377}
7378
Sean Huntcb45a0f2011-05-12 22:46:25 +00007379Sema::ImplicitExceptionSpecification
7380Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007381 // C++ [except.spec]p14:
7382 // An implicitly declared special member function (Clause 12) shall have
7383 // an exception-specification.
7384 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007385 if (ClassDecl->isInvalidDecl())
7386 return ExceptSpec;
7387
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007388 // Direct base-class destructors.
7389 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7390 BEnd = ClassDecl->bases_end();
7391 B != BEnd; ++B) {
7392 if (B->isVirtual()) // Handled below.
7393 continue;
7394
7395 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7396 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007397 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007398 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007399
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007400 // Virtual base-class destructors.
7401 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7402 BEnd = ClassDecl->vbases_end();
7403 B != BEnd; ++B) {
7404 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7405 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007406 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007407 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007408
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007409 // Field destructors.
7410 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7411 FEnd = ClassDecl->field_end();
7412 F != FEnd; ++F) {
7413 if (const RecordType *RecordTy
7414 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7415 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007416 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007417 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007418
Sean Huntcb45a0f2011-05-12 22:46:25 +00007419 return ExceptSpec;
7420}
7421
7422CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7423 // C++ [class.dtor]p2:
7424 // If a class has no user-declared destructor, a destructor is
7425 // declared implicitly. An implicitly-declared destructor is an
7426 // inline public member of its class.
7427
7428 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007429 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007430 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7431
Douglas Gregor4923aa22010-07-02 20:37:36 +00007432 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007433 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007434
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007435 CanQualType ClassType
7436 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007437 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007438 DeclarationName Name
7439 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007440 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007441 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007442 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7443 /*isInline=*/true,
7444 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007445 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007446 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007447 Destructor->setImplicit();
7448 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007449
7450 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007451 ++ASTContext::NumImplicitDestructorsDeclared;
7452
7453 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007454 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007455 PushOnScopeChains(Destructor, S, false);
7456 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007457
7458 // This could be uniqued if it ever proves significant.
7459 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007460
7461 if (ShouldDeleteDestructor(Destructor))
7462 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007463
7464 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00007465
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007466 return Destructor;
7467}
7468
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007469void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007470 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007471 assert((Destructor->isDefaulted() &&
7472 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007473 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007474 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007475 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007476
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007477 if (Destructor->isInvalidDecl())
7478 return;
7479
Douglas Gregor39957dc2010-05-01 15:04:51 +00007480 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007481
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007482 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007483 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7484 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007485
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007486 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007487 Diag(CurrentLocation, diag::note_member_synthesized_at)
7488 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7489
7490 Destructor->setInvalidDecl();
7491 return;
7492 }
7493
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007494 SourceLocation Loc = Destructor->getLocation();
7495 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007496 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007497 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007498 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007499
7500 if (ASTMutationListener *L = getASTMutationListener()) {
7501 L->CompletedImplicitDefinition(Destructor);
7502 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007503}
7504
Sebastian Redl0ee33912011-05-19 05:13:44 +00007505void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7506 CXXDestructorDecl *destructor) {
7507 // C++11 [class.dtor]p3:
7508 // A declaration of a destructor that does not have an exception-
7509 // specification is implicitly considered to have the same exception-
7510 // specification as an implicit declaration.
7511 const FunctionProtoType *dtorType = destructor->getType()->
7512 getAs<FunctionProtoType>();
7513 if (dtorType->hasExceptionSpec())
7514 return;
7515
7516 ImplicitExceptionSpecification exceptSpec =
7517 ComputeDefaultedDtorExceptionSpec(classDecl);
7518
Chandler Carruth3f224b22011-09-20 04:55:26 +00007519 // Replace the destructor's type, building off the existing one. Fortunately,
7520 // the only thing of interest in the destructor type is its extended info.
7521 // The return and arguments are fixed.
7522 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007523 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7524 epi.NumExceptions = exceptSpec.size();
7525 epi.Exceptions = exceptSpec.data();
7526 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7527
7528 destructor->setType(ty);
7529
7530 // FIXME: If the destructor has a body that could throw, and the newly created
7531 // spec doesn't allow exceptions, we should emit a warning, because this
7532 // change in behavior can break conforming C++03 programs at runtime.
7533 // However, we don't have a body yet, so it needs to be done somewhere else.
7534}
7535
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007536/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007537/// \c To.
7538///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007539/// This routine is used to copy/move the members of a class with an
7540/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007541/// copied are arrays, this routine builds for loops to copy them.
7542///
7543/// \param S The Sema object used for type-checking.
7544///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007545/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007546///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007547/// \param T The type of the expressions being copied/moved. Both expressions
7548/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007549///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007550/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007551///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007552/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007553///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007554/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007555/// Otherwise, it's a non-static member subobject.
7556///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007557/// \param Copying Whether we're copying or moving.
7558///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007559/// \param Depth Internal parameter recording the depth of the recursion.
7560///
7561/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007562static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007563BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007564 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007565 bool CopyingBaseSubobject, bool Copying,
7566 unsigned Depth = 0) {
7567 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007568 // Each subobject is assigned in the manner appropriate to its type:
7569 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007570 // - if the subobject is of class type, as if by a call to operator= with
7571 // the subobject as the object expression and the corresponding
7572 // subobject of x as a single function argument (as if by explicit
7573 // qualification; that is, ignoring any possible virtual overriding
7574 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007575 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7576 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7577
7578 // Look for operator=.
7579 DeclarationName Name
7580 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7581 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7582 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7583
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007584 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007585 LookupResult::Filter F = OpLookup.makeFilter();
7586 while (F.hasNext()) {
7587 NamedDecl *D = F.next();
7588 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007589 if (Copying ? Method->isCopyAssignmentOperator() :
7590 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007591 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007592
Douglas Gregor06a9f362010-05-01 20:49:11 +00007593 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007594 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007595 F.done();
7596
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007597 // Suppress the protected check (C++ [class.protected]) for each of the
7598 // assignment operators we found. This strange dance is required when
7599 // we're assigning via a base classes's copy-assignment operator. To
7600 // ensure that we're getting the right base class subobject (without
7601 // ambiguities), we need to cast "this" to that subobject type; to
7602 // ensure that we don't go through the virtual call mechanism, we need
7603 // to qualify the operator= name with the base class (see below). However,
7604 // this means that if the base class has a protected copy assignment
7605 // operator, the protected member access check will fail. So, we
7606 // rewrite "protected" access to "public" access in this case, since we
7607 // know by construction that we're calling from a derived class.
7608 if (CopyingBaseSubobject) {
7609 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7610 L != LEnd; ++L) {
7611 if (L.getAccess() == AS_protected)
7612 L.setAccess(AS_public);
7613 }
7614 }
7615
Douglas Gregor06a9f362010-05-01 20:49:11 +00007616 // Create the nested-name-specifier that will be used to qualify the
7617 // reference to operator=; this is required to suppress the virtual
7618 // call mechanism.
7619 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007620 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007621 SS.MakeTrivial(S.Context,
7622 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007623 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007624 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007625
7626 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007627 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007628 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007629 /*TemplateKWLoc=*/SourceLocation(),
7630 /*FirstQualifierInScope=*/0,
7631 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007632 /*TemplateArgs=*/0,
7633 /*SuppressQualifierCheck=*/true);
7634 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007635 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007636
7637 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007638
John McCall60d7b3a2010-08-24 06:29:42 +00007639 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007640 OpEqualRef.takeAs<Expr>(),
7641 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007642 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007643 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007644
7645 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007646 }
John McCallb0207482010-03-16 06:11:48 +00007647
Douglas Gregor06a9f362010-05-01 20:49:11 +00007648 // - if the subobject is of scalar type, the built-in assignment
7649 // operator is used.
7650 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7651 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007652 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007653 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007654 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007655
7656 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007657 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007658
7659 // - if the subobject is an array, each element is assigned, in the
7660 // manner appropriate to the element type;
7661
7662 // Construct a loop over the array bounds, e.g.,
7663 //
7664 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7665 //
7666 // that will copy each of the array elements.
7667 QualType SizeType = S.Context.getSizeType();
7668
7669 // Create the iteration variable.
7670 IdentifierInfo *IterationVarName = 0;
7671 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007672 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007673 llvm::raw_svector_ostream OS(Str);
7674 OS << "__i" << Depth;
7675 IterationVarName = &S.Context.Idents.get(OS.str());
7676 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007677 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007678 IterationVarName, SizeType,
7679 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007680 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007681
7682 // Initialize the iteration variable to zero.
7683 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007684 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007685
7686 // Create a reference to the iteration variable; we'll use this several
7687 // times throughout.
7688 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007689 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007690 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007691 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7692 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7693
Douglas Gregor06a9f362010-05-01 20:49:11 +00007694 // Create the DeclStmt that holds the iteration variable.
7695 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7696
7697 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007698 llvm::APInt Upper
7699 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007700 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007701 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007702 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7703 BO_NE, S.Context.BoolTy,
7704 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007705
7706 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007707 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007708 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7709 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007710
7711 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007712 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007713 IterationVarRefRVal,
7714 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007715 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007716 IterationVarRefRVal,
7717 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007718 if (!Copying) // Cast to rvalue
7719 From = CastForMoving(S, From);
7720
7721 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007722 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7723 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007724 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007725 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007726 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007727
7728 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007729 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007730 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007731 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007732 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007733}
7734
Sean Hunt30de05c2011-05-14 05:23:20 +00007735std::pair<Sema::ImplicitExceptionSpecification, bool>
7736Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7737 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007738 if (ClassDecl->isInvalidDecl())
7739 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7740
Douglas Gregord3c35902010-07-01 16:36:15 +00007741 // C++ [class.copy]p10:
7742 // If the class definition does not explicitly declare a copy
7743 // assignment operator, one is declared implicitly.
7744 // The implicitly-defined copy assignment operator for a class X
7745 // will have the form
7746 //
7747 // X& X::operator=(const X&)
7748 //
7749 // if
7750 bool HasConstCopyAssignment = true;
7751
7752 // -- each direct base class B of X has a copy assignment operator
7753 // whose parameter is of type const B&, const volatile B& or B,
7754 // and
7755 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7756 BaseEnd = ClassDecl->bases_end();
7757 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007758 // We'll handle this below
7759 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7760 continue;
7761
Douglas Gregord3c35902010-07-01 16:36:15 +00007762 assert(!Base->getType()->isDependentType() &&
7763 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007764 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7765 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7766 &HasConstCopyAssignment);
7767 }
7768
Richard Smithebaf0e62011-10-18 20:49:44 +00007769 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007770 if (LangOpts.CPlusPlus0x) {
7771 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7772 BaseEnd = ClassDecl->vbases_end();
7773 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7774 assert(!Base->getType()->isDependentType() &&
7775 "Cannot generate implicit members for class with dependent bases.");
7776 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7777 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7778 &HasConstCopyAssignment);
7779 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007780 }
7781
7782 // -- for all the nonstatic data members of X that are of a class
7783 // type M (or array thereof), each such class type has a copy
7784 // assignment operator whose parameter is of type const M&,
7785 // const volatile M& or M.
7786 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7787 FieldEnd = ClassDecl->field_end();
7788 HasConstCopyAssignment && Field != FieldEnd;
7789 ++Field) {
7790 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007791 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7792 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7793 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007794 }
7795 }
7796
7797 // Otherwise, the implicitly declared copy assignment operator will
7798 // have the form
7799 //
7800 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007801
Douglas Gregorb87786f2010-07-01 17:48:08 +00007802 // C++ [except.spec]p14:
7803 // An implicitly declared special member function (Clause 12) shall have an
7804 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007805
7806 // It is unspecified whether or not an implicit copy assignment operator
7807 // attempts to deduplicate calls to assignment operators of virtual bases are
7808 // made. As such, this exception specification is effectively unspecified.
7809 // Based on a similar decision made for constness in C++0x, we're erring on
7810 // the side of assuming such calls to be made regardless of whether they
7811 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007812 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007813 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007814 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7815 BaseEnd = ClassDecl->bases_end();
7816 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007817 if (Base->isVirtual())
7818 continue;
7819
Douglas Gregora376d102010-07-02 21:50:04 +00007820 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007821 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007822 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7823 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007824 ExceptSpec.CalledDecl(CopyAssign);
7825 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007826
7827 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7828 BaseEnd = ClassDecl->vbases_end();
7829 Base != BaseEnd; ++Base) {
7830 CXXRecordDecl *BaseClassDecl
7831 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7832 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7833 ArgQuals, false, 0))
7834 ExceptSpec.CalledDecl(CopyAssign);
7835 }
7836
Douglas Gregorb87786f2010-07-01 17:48:08 +00007837 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7838 FieldEnd = ClassDecl->field_end();
7839 Field != FieldEnd;
7840 ++Field) {
7841 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007842 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7843 if (CXXMethodDecl *CopyAssign =
7844 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7845 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007846 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007847 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007848
Sean Hunt30de05c2011-05-14 05:23:20 +00007849 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7850}
7851
7852CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7853 // Note: The following rules are largely analoguous to the copy
7854 // constructor rules. Note that virtual bases are not taken into account
7855 // for determining the argument type of the operator. Note also that
7856 // operators taking an object instead of a reference are allowed.
7857
7858 ImplicitExceptionSpecification Spec(Context);
7859 bool Const;
7860 llvm::tie(Spec, Const) =
7861 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7862
7863 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7864 QualType RetType = Context.getLValueReferenceType(ArgType);
7865 if (Const)
7866 ArgType = ArgType.withConst();
7867 ArgType = Context.getLValueReferenceType(ArgType);
7868
Douglas Gregord3c35902010-07-01 16:36:15 +00007869 // An implicitly-declared copy assignment operator is an inline public
7870 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007871 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007872 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007873 SourceLocation ClassLoc = ClassDecl->getLocation();
7874 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007875 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007876 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007877 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007878 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007879 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007880 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007881 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007882 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007883 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007884 CopyAssignment->setImplicit();
7885 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007886
7887 // Add the parameter to the operator.
7888 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007889 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007890 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007891 SC_None,
7892 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007893 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007894
Douglas Gregora376d102010-07-02 21:50:04 +00007895 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007896 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007897
Douglas Gregor23c94db2010-07-02 17:43:08 +00007898 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007899 PushOnScopeChains(CopyAssignment, S, false);
7900 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007901
Nico Weberafcc96a2012-01-23 03:19:29 +00007902 // C++0x [class.copy]p19:
7903 // .... If the class definition does not explicitly declare a copy
7904 // assignment operator, there is no user-declared move constructor, and
7905 // there is no user-declared move assignment operator, a copy assignment
7906 // operator is implicitly declared as defaulted.
7907 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber28976602012-01-23 04:01:33 +00007908 !getLangOptions().MicrosoftMode) ||
7909 ClassDecl->hasUserDeclaredMoveAssignment() ||
Sean Hunt1ccbc542011-06-22 01:05:13 +00007910 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007911 CopyAssignment->setDeletedAsWritten();
7912
Douglas Gregord3c35902010-07-01 16:36:15 +00007913 AddOverriddenMethods(ClassDecl, CopyAssignment);
7914 return CopyAssignment;
7915}
7916
Douglas Gregor06a9f362010-05-01 20:49:11 +00007917void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7918 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007919 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007920 CopyAssignOperator->isOverloadedOperator() &&
7921 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007922 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007923 "DefineImplicitCopyAssignment called for wrong function");
7924
7925 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7926
7927 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7928 CopyAssignOperator->setInvalidDecl();
7929 return;
7930 }
7931
7932 CopyAssignOperator->setUsed();
7933
7934 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007935 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007936
7937 // C++0x [class.copy]p30:
7938 // The implicitly-defined or explicitly-defaulted copy assignment operator
7939 // for a non-union class X performs memberwise copy assignment of its
7940 // subobjects. The direct base classes of X are assigned first, in the
7941 // order of their declaration in the base-specifier-list, and then the
7942 // immediate non-static data members of X are assigned, in the order in
7943 // which they were declared in the class definition.
7944
7945 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007946 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007947
7948 // The parameter for the "other" object, which we are copying from.
7949 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7950 Qualifiers OtherQuals = Other->getType().getQualifiers();
7951 QualType OtherRefType = Other->getType();
7952 if (const LValueReferenceType *OtherRef
7953 = OtherRefType->getAs<LValueReferenceType>()) {
7954 OtherRefType = OtherRef->getPointeeType();
7955 OtherQuals = OtherRefType.getQualifiers();
7956 }
7957
7958 // Our location for everything implicitly-generated.
7959 SourceLocation Loc = CopyAssignOperator->getLocation();
7960
7961 // Construct a reference to the "other" object. We'll be using this
7962 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007963 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007964 assert(OtherRef && "Reference to parameter cannot fail!");
7965
7966 // Construct the "this" pointer. We'll be using this throughout the generated
7967 // ASTs.
7968 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7969 assert(This && "Reference to this cannot fail!");
7970
7971 // Assign base classes.
7972 bool Invalid = false;
7973 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7974 E = ClassDecl->bases_end(); Base != E; ++Base) {
7975 // Form the assignment:
7976 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7977 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007978 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007979 Invalid = true;
7980 continue;
7981 }
7982
John McCallf871d0c2010-08-07 06:22:56 +00007983 CXXCastPath BasePath;
7984 BasePath.push_back(Base);
7985
Douglas Gregor06a9f362010-05-01 20:49:11 +00007986 // Construct the "from" expression, which is an implicit cast to the
7987 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007988 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007989 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7990 CK_UncheckedDerivedToBase,
7991 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007992
7993 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007994 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007995
7996 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007997 To = ImpCastExprToType(To.take(),
7998 Context.getCVRQualifiedType(BaseType,
7999 CopyAssignOperator->getTypeQualifiers()),
8000 CK_UncheckedDerivedToBase,
8001 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008002
8003 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00008004 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008005 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008006 /*CopyingBaseSubobject=*/true,
8007 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008008 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008009 Diag(CurrentLocation, diag::note_member_synthesized_at)
8010 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8011 CopyAssignOperator->setInvalidDecl();
8012 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008013 }
8014
8015 // Success! Record the copy.
8016 Statements.push_back(Copy.takeAs<Expr>());
8017 }
8018
8019 // \brief Reference to the __builtin_memcpy function.
8020 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008021 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008022 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008023
8024 // Assign non-static members.
8025 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8026 FieldEnd = ClassDecl->field_end();
8027 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008028 if (Field->isUnnamedBitfield())
8029 continue;
8030
Douglas Gregor06a9f362010-05-01 20:49:11 +00008031 // Check for members of reference type; we can't copy those.
8032 if (Field->getType()->isReferenceType()) {
8033 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8034 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8035 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008036 Diag(CurrentLocation, diag::note_member_synthesized_at)
8037 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008038 Invalid = true;
8039 continue;
8040 }
8041
8042 // Check for members of const-qualified, non-class type.
8043 QualType BaseType = Context.getBaseElementType(Field->getType());
8044 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8045 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8046 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8047 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008048 Diag(CurrentLocation, diag::note_member_synthesized_at)
8049 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008050 Invalid = true;
8051 continue;
8052 }
John McCallb77115d2011-06-17 00:18:42 +00008053
8054 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008055 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8056 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008057
8058 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008059 if (FieldType->isIncompleteArrayType()) {
8060 assert(ClassDecl->hasFlexibleArrayMember() &&
8061 "Incomplete array type is not valid");
8062 continue;
8063 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008064
8065 // Build references to the field in the object we're copying from and to.
8066 CXXScopeSpec SS; // Intentionally empty
8067 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8068 LookupMemberName);
8069 MemberLookup.addDecl(*Field);
8070 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008071 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008072 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008073 SS, SourceLocation(), 0,
8074 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008075 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008076 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008077 SS, SourceLocation(), 0,
8078 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008079 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8080 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8081
8082 // If the field should be copied with __builtin_memcpy rather than via
8083 // explicit assignments, do so. This optimization only applies for arrays
8084 // of scalars and arrays of class type with trivial copy-assignment
8085 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00008086 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008087 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008088 // Compute the size of the memory buffer to be copied.
8089 QualType SizeType = Context.getSizeType();
8090 llvm::APInt Size(Context.getTypeSize(SizeType),
8091 Context.getTypeSizeInChars(BaseType).getQuantity());
8092 for (const ConstantArrayType *Array
8093 = Context.getAsConstantArrayType(FieldType);
8094 Array;
8095 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00008096 llvm::APInt ArraySize
8097 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008098 Size *= ArraySize;
8099 }
8100
8101 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00008102 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8103 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008104
8105 bool NeedsCollectableMemCpy =
8106 (BaseType->isRecordType() &&
8107 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8108
8109 if (NeedsCollectableMemCpy) {
8110 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008111 // Create a reference to the __builtin_objc_memmove_collectable function.
8112 LookupResult R(*this,
8113 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008114 Loc, LookupOrdinaryName);
8115 LookupName(R, TUScope, true);
8116
8117 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8118 if (!CollectableMemCpy) {
8119 // Something went horribly wrong earlier, and we will have
8120 // complained about it.
8121 Invalid = true;
8122 continue;
8123 }
8124
8125 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8126 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008127 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008128 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8129 }
8130 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008131 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008132 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008133 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8134 LookupOrdinaryName);
8135 LookupName(R, TUScope, true);
8136
8137 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8138 if (!BuiltinMemCpy) {
8139 // Something went horribly wrong earlier, and we will have complained
8140 // about it.
8141 Invalid = true;
8142 continue;
8143 }
8144
8145 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8146 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008147 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008148 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8149 }
8150
John McCallca0408f2010-08-23 06:44:23 +00008151 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008152 CallArgs.push_back(To.takeAs<Expr>());
8153 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008154 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00008155 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008156 if (NeedsCollectableMemCpy)
8157 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008158 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008159 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008160 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008161 else
8162 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008163 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008164 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008165 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008166
Douglas Gregor06a9f362010-05-01 20:49:11 +00008167 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8168 Statements.push_back(Call.takeAs<Expr>());
8169 continue;
8170 }
8171
8172 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00008173 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008174 To.get(), From.get(),
8175 /*CopyingBaseSubobject=*/false,
8176 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008177 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008178 Diag(CurrentLocation, diag::note_member_synthesized_at)
8179 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8180 CopyAssignOperator->setInvalidDecl();
8181 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008182 }
8183
8184 // Success! Record the copy.
8185 Statements.push_back(Copy.takeAs<Stmt>());
8186 }
8187
8188 if (!Invalid) {
8189 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008190 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008191
John McCall60d7b3a2010-08-24 06:29:42 +00008192 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008193 if (Return.isInvalid())
8194 Invalid = true;
8195 else {
8196 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008197
8198 if (Trap.hasErrorOccurred()) {
8199 Diag(CurrentLocation, diag::note_member_synthesized_at)
8200 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8201 Invalid = true;
8202 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008203 }
8204 }
8205
8206 if (Invalid) {
8207 CopyAssignOperator->setInvalidDecl();
8208 return;
8209 }
8210
John McCall60d7b3a2010-08-24 06:29:42 +00008211 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00008212 /*isStmtExpr=*/false);
8213 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8214 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008215
8216 if (ASTMutationListener *L = getASTMutationListener()) {
8217 L->CompletedImplicitDefinition(CopyAssignOperator);
8218 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008219}
8220
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008221Sema::ImplicitExceptionSpecification
8222Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8223 ImplicitExceptionSpecification ExceptSpec(Context);
8224
8225 if (ClassDecl->isInvalidDecl())
8226 return ExceptSpec;
8227
8228 // C++0x [except.spec]p14:
8229 // An implicitly declared special member function (Clause 12) shall have an
8230 // exception-specification. [...]
8231
8232 // It is unspecified whether or not an implicit move assignment operator
8233 // attempts to deduplicate calls to assignment operators of virtual bases are
8234 // made. As such, this exception specification is effectively unspecified.
8235 // Based on a similar decision made for constness in C++0x, we're erring on
8236 // the side of assuming such calls to be made regardless of whether they
8237 // actually happen.
8238 // Note that a move constructor is not implicitly declared when there are
8239 // virtual bases, but it can still be user-declared and explicitly defaulted.
8240 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8241 BaseEnd = ClassDecl->bases_end();
8242 Base != BaseEnd; ++Base) {
8243 if (Base->isVirtual())
8244 continue;
8245
8246 CXXRecordDecl *BaseClassDecl
8247 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8248 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8249 false, 0))
8250 ExceptSpec.CalledDecl(MoveAssign);
8251 }
8252
8253 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8254 BaseEnd = ClassDecl->vbases_end();
8255 Base != BaseEnd; ++Base) {
8256 CXXRecordDecl *BaseClassDecl
8257 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8258 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8259 false, 0))
8260 ExceptSpec.CalledDecl(MoveAssign);
8261 }
8262
8263 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8264 FieldEnd = ClassDecl->field_end();
8265 Field != FieldEnd;
8266 ++Field) {
8267 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8268 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8269 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8270 false, 0))
8271 ExceptSpec.CalledDecl(MoveAssign);
8272 }
8273 }
8274
8275 return ExceptSpec;
8276}
8277
8278CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8279 // Note: The following rules are largely analoguous to the move
8280 // constructor rules.
8281
8282 ImplicitExceptionSpecification Spec(
8283 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8284
8285 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8286 QualType RetType = Context.getLValueReferenceType(ArgType);
8287 ArgType = Context.getRValueReferenceType(ArgType);
8288
8289 // An implicitly-declared move assignment operator is an inline public
8290 // member of its class.
8291 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8292 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8293 SourceLocation ClassLoc = ClassDecl->getLocation();
8294 DeclarationNameInfo NameInfo(Name, ClassLoc);
8295 CXXMethodDecl *MoveAssignment
8296 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8297 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8298 /*TInfo=*/0, /*isStatic=*/false,
8299 /*StorageClassAsWritten=*/SC_None,
8300 /*isInline=*/true,
8301 /*isConstexpr=*/false,
8302 SourceLocation());
8303 MoveAssignment->setAccess(AS_public);
8304 MoveAssignment->setDefaulted();
8305 MoveAssignment->setImplicit();
8306 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8307
8308 // Add the parameter to the operator.
8309 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8310 ClassLoc, ClassLoc, /*Id=*/0,
8311 ArgType, /*TInfo=*/0,
8312 SC_None,
8313 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008314 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008315
8316 // Note that we have added this copy-assignment operator.
8317 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8318
8319 // C++0x [class.copy]p9:
8320 // If the definition of a class X does not explicitly declare a move
8321 // assignment operator, one will be implicitly declared as defaulted if and
8322 // only if:
8323 // [...]
8324 // - the move assignment operator would not be implicitly defined as
8325 // deleted.
8326 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8327 // Cache this result so that we don't try to generate this over and over
8328 // on every lookup, leaking memory and wasting time.
8329 ClassDecl->setFailedImplicitMoveAssignment();
8330 return 0;
8331 }
8332
8333 if (Scope *S = getScopeForContext(ClassDecl))
8334 PushOnScopeChains(MoveAssignment, S, false);
8335 ClassDecl->addDecl(MoveAssignment);
8336
8337 AddOverriddenMethods(ClassDecl, MoveAssignment);
8338 return MoveAssignment;
8339}
8340
8341void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8342 CXXMethodDecl *MoveAssignOperator) {
8343 assert((MoveAssignOperator->isDefaulted() &&
8344 MoveAssignOperator->isOverloadedOperator() &&
8345 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8346 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8347 "DefineImplicitMoveAssignment called for wrong function");
8348
8349 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8350
8351 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8352 MoveAssignOperator->setInvalidDecl();
8353 return;
8354 }
8355
8356 MoveAssignOperator->setUsed();
8357
8358 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8359 DiagnosticErrorTrap Trap(Diags);
8360
8361 // C++0x [class.copy]p28:
8362 // The implicitly-defined or move assignment operator for a non-union class
8363 // X performs memberwise move assignment of its subobjects. The direct base
8364 // classes of X are assigned first, in the order of their declaration in the
8365 // base-specifier-list, and then the immediate non-static data members of X
8366 // are assigned, in the order in which they were declared in the class
8367 // definition.
8368
8369 // The statements that form the synthesized function body.
8370 ASTOwningVector<Stmt*> Statements(*this);
8371
8372 // The parameter for the "other" object, which we are move from.
8373 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8374 QualType OtherRefType = Other->getType()->
8375 getAs<RValueReferenceType>()->getPointeeType();
8376 assert(OtherRefType.getQualifiers() == 0 &&
8377 "Bad argument type of defaulted move assignment");
8378
8379 // Our location for everything implicitly-generated.
8380 SourceLocation Loc = MoveAssignOperator->getLocation();
8381
8382 // Construct a reference to the "other" object. We'll be using this
8383 // throughout the generated ASTs.
8384 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8385 assert(OtherRef && "Reference to parameter cannot fail!");
8386 // Cast to rvalue.
8387 OtherRef = CastForMoving(*this, OtherRef);
8388
8389 // Construct the "this" pointer. We'll be using this throughout the generated
8390 // ASTs.
8391 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8392 assert(This && "Reference to this cannot fail!");
8393
8394 // Assign base classes.
8395 bool Invalid = false;
8396 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8397 E = ClassDecl->bases_end(); Base != E; ++Base) {
8398 // Form the assignment:
8399 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8400 QualType BaseType = Base->getType().getUnqualifiedType();
8401 if (!BaseType->isRecordType()) {
8402 Invalid = true;
8403 continue;
8404 }
8405
8406 CXXCastPath BasePath;
8407 BasePath.push_back(Base);
8408
8409 // Construct the "from" expression, which is an implicit cast to the
8410 // appropriately-qualified base type.
8411 Expr *From = OtherRef;
8412 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008413 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008414
8415 // Dereference "this".
8416 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8417
8418 // Implicitly cast "this" to the appropriately-qualified base type.
8419 To = ImpCastExprToType(To.take(),
8420 Context.getCVRQualifiedType(BaseType,
8421 MoveAssignOperator->getTypeQualifiers()),
8422 CK_UncheckedDerivedToBase,
8423 VK_LValue, &BasePath);
8424
8425 // Build the move.
8426 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8427 To.get(), From,
8428 /*CopyingBaseSubobject=*/true,
8429 /*Copying=*/false);
8430 if (Move.isInvalid()) {
8431 Diag(CurrentLocation, diag::note_member_synthesized_at)
8432 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8433 MoveAssignOperator->setInvalidDecl();
8434 return;
8435 }
8436
8437 // Success! Record the move.
8438 Statements.push_back(Move.takeAs<Expr>());
8439 }
8440
8441 // \brief Reference to the __builtin_memcpy function.
8442 Expr *BuiltinMemCpyRef = 0;
8443 // \brief Reference to the __builtin_objc_memmove_collectable function.
8444 Expr *CollectableMemCpyRef = 0;
8445
8446 // Assign non-static members.
8447 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8448 FieldEnd = ClassDecl->field_end();
8449 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008450 if (Field->isUnnamedBitfield())
8451 continue;
8452
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008453 // Check for members of reference type; we can't move those.
8454 if (Field->getType()->isReferenceType()) {
8455 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8456 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8457 Diag(Field->getLocation(), diag::note_declared_at);
8458 Diag(CurrentLocation, diag::note_member_synthesized_at)
8459 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8460 Invalid = true;
8461 continue;
8462 }
8463
8464 // Check for members of const-qualified, non-class type.
8465 QualType BaseType = Context.getBaseElementType(Field->getType());
8466 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8467 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8468 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8469 Diag(Field->getLocation(), diag::note_declared_at);
8470 Diag(CurrentLocation, diag::note_member_synthesized_at)
8471 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8472 Invalid = true;
8473 continue;
8474 }
8475
8476 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008477 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8478 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008479
8480 QualType FieldType = Field->getType().getNonReferenceType();
8481 if (FieldType->isIncompleteArrayType()) {
8482 assert(ClassDecl->hasFlexibleArrayMember() &&
8483 "Incomplete array type is not valid");
8484 continue;
8485 }
8486
8487 // Build references to the field in the object we're copying from and to.
8488 CXXScopeSpec SS; // Intentionally empty
8489 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8490 LookupMemberName);
8491 MemberLookup.addDecl(*Field);
8492 MemberLookup.resolveKind();
8493 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8494 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008495 SS, SourceLocation(), 0,
8496 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008497 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8498 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008499 SS, SourceLocation(), 0,
8500 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008501 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8502 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8503
8504 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8505 "Member reference with rvalue base must be rvalue except for reference "
8506 "members, which aren't allowed for move assignment.");
8507
8508 // If the field should be copied with __builtin_memcpy rather than via
8509 // explicit assignments, do so. This optimization only applies for arrays
8510 // of scalars and arrays of class type with trivial move-assignment
8511 // operators.
8512 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8513 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8514 // Compute the size of the memory buffer to be copied.
8515 QualType SizeType = Context.getSizeType();
8516 llvm::APInt Size(Context.getTypeSize(SizeType),
8517 Context.getTypeSizeInChars(BaseType).getQuantity());
8518 for (const ConstantArrayType *Array
8519 = Context.getAsConstantArrayType(FieldType);
8520 Array;
8521 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8522 llvm::APInt ArraySize
8523 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8524 Size *= ArraySize;
8525 }
8526
Douglas Gregor45d3d712011-09-01 02:09:07 +00008527 // Take the address of the field references for "from" and "to". We
8528 // directly construct UnaryOperators here because semantic analysis
8529 // does not permit us to take the address of an xvalue.
8530 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8531 Context.getPointerType(From.get()->getType()),
8532 VK_RValue, OK_Ordinary, Loc);
8533 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8534 Context.getPointerType(To.get()->getType()),
8535 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008536
8537 bool NeedsCollectableMemCpy =
8538 (BaseType->isRecordType() &&
8539 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8540
8541 if (NeedsCollectableMemCpy) {
8542 if (!CollectableMemCpyRef) {
8543 // Create a reference to the __builtin_objc_memmove_collectable function.
8544 LookupResult R(*this,
8545 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8546 Loc, LookupOrdinaryName);
8547 LookupName(R, TUScope, true);
8548
8549 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8550 if (!CollectableMemCpy) {
8551 // Something went horribly wrong earlier, and we will have
8552 // complained about it.
8553 Invalid = true;
8554 continue;
8555 }
8556
8557 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8558 CollectableMemCpy->getType(),
8559 VK_LValue, Loc, 0).take();
8560 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8561 }
8562 }
8563 // Create a reference to the __builtin_memcpy builtin function.
8564 else if (!BuiltinMemCpyRef) {
8565 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8566 LookupOrdinaryName);
8567 LookupName(R, TUScope, true);
8568
8569 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8570 if (!BuiltinMemCpy) {
8571 // Something went horribly wrong earlier, and we will have complained
8572 // about it.
8573 Invalid = true;
8574 continue;
8575 }
8576
8577 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8578 BuiltinMemCpy->getType(),
8579 VK_LValue, Loc, 0).take();
8580 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8581 }
8582
8583 ASTOwningVector<Expr*> CallArgs(*this);
8584 CallArgs.push_back(To.takeAs<Expr>());
8585 CallArgs.push_back(From.takeAs<Expr>());
8586 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8587 ExprResult Call = ExprError();
8588 if (NeedsCollectableMemCpy)
8589 Call = ActOnCallExpr(/*Scope=*/0,
8590 CollectableMemCpyRef,
8591 Loc, move_arg(CallArgs),
8592 Loc);
8593 else
8594 Call = ActOnCallExpr(/*Scope=*/0,
8595 BuiltinMemCpyRef,
8596 Loc, move_arg(CallArgs),
8597 Loc);
8598
8599 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8600 Statements.push_back(Call.takeAs<Expr>());
8601 continue;
8602 }
8603
8604 // Build the move of this field.
8605 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8606 To.get(), From.get(),
8607 /*CopyingBaseSubobject=*/false,
8608 /*Copying=*/false);
8609 if (Move.isInvalid()) {
8610 Diag(CurrentLocation, diag::note_member_synthesized_at)
8611 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8612 MoveAssignOperator->setInvalidDecl();
8613 return;
8614 }
8615
8616 // Success! Record the copy.
8617 Statements.push_back(Move.takeAs<Stmt>());
8618 }
8619
8620 if (!Invalid) {
8621 // Add a "return *this;"
8622 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8623
8624 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8625 if (Return.isInvalid())
8626 Invalid = true;
8627 else {
8628 Statements.push_back(Return.takeAs<Stmt>());
8629
8630 if (Trap.hasErrorOccurred()) {
8631 Diag(CurrentLocation, diag::note_member_synthesized_at)
8632 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8633 Invalid = true;
8634 }
8635 }
8636 }
8637
8638 if (Invalid) {
8639 MoveAssignOperator->setInvalidDecl();
8640 return;
8641 }
8642
8643 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8644 /*isStmtExpr=*/false);
8645 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8646 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8647
8648 if (ASTMutationListener *L = getASTMutationListener()) {
8649 L->CompletedImplicitDefinition(MoveAssignOperator);
8650 }
8651}
8652
Sean Hunt49634cf2011-05-13 06:10:58 +00008653std::pair<Sema::ImplicitExceptionSpecification, bool>
8654Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008655 if (ClassDecl->isInvalidDecl())
8656 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8657
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008658 // C++ [class.copy]p5:
8659 // The implicitly-declared copy constructor for a class X will
8660 // have the form
8661 //
8662 // X::X(const X&)
8663 //
8664 // if
Sean Huntc530d172011-06-10 04:44:37 +00008665 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008666 bool HasConstCopyConstructor = true;
8667
8668 // -- each direct or virtual base class B of X has a copy
8669 // constructor whose first parameter is of type const B& or
8670 // const volatile B&, and
8671 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8672 BaseEnd = ClassDecl->bases_end();
8673 HasConstCopyConstructor && Base != BaseEnd;
8674 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008675 // Virtual bases are handled below.
8676 if (Base->isVirtual())
8677 continue;
8678
Douglas Gregor22584312010-07-02 23:41:54 +00008679 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008680 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008681 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8682 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008683 }
8684
8685 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8686 BaseEnd = ClassDecl->vbases_end();
8687 HasConstCopyConstructor && Base != BaseEnd;
8688 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008689 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008690 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008691 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8692 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008693 }
8694
8695 // -- for all the nonstatic data members of X that are of a
8696 // class type M (or array thereof), each such class type
8697 // has a copy constructor whose first parameter is of type
8698 // const M& or const volatile M&.
8699 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8700 FieldEnd = ClassDecl->field_end();
8701 HasConstCopyConstructor && Field != FieldEnd;
8702 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008703 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008704 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008705 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8706 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008707 }
8708 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008709 // Otherwise, the implicitly declared copy constructor will have
8710 // the form
8711 //
8712 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008713
Douglas Gregor0d405db2010-07-01 20:59:04 +00008714 // C++ [except.spec]p14:
8715 // An implicitly declared special member function (Clause 12) shall have an
8716 // exception-specification. [...]
8717 ImplicitExceptionSpecification ExceptSpec(Context);
8718 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8719 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8720 BaseEnd = ClassDecl->bases_end();
8721 Base != BaseEnd;
8722 ++Base) {
8723 // Virtual bases are handled below.
8724 if (Base->isVirtual())
8725 continue;
8726
Douglas Gregor22584312010-07-02 23:41:54 +00008727 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008728 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008729 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008730 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008731 ExceptSpec.CalledDecl(CopyConstructor);
8732 }
8733 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8734 BaseEnd = ClassDecl->vbases_end();
8735 Base != BaseEnd;
8736 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008737 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008738 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008739 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008740 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008741 ExceptSpec.CalledDecl(CopyConstructor);
8742 }
8743 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8744 FieldEnd = ClassDecl->field_end();
8745 Field != FieldEnd;
8746 ++Field) {
8747 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008748 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8749 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008750 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008751 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008752 }
8753 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008754
Sean Hunt49634cf2011-05-13 06:10:58 +00008755 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8756}
8757
8758CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8759 CXXRecordDecl *ClassDecl) {
8760 // C++ [class.copy]p4:
8761 // If the class definition does not explicitly declare a copy
8762 // constructor, one is declared implicitly.
8763
8764 ImplicitExceptionSpecification Spec(Context);
8765 bool Const;
8766 llvm::tie(Spec, Const) =
8767 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8768
8769 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8770 QualType ArgType = ClassType;
8771 if (Const)
8772 ArgType = ArgType.withConst();
8773 ArgType = Context.getLValueReferenceType(ArgType);
8774
8775 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8776
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008777 DeclarationName Name
8778 = Context.DeclarationNames.getCXXConstructorName(
8779 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008780 SourceLocation ClassLoc = ClassDecl->getLocation();
8781 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008782
8783 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008784 // member of its class.
8785 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8786 Context, ClassDecl, ClassLoc, NameInfo,
8787 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8788 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8789 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8790 getLangOptions().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008791 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008792 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008793 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008794
Douglas Gregor22584312010-07-02 23:41:54 +00008795 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008796 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8797
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008798 // Add the parameter to the constructor.
8799 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008800 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008801 /*IdentifierInfo=*/0,
8802 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008803 SC_None,
8804 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008805 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008806
Douglas Gregor23c94db2010-07-02 17:43:08 +00008807 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008808 PushOnScopeChains(CopyConstructor, S, false);
8809 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008810
Nico Weberafcc96a2012-01-23 03:19:29 +00008811 // C++11 [class.copy]p8:
8812 // ... If the class definition does not explicitly declare a copy
8813 // constructor, there is no user-declared move constructor, and there is no
8814 // user-declared move assignment operator, a copy constructor is implicitly
8815 // declared as defaulted.
Sean Hunt1ccbc542011-06-22 01:05:13 +00008816 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weberafcc96a2012-01-23 03:19:29 +00008817 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber28976602012-01-23 04:01:33 +00008818 !getLangOptions().MicrosoftMode) ||
Sean Huntc32d6842011-10-11 04:55:36 +00008819 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008820 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008821
8822 return CopyConstructor;
8823}
8824
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008825void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008826 CXXConstructorDecl *CopyConstructor) {
8827 assert((CopyConstructor->isDefaulted() &&
8828 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008829 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008830 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008831
Anders Carlsson63010a72010-04-23 16:24:12 +00008832 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008833 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008834
Douglas Gregor39957dc2010-05-01 15:04:51 +00008835 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008836 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008837
Sean Huntcbb67482011-01-08 20:30:50 +00008838 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008839 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008840 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008841 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008842 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008843 } else {
8844 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8845 CopyConstructor->getLocation(),
8846 MultiStmtArg(*this, 0, 0),
8847 /*isStmtExpr=*/false)
8848 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008849 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008850 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008851
8852 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008853 if (ASTMutationListener *L = getASTMutationListener()) {
8854 L->CompletedImplicitDefinition(CopyConstructor);
8855 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008856}
8857
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008858Sema::ImplicitExceptionSpecification
8859Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8860 // C++ [except.spec]p14:
8861 // An implicitly declared special member function (Clause 12) shall have an
8862 // exception-specification. [...]
8863 ImplicitExceptionSpecification ExceptSpec(Context);
8864 if (ClassDecl->isInvalidDecl())
8865 return ExceptSpec;
8866
8867 // Direct base-class constructors.
8868 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8869 BEnd = ClassDecl->bases_end();
8870 B != BEnd; ++B) {
8871 if (B->isVirtual()) // Handled below.
8872 continue;
8873
8874 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8875 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8876 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8877 // If this is a deleted function, add it anyway. This might be conformant
8878 // with the standard. This might not. I'm not sure. It might not matter.
8879 if (Constructor)
8880 ExceptSpec.CalledDecl(Constructor);
8881 }
8882 }
8883
8884 // Virtual base-class constructors.
8885 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8886 BEnd = ClassDecl->vbases_end();
8887 B != BEnd; ++B) {
8888 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8889 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8890 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8891 // If this is a deleted function, add it anyway. This might be conformant
8892 // with the standard. This might not. I'm not sure. It might not matter.
8893 if (Constructor)
8894 ExceptSpec.CalledDecl(Constructor);
8895 }
8896 }
8897
8898 // Field constructors.
8899 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8900 FEnd = ClassDecl->field_end();
8901 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008902 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008903 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8904 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8905 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8906 // If this is a deleted function, add it anyway. This might be conformant
8907 // with the standard. This might not. I'm not sure. It might not matter.
8908 // In particular, the problem is that this function never gets called. It
8909 // might just be ill-formed because this function attempts to refer to
8910 // a deleted function here.
8911 if (Constructor)
8912 ExceptSpec.CalledDecl(Constructor);
8913 }
8914 }
8915
8916 return ExceptSpec;
8917}
8918
8919CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8920 CXXRecordDecl *ClassDecl) {
8921 ImplicitExceptionSpecification Spec(
8922 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8923
8924 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8925 QualType ArgType = Context.getRValueReferenceType(ClassType);
8926
8927 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8928
8929 DeclarationName Name
8930 = Context.DeclarationNames.getCXXConstructorName(
8931 Context.getCanonicalType(ClassType));
8932 SourceLocation ClassLoc = ClassDecl->getLocation();
8933 DeclarationNameInfo NameInfo(Name, ClassLoc);
8934
8935 // C++0x [class.copy]p11:
8936 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008937 // member of its class.
8938 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8939 Context, ClassDecl, ClassLoc, NameInfo,
8940 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8941 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8942 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8943 getLangOptions().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008944 MoveConstructor->setAccess(AS_public);
8945 MoveConstructor->setDefaulted();
8946 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008947
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008948 // Add the parameter to the constructor.
8949 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8950 ClassLoc, ClassLoc,
8951 /*IdentifierInfo=*/0,
8952 ArgType, /*TInfo=*/0,
8953 SC_None,
8954 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008955 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008956
8957 // C++0x [class.copy]p9:
8958 // If the definition of a class X does not explicitly declare a move
8959 // constructor, one will be implicitly declared as defaulted if and only if:
8960 // [...]
8961 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008962 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008963 // Cache this result so that we don't try to generate this over and over
8964 // on every lookup, leaking memory and wasting time.
8965 ClassDecl->setFailedImplicitMoveConstructor();
8966 return 0;
8967 }
8968
8969 // Note that we have declared this constructor.
8970 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8971
8972 if (Scope *S = getScopeForContext(ClassDecl))
8973 PushOnScopeChains(MoveConstructor, S, false);
8974 ClassDecl->addDecl(MoveConstructor);
8975
8976 return MoveConstructor;
8977}
8978
8979void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8980 CXXConstructorDecl *MoveConstructor) {
8981 assert((MoveConstructor->isDefaulted() &&
8982 MoveConstructor->isMoveConstructor() &&
8983 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8984 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8985
8986 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8987 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8988
8989 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8990 DiagnosticErrorTrap Trap(Diags);
8991
8992 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8993 Trap.hasErrorOccurred()) {
8994 Diag(CurrentLocation, diag::note_member_synthesized_at)
8995 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8996 MoveConstructor->setInvalidDecl();
8997 } else {
8998 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8999 MoveConstructor->getLocation(),
9000 MultiStmtArg(*this, 0, 0),
9001 /*isStmtExpr=*/false)
9002 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009003 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009004 }
9005
9006 MoveConstructor->setUsed();
9007
9008 if (ASTMutationListener *L = getASTMutationListener()) {
9009 L->CompletedImplicitDefinition(MoveConstructor);
9010 }
9011}
9012
John McCall60d7b3a2010-08-24 06:29:42 +00009013ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009014Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009015 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009016 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009017 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009018 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009019 unsigned ConstructKind,
9020 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009021 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009022
Douglas Gregor2f599792010-04-02 18:24:57 +00009023 // C++0x [class.copy]p34:
9024 // When certain criteria are met, an implementation is allowed to
9025 // omit the copy/move construction of a class object, even if the
9026 // copy/move constructor and/or destructor for the object have
9027 // side effects. [...]
9028 // - when a temporary class object that has not been bound to a
9029 // reference (12.2) would be copied/moved to a class object
9030 // with the same cv-unqualified type, the copy/move operation
9031 // can be omitted by constructing the temporary object
9032 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009033 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00009034 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009035 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009036 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009037 }
Mike Stump1eb44332009-09-09 15:08:12 +00009038
9039 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009040 Elidable, move(ExprArgs), HadMultipleCandidates,
9041 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009042}
9043
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009044/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9045/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009046ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009047Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9048 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009049 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009050 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009051 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009052 unsigned ConstructKind,
9053 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009054 unsigned NumExprs = ExprArgs.size();
9055 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009056
Nick Lewycky909a70d2011-03-25 01:44:32 +00009057 for (specific_attr_iterator<NonNullAttr>
9058 i = Constructor->specific_attr_begin<NonNullAttr>(),
9059 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9060 const NonNullAttr *NonNull = *i;
9061 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9062 }
9063
Eli Friedman5f2987c2012-02-02 03:46:19 +00009064 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009065 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009066 Constructor, Elidable, Exprs, NumExprs,
9067 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009068 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9069 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009070}
9071
Mike Stump1eb44332009-09-09 15:08:12 +00009072bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009073 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009074 MultiExprArg Exprs,
9075 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009076 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009077 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009078 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009079 move(Exprs), HadMultipleCandidates, false,
9080 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009081 if (TempResult.isInvalid())
9082 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009083
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009084 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009085 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009086 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009087 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009088 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009089
Anders Carlssonfe2de492009-08-25 05:18:00 +00009090 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009091}
9092
John McCall68c6c9a2010-02-02 09:10:11 +00009093void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009094 if (VD->isInvalidDecl()) return;
9095
John McCall68c6c9a2010-02-02 09:10:11 +00009096 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009097 if (ClassDecl->isInvalidDecl()) return;
9098 if (ClassDecl->hasTrivialDestructor()) return;
9099 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009100
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009101 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009102 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009103 CheckDestructorAccess(VD->getLocation(), Destructor,
9104 PDiag(diag::err_access_dtor_var)
9105 << VD->getDeclName()
9106 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009107
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009108 if (!VD->hasGlobalStorage()) return;
9109
9110 // Emit warning for non-trivial dtor in global scope (a real global,
9111 // class-static, function-static).
9112 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9113
9114 // TODO: this should be re-enabled for static locals by !CXAAtExit
9115 if (!VD->isStaticLocal())
9116 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009117}
9118
Mike Stump1eb44332009-09-09 15:08:12 +00009119/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009120/// ActOnDeclarator, when a C++ direct initializer is present.
9121/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00009122void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00009123 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009124 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00009125 SourceLocation RParenLoc,
9126 bool TypeMayContainAuto) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009127 // If there is no declaration, there was an error parsing it. Just ignore
9128 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00009129 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009130 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009131
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009132 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9133 if (!VDecl) {
9134 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9135 RealDecl->setInvalidDecl();
9136 return;
9137 }
9138
Eli Friedman6aeaa602012-01-05 22:34:08 +00009139 // C++0x [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith34b41d92011-02-20 03:19:35 +00009140 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Eli Friedman6aeaa602012-01-05 22:34:08 +00009141 if (Exprs.size() == 0) {
9142 // It isn't possible to write this directly, but it is possible to
9143 // end up in this situation with "auto x(some_pack...);"
9144 Diag(LParenLoc, diag::err_auto_var_init_no_expression)
9145 << VDecl->getDeclName() << VDecl->getType()
9146 << VDecl->getSourceRange();
9147 RealDecl->setInvalidDecl();
9148 return;
9149 }
9150
Richard Smith34b41d92011-02-20 03:19:35 +00009151 if (Exprs.size() > 1) {
9152 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
9153 diag::err_auto_var_init_multiple_expressions)
9154 << VDecl->getDeclName() << VDecl->getType()
9155 << VDecl->getSourceRange();
9156 RealDecl->setInvalidDecl();
9157 return;
9158 }
9159
9160 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00009161 TypeSourceInfo *DeducedType = 0;
Sebastian Redlb832f6d2012-01-23 22:09:39 +00009162 if (DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType) ==
9163 DAR_Failed)
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00009164 DiagnoseAutoDeductionFailure(VDecl, Init);
Richard Smitha085da82011-03-17 16:11:59 +00009165 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00009166 RealDecl->setInvalidDecl();
9167 return;
9168 }
Richard Smitha085da82011-03-17 16:11:59 +00009169 VDecl->setTypeSourceInfo(DeducedType);
9170 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00009171
John McCallf85e1932011-06-15 23:02:42 +00009172 // In ARC, infer lifetime.
9173 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9174 VDecl->setInvalidDecl();
9175
Richard Smith34b41d92011-02-20 03:19:35 +00009176 // If this is a redeclaration, check that the type we just deduced matches
9177 // the previously declared type.
Douglas Gregoref96ee02012-01-14 16:38:05 +00009178 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith34b41d92011-02-20 03:19:35 +00009179 MergeVarDeclTypes(VDecl, Old);
9180 }
9181
Douglas Gregor83ddad32009-08-26 21:14:46 +00009182 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009183 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009184 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9185 //
9186 // Clients that want to distinguish between the two forms, can check for
9187 // direct initializer using VarDecl::hasCXXDirectInitializer().
9188 // A major benefit is that clients that don't particularly care about which
9189 // exactly form was it (like the CodeGen) can handle both cases without
9190 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009191
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009192 // C++ 8.5p11:
9193 // The form of initialization (using parentheses or '=') is generally
9194 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009195 // class type.
9196
Douglas Gregor4dffad62010-02-11 22:55:30 +00009197 if (!VDecl->getType()->isDependentType() &&
Douglas Gregord24c3062011-10-10 16:05:18 +00009198 !VDecl->getType()->isIncompleteArrayType() &&
Douglas Gregor4dffad62010-02-11 22:55:30 +00009199 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00009200 diag::err_typecheck_decl_incomplete_type)) {
9201 VDecl->setInvalidDecl();
9202 return;
9203 }
9204
Douglas Gregor90f93822009-12-22 22:17:25 +00009205 // The variable can not have an abstract class type.
9206 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9207 diag::err_abstract_type_in_decl,
9208 AbstractVariableType))
9209 VDecl->setInvalidDecl();
9210
Sebastian Redl31310a22010-02-01 20:16:42 +00009211 const VarDecl *Def;
9212 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00009213 Diag(VDecl->getLocation(), diag::err_redefinition)
9214 << VDecl->getDeclName();
9215 Diag(Def->getLocation(), diag::note_previous_definition);
9216 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009217 return;
9218 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00009219
Douglas Gregor3a91abf2010-08-24 05:27:49 +00009220 // C++ [class.static.data]p4
9221 // If a static data member is of const integral or const
9222 // enumeration type, its declaration in the class definition can
9223 // specify a constant-initializer which shall be an integral
9224 // constant expression (5.19). In that case, the member can appear
9225 // in integral constant expressions. The member shall still be
9226 // defined in a namespace scope if it is used in the program and the
9227 // namespace scope definition shall not contain an initializer.
9228 //
9229 // We already performed a redefinition check above, but for static
9230 // data members we also need to check whether there was an in-class
9231 // declaration with an initializer.
9232 const VarDecl* PrevInit = 0;
9233 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9234 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9235 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9236 return;
9237 }
9238
Eli Friedman7badd242012-02-09 20:13:14 +00009239 if (VDecl->hasLocalStorage())
9240 getCurFunction()->setHasBranchProtectedScope();
9241
Douglas Gregora31040f2010-12-16 01:31:22 +00009242 bool IsDependent = false;
9243 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9244 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9245 VDecl->setInvalidDecl();
9246 return;
9247 }
9248
9249 if (Exprs.get()[I]->isTypeDependent())
9250 IsDependent = true;
9251 }
9252
Douglas Gregor4dffad62010-02-11 22:55:30 +00009253 // If either the declaration has a dependent type or if any of the
9254 // expressions is type-dependent, we represent the initialization
9255 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00009256 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00009257 // Let clients know that initialization was done with a direct initializer.
9258 VDecl->setCXXDirectInitializer(true);
9259
9260 // Store the initialization expressions as a ParenListExpr.
9261 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00009262 VDecl->setInit(new (Context) ParenListExpr(
9263 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9264 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00009265 return;
9266 }
Douglas Gregor90f93822009-12-22 22:17:25 +00009267
9268 // Capture the variable that is being initialized and the style of
9269 // initialization.
9270 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9271
9272 // FIXME: Poor source location information.
9273 InitializationKind Kind
9274 = InitializationKind::CreateDirect(VDecl->getLocation(),
9275 LParenLoc, RParenLoc);
9276
Douglas Gregord24c3062011-10-10 16:05:18 +00009277 QualType T = VDecl->getType();
Douglas Gregor90f93822009-12-22 22:17:25 +00009278 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00009279 Exprs.get(), Exprs.size());
Douglas Gregord24c3062011-10-10 16:05:18 +00009280 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
Douglas Gregor90f93822009-12-22 22:17:25 +00009281 if (Result.isInvalid()) {
9282 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009283 return;
Douglas Gregord24c3062011-10-10 16:05:18 +00009284 } else if (T != VDecl->getType()) {
9285 VDecl->setType(T);
9286 Result.get()->setType(T);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009287 }
John McCallb4eb64d2010-10-08 02:01:28 +00009288
Douglas Gregord24c3062011-10-10 16:05:18 +00009289
Richard Smithc6d990a2011-09-29 19:11:37 +00009290 Expr *Init = Result.get();
9291 CheckImplicitConversions(Init, LParenLoc);
Richard Smithc6d990a2011-09-29 19:11:37 +00009292
9293 Init = MaybeCreateExprWithCleanups(Init);
9294 VDecl->setInit(Init);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009295 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009296
John McCall2998d6b2011-01-19 11:48:09 +00009297 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009298}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00009299
Douglas Gregor39da0b82009-09-09 23:08:42 +00009300/// \brief Given a constructor and the set of arguments provided for the
9301/// constructor, convert the arguments and add any required default arguments
9302/// to form a proper call to this constructor.
9303///
9304/// \returns true if an error occurred, false otherwise.
9305bool
9306Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9307 MultiExprArg ArgsPtr,
9308 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00009309 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009310 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9311 unsigned NumArgs = ArgsPtr.size();
9312 Expr **Args = (Expr **)ArgsPtr.get();
9313
9314 const FunctionProtoType *Proto
9315 = Constructor->getType()->getAs<FunctionProtoType>();
9316 assert(Proto && "Constructor without a prototype?");
9317 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009318
9319 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009320 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009321 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009322 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009323 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009324
9325 VariadicCallType CallType =
9326 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009327 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009328 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9329 Proto, 0, Args, NumArgs, AllArgs,
9330 CallType);
9331 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9332 ConvertedArgs.push_back(AllArgs[i]);
9333 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009334}
9335
Anders Carlsson20d45d22009-12-12 00:32:00 +00009336static inline bool
9337CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9338 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009339 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009340 if (isa<NamespaceDecl>(DC)) {
9341 return SemaRef.Diag(FnDecl->getLocation(),
9342 diag::err_operator_new_delete_declared_in_namespace)
9343 << FnDecl->getDeclName();
9344 }
9345
9346 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009347 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009348 return SemaRef.Diag(FnDecl->getLocation(),
9349 diag::err_operator_new_delete_declared_static)
9350 << FnDecl->getDeclName();
9351 }
9352
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009353 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009354}
9355
Anders Carlsson156c78e2009-12-13 17:53:43 +00009356static inline bool
9357CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9358 CanQualType ExpectedResultType,
9359 CanQualType ExpectedFirstParamType,
9360 unsigned DependentParamTypeDiag,
9361 unsigned InvalidParamTypeDiag) {
9362 QualType ResultType =
9363 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9364
9365 // Check that the result type is not dependent.
9366 if (ResultType->isDependentType())
9367 return SemaRef.Diag(FnDecl->getLocation(),
9368 diag::err_operator_new_delete_dependent_result_type)
9369 << FnDecl->getDeclName() << ExpectedResultType;
9370
9371 // Check that the result type is what we expect.
9372 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9373 return SemaRef.Diag(FnDecl->getLocation(),
9374 diag::err_operator_new_delete_invalid_result_type)
9375 << FnDecl->getDeclName() << ExpectedResultType;
9376
9377 // A function template must have at least 2 parameters.
9378 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9379 return SemaRef.Diag(FnDecl->getLocation(),
9380 diag::err_operator_new_delete_template_too_few_parameters)
9381 << FnDecl->getDeclName();
9382
9383 // The function decl must have at least 1 parameter.
9384 if (FnDecl->getNumParams() == 0)
9385 return SemaRef.Diag(FnDecl->getLocation(),
9386 diag::err_operator_new_delete_too_few_parameters)
9387 << FnDecl->getDeclName();
9388
9389 // Check the the first parameter type is not dependent.
9390 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9391 if (FirstParamType->isDependentType())
9392 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9393 << FnDecl->getDeclName() << ExpectedFirstParamType;
9394
9395 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009396 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009397 ExpectedFirstParamType)
9398 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9399 << FnDecl->getDeclName() << ExpectedFirstParamType;
9400
9401 return false;
9402}
9403
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009404static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009405CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009406 // C++ [basic.stc.dynamic.allocation]p1:
9407 // A program is ill-formed if an allocation function is declared in a
9408 // namespace scope other than global scope or declared static in global
9409 // scope.
9410 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9411 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009412
9413 CanQualType SizeTy =
9414 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9415
9416 // C++ [basic.stc.dynamic.allocation]p1:
9417 // The return type shall be void*. The first parameter shall have type
9418 // std::size_t.
9419 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9420 SizeTy,
9421 diag::err_operator_new_dependent_param_type,
9422 diag::err_operator_new_param_type))
9423 return true;
9424
9425 // C++ [basic.stc.dynamic.allocation]p1:
9426 // The first parameter shall not have an associated default argument.
9427 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009428 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009429 diag::err_operator_new_default_arg)
9430 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9431
9432 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009433}
9434
9435static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009436CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9437 // C++ [basic.stc.dynamic.deallocation]p1:
9438 // A program is ill-formed if deallocation functions are declared in a
9439 // namespace scope other than global scope or declared static in global
9440 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009441 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9442 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009443
9444 // C++ [basic.stc.dynamic.deallocation]p2:
9445 // Each deallocation function shall return void and its first parameter
9446 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009447 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9448 SemaRef.Context.VoidPtrTy,
9449 diag::err_operator_delete_dependent_param_type,
9450 diag::err_operator_delete_param_type))
9451 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009452
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009453 return false;
9454}
9455
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009456/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9457/// of this overloaded operator is well-formed. If so, returns false;
9458/// otherwise, emits appropriate diagnostics and returns true.
9459bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009460 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009461 "Expected an overloaded operator declaration");
9462
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009463 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9464
Mike Stump1eb44332009-09-09 15:08:12 +00009465 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009466 // The allocation and deallocation functions, operator new,
9467 // operator new[], operator delete and operator delete[], are
9468 // described completely in 3.7.3. The attributes and restrictions
9469 // found in the rest of this subclause do not apply to them unless
9470 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009471 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009472 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009473
Anders Carlssona3ccda52009-12-12 00:26:23 +00009474 if (Op == OO_New || Op == OO_Array_New)
9475 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009476
9477 // C++ [over.oper]p6:
9478 // An operator function shall either be a non-static member
9479 // function or be a non-member function and have at least one
9480 // parameter whose type is a class, a reference to a class, an
9481 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009482 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9483 if (MethodDecl->isStatic())
9484 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009485 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009486 } else {
9487 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009488 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9489 ParamEnd = FnDecl->param_end();
9490 Param != ParamEnd; ++Param) {
9491 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009492 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9493 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009494 ClassOrEnumParam = true;
9495 break;
9496 }
9497 }
9498
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009499 if (!ClassOrEnumParam)
9500 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009501 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009502 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009503 }
9504
9505 // C++ [over.oper]p8:
9506 // An operator function cannot have default arguments (8.3.6),
9507 // except where explicitly stated below.
9508 //
Mike Stump1eb44332009-09-09 15:08:12 +00009509 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009510 // (C++ [over.call]p1).
9511 if (Op != OO_Call) {
9512 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9513 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009514 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009515 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009516 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009517 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009518 }
9519 }
9520
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009521 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9522 { false, false, false }
9523#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9524 , { Unary, Binary, MemberOnly }
9525#include "clang/Basic/OperatorKinds.def"
9526 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009527
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009528 bool CanBeUnaryOperator = OperatorUses[Op][0];
9529 bool CanBeBinaryOperator = OperatorUses[Op][1];
9530 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009531
9532 // C++ [over.oper]p8:
9533 // [...] Operator functions cannot have more or fewer parameters
9534 // than the number required for the corresponding operator, as
9535 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009536 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009537 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009538 if (Op != OO_Call &&
9539 ((NumParams == 1 && !CanBeUnaryOperator) ||
9540 (NumParams == 2 && !CanBeBinaryOperator) ||
9541 (NumParams < 1) || (NumParams > 2))) {
9542 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009543 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009544 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009545 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009546 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009547 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009548 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009549 assert(CanBeBinaryOperator &&
9550 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009551 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009552 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009553
Chris Lattner416e46f2008-11-21 07:57:12 +00009554 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009555 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009556 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009557
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009558 // Overloaded operators other than operator() cannot be variadic.
9559 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009560 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009561 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009562 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009563 }
9564
9565 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009566 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9567 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009568 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009569 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009570 }
9571
9572 // C++ [over.inc]p1:
9573 // The user-defined function called operator++ implements the
9574 // prefix and postfix ++ operator. If this function is a member
9575 // function with no parameters, or a non-member function with one
9576 // parameter of class or enumeration type, it defines the prefix
9577 // increment operator ++ for objects of that type. If the function
9578 // is a member function with one parameter (which shall be of type
9579 // int) or a non-member function with two parameters (the second
9580 // of which shall be of type int), it defines the postfix
9581 // increment operator ++ for objects of that type.
9582 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9583 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9584 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009585 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009586 ParamIsInt = BT->getKind() == BuiltinType::Int;
9587
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009588 if (!ParamIsInt)
9589 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009590 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009591 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009592 }
9593
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009594 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009595}
Chris Lattner5a003a42008-12-17 07:09:26 +00009596
Sean Hunta6c058d2010-01-13 09:01:02 +00009597/// CheckLiteralOperatorDeclaration - Check whether the declaration
9598/// of this literal operator function is well-formed. If so, returns
9599/// false; otherwise, emits appropriate diagnostics and returns true.
9600bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9601 DeclContext *DC = FnDecl->getDeclContext();
9602 Decl::Kind Kind = DC->getDeclKind();
9603 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9604 Kind != Decl::LinkageSpec) {
9605 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9606 << FnDecl->getDeclName();
9607 return true;
9608 }
9609
9610 bool Valid = false;
9611
Sean Hunt216c2782010-04-07 23:11:06 +00009612 // template <char...> type operator "" name() is the only valid template
9613 // signature, and the only valid signature with no parameters.
9614 if (FnDecl->param_size() == 0) {
9615 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9616 // Must have only one template parameter
9617 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9618 if (Params->size() == 1) {
9619 NonTypeTemplateParmDecl *PmDecl =
9620 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009621
Sean Hunt216c2782010-04-07 23:11:06 +00009622 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009623 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9624 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9625 Valid = true;
9626 }
9627 }
9628 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009629 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009630 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9631
Sean Hunta6c058d2010-01-13 09:01:02 +00009632 QualType T = (*Param)->getType();
9633
Sean Hunt30019c02010-04-07 22:57:35 +00009634 // unsigned long long int, long double, and any character type are allowed
9635 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009636 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9637 Context.hasSameType(T, Context.LongDoubleTy) ||
9638 Context.hasSameType(T, Context.CharTy) ||
9639 Context.hasSameType(T, Context.WCharTy) ||
9640 Context.hasSameType(T, Context.Char16Ty) ||
9641 Context.hasSameType(T, Context.Char32Ty)) {
9642 if (++Param == FnDecl->param_end())
9643 Valid = true;
9644 goto FinishedParams;
9645 }
9646
Sean Hunt30019c02010-04-07 22:57:35 +00009647 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009648 const PointerType *PT = T->getAs<PointerType>();
9649 if (!PT)
9650 goto FinishedParams;
9651 T = PT->getPointeeType();
9652 if (!T.isConstQualified())
9653 goto FinishedParams;
9654 T = T.getUnqualifiedType();
9655
9656 // Move on to the second parameter;
9657 ++Param;
9658
9659 // If there is no second parameter, the first must be a const char *
9660 if (Param == FnDecl->param_end()) {
9661 if (Context.hasSameType(T, Context.CharTy))
9662 Valid = true;
9663 goto FinishedParams;
9664 }
9665
9666 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9667 // are allowed as the first parameter to a two-parameter function
9668 if (!(Context.hasSameType(T, Context.CharTy) ||
9669 Context.hasSameType(T, Context.WCharTy) ||
9670 Context.hasSameType(T, Context.Char16Ty) ||
9671 Context.hasSameType(T, Context.Char32Ty)))
9672 goto FinishedParams;
9673
9674 // The second and final parameter must be an std::size_t
9675 T = (*Param)->getType().getUnqualifiedType();
9676 if (Context.hasSameType(T, Context.getSizeType()) &&
9677 ++Param == FnDecl->param_end())
9678 Valid = true;
9679 }
9680
9681 // FIXME: This diagnostic is absolutely terrible.
9682FinishedParams:
9683 if (!Valid) {
9684 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9685 << FnDecl->getDeclName();
9686 return true;
9687 }
9688
Douglas Gregor1155c422011-08-30 22:40:35 +00009689 StringRef LiteralName
9690 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9691 if (LiteralName[0] != '_') {
9692 // C++0x [usrlit.suffix]p1:
9693 // Literal suffix identifiers that do not start with an underscore are
9694 // reserved for future standardization.
9695 bool IsHexFloat = true;
9696 if (LiteralName.size() > 1 &&
9697 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9698 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9699 if (!isdigit(LiteralName[I])) {
9700 IsHexFloat = false;
9701 break;
9702 }
9703 }
9704 }
9705
9706 if (IsHexFloat)
9707 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9708 << LiteralName;
9709 else
9710 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9711 }
9712
Sean Hunta6c058d2010-01-13 09:01:02 +00009713 return false;
9714}
9715
Douglas Gregor074149e2009-01-05 19:45:36 +00009716/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9717/// linkage specification, including the language and (if present)
9718/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9719/// the location of the language string literal, which is provided
9720/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9721/// the '{' brace. Otherwise, this linkage specification does not
9722/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009723Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9724 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009725 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009726 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009727 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009728 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009729 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009730 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009731 Language = LinkageSpecDecl::lang_cxx;
9732 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009733 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009734 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009735 }
Mike Stump1eb44332009-09-09 15:08:12 +00009736
Chris Lattnercc98eac2008-12-17 07:13:27 +00009737 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009738
Douglas Gregor074149e2009-01-05 19:45:36 +00009739 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009740 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009741 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009742 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009743 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009744}
9745
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009746/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009747/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9748/// valid, it's the position of the closing '}' brace in a linkage
9749/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009750Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009751 Decl *LinkageSpec,
9752 SourceLocation RBraceLoc) {
9753 if (LinkageSpec) {
9754 if (RBraceLoc.isValid()) {
9755 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9756 LSDecl->setRBraceLoc(RBraceLoc);
9757 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009758 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009759 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009760 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009761}
9762
Douglas Gregord308e622009-05-18 20:51:54 +00009763/// \brief Perform semantic analysis for the variable declaration that
9764/// occurs within a C++ catch clause, returning the newly-created
9765/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009766VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009767 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009768 SourceLocation StartLoc,
9769 SourceLocation Loc,
9770 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009771 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009772 QualType ExDeclType = TInfo->getType();
9773
Sebastian Redl4b07b292008-12-22 19:15:10 +00009774 // Arrays and functions decay.
9775 if (ExDeclType->isArrayType())
9776 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9777 else if (ExDeclType->isFunctionType())
9778 ExDeclType = Context.getPointerType(ExDeclType);
9779
9780 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9781 // The exception-declaration shall not denote a pointer or reference to an
9782 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009783 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009784 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009785 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009786 Invalid = true;
9787 }
Douglas Gregord308e622009-05-18 20:51:54 +00009788
Sebastian Redl4b07b292008-12-22 19:15:10 +00009789 QualType BaseType = ExDeclType;
9790 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009791 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009792 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009793 BaseType = Ptr->getPointeeType();
9794 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009795 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009796 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009797 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009798 BaseType = Ref->getPointeeType();
9799 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009800 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009801 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009802 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009803 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009804 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009805
Mike Stump1eb44332009-09-09 15:08:12 +00009806 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009807 RequireNonAbstractType(Loc, ExDeclType,
9808 diag::err_abstract_type_in_decl,
9809 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009810 Invalid = true;
9811
John McCall5a180392010-07-24 00:37:23 +00009812 // Only the non-fragile NeXT runtime currently supports C++ catches
9813 // of ObjC types, and no runtime supports catching ObjC types by value.
9814 if (!Invalid && getLangOptions().ObjC1) {
9815 QualType T = ExDeclType;
9816 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9817 T = RT->getPointeeType();
9818
9819 if (T->isObjCObjectType()) {
9820 Diag(Loc, diag::err_objc_object_catch);
9821 Invalid = true;
9822 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009823 if (!getLangOptions().ObjCNonFragileABI)
9824 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009825 }
9826 }
9827
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009828 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9829 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009830 ExDecl->setExceptionVariable(true);
9831
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009832 // In ARC, infer 'retaining' for variables of retainable type.
9833 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9834 Invalid = true;
9835
Douglas Gregorc41b8782011-07-06 18:14:43 +00009836 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009837 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009838 // C++ [except.handle]p16:
9839 // The object declared in an exception-declaration or, if the
9840 // exception-declaration does not specify a name, a temporary (12.2) is
9841 // copy-initialized (8.5) from the exception object. [...]
9842 // The object is destroyed when the handler exits, after the destruction
9843 // of any automatic objects initialized within the handler.
9844 //
9845 // We just pretend to initialize the object with itself, then make sure
9846 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009847 QualType initType = ExDeclType;
9848
9849 InitializedEntity entity =
9850 InitializedEntity::InitializeVariable(ExDecl);
9851 InitializationKind initKind =
9852 InitializationKind::CreateCopy(Loc, SourceLocation());
9853
9854 Expr *opaqueValue =
9855 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9856 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9857 ExprResult result = sequence.Perform(*this, entity, initKind,
9858 MultiExprArg(&opaqueValue, 1));
9859 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009860 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009861 else {
9862 // If the constructor used was non-trivial, set this as the
9863 // "initializer".
9864 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9865 if (!construct->getConstructor()->isTrivial()) {
9866 Expr *init = MaybeCreateExprWithCleanups(construct);
9867 ExDecl->setInit(init);
9868 }
9869
9870 // And make sure it's destructable.
9871 FinalizeVarWithDestructor(ExDecl, recordType);
9872 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009873 }
9874 }
9875
Douglas Gregord308e622009-05-18 20:51:54 +00009876 if (Invalid)
9877 ExDecl->setInvalidDecl();
9878
9879 return ExDecl;
9880}
9881
9882/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9883/// handler.
John McCalld226f652010-08-21 09:40:31 +00009884Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009885 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009886 bool Invalid = D.isInvalidType();
9887
9888 // Check for unexpanded parameter packs.
9889 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9890 UPPC_ExceptionType)) {
9891 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9892 D.getIdentifierLoc());
9893 Invalid = true;
9894 }
9895
Sebastian Redl4b07b292008-12-22 19:15:10 +00009896 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009897 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009898 LookupOrdinaryName,
9899 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009900 // The scope should be freshly made just for us. There is just no way
9901 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009902 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009903 if (PrevDecl->isTemplateParameter()) {
9904 // Maybe we will complain about the shadowed template parameter.
9905 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009906 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009907 }
9908 }
9909
Chris Lattnereaaebc72009-04-25 08:06:05 +00009910 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009911 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9912 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009913 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009914 }
9915
Douglas Gregor83cb9422010-09-09 17:09:21 +00009916 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009917 D.getSourceRange().getBegin(),
9918 D.getIdentifierLoc(),
9919 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009920 if (Invalid)
9921 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009922
Sebastian Redl4b07b292008-12-22 19:15:10 +00009923 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009924 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009925 PushOnScopeChains(ExDecl, S);
9926 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009927 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009928
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009929 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009930 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009931}
Anders Carlssonfb311762009-03-14 00:25:26 +00009932
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009933Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009934 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009935 Expr *AssertMessageExpr_,
9936 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009937 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009938
Anders Carlssonc3082412009-03-14 00:33:21 +00009939 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009940 // In a static_assert-declaration, the constant-expression shall be a
9941 // constant expression that can be contextually converted to bool.
9942 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9943 if (Converted.isInvalid())
9944 return 0;
9945
Richard Smithdaaefc52011-12-14 23:32:26 +00009946 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009947 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9948 PDiag(diag::err_static_assert_expression_is_not_constant),
9949 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009950 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009951
Richard Smithdaaefc52011-12-14 23:32:26 +00009952 if (!Cond)
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009953 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009954 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009955 }
Mike Stump1eb44332009-09-09 15:08:12 +00009956
Douglas Gregor399ad972010-12-15 23:55:21 +00009957 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9958 return 0;
9959
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009960 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9961 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009962
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009963 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009964 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009965}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009966
Douglas Gregor1d869352010-04-07 16:53:43 +00009967/// \brief Perform semantic analysis of the given friend type declaration.
9968///
9969/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009970FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9971 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009972 TypeSourceInfo *TSInfo) {
9973 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9974
9975 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009976 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009977
Richard Smith6b130222011-10-18 21:39:00 +00009978 // C++03 [class.friend]p2:
9979 // An elaborated-type-specifier shall be used in a friend declaration
9980 // for a class.*
9981 //
9982 // * The class-key of the elaborated-type-specifier is required.
9983 if (!ActiveTemplateInstantiations.empty()) {
9984 // Do not complain about the form of friend template types during
9985 // template instantiation; we will already have complained when the
9986 // template was declared.
9987 } else if (!T->isElaboratedTypeSpecifier()) {
9988 // If we evaluated the type to a record type, suggest putting
9989 // a tag in front.
9990 if (const RecordType *RT = T->getAs<RecordType>()) {
9991 RecordDecl *RD = RT->getDecl();
9992
9993 std::string InsertionText = std::string(" ") + RD->getKindName();
9994
9995 Diag(TypeRange.getBegin(),
9996 getLangOptions().CPlusPlus0x ?
9997 diag::warn_cxx98_compat_unelaborated_friend_type :
9998 diag::ext_unelaborated_friend_type)
9999 << (unsigned) RD->getTagKind()
10000 << T
10001 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10002 InsertionText);
10003 } else {
10004 Diag(FriendLoc,
10005 getLangOptions().CPlusPlus0x ?
10006 diag::warn_cxx98_compat_nonclass_type_friend :
10007 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010008 << T
Douglas Gregor1d869352010-04-07 16:53:43 +000010009 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +000010010 }
Richard Smith6b130222011-10-18 21:39:00 +000010011 } else if (T->getAs<EnumType>()) {
10012 Diag(FriendLoc,
10013 getLangOptions().CPlusPlus0x ?
10014 diag::warn_cxx98_compat_enum_friend :
10015 diag::ext_enum_friend)
10016 << T
10017 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +000010018 }
10019
Douglas Gregor06245bf2010-04-07 17:57:12 +000010020 // C++0x [class.friend]p3:
10021 // If the type specifier in a friend declaration designates a (possibly
10022 // cv-qualified) class type, that class is declared as a friend; otherwise,
10023 // the friend declaration is ignored.
10024
10025 // FIXME: C++0x has some syntactic restrictions on friend type declarations
10026 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +000010027
Abramo Bagnara0216df82011-10-29 20:52:52 +000010028 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010029}
10030
John McCall9a34edb2010-10-19 01:40:49 +000010031/// Handle a friend tag declaration where the scope specifier was
10032/// templated.
10033Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10034 unsigned TagSpec, SourceLocation TagLoc,
10035 CXXScopeSpec &SS,
10036 IdentifierInfo *Name, SourceLocation NameLoc,
10037 AttributeList *Attr,
10038 MultiTemplateParamsArg TempParamLists) {
10039 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10040
10041 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010042 bool Invalid = false;
10043
10044 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010045 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +000010046 TempParamLists.get(),
10047 TempParamLists.size(),
10048 /*friend*/ true,
10049 isExplicitSpecialization,
10050 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010051 if (TemplateParams->size() > 0) {
10052 // This is a declaration of a class template.
10053 if (Invalid)
10054 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010055
Eric Christopher4110e132011-07-21 05:34:24 +000010056 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10057 SS, Name, NameLoc, Attr,
10058 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010059 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010060 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010061 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010062 } else {
10063 // The "template<>" header is extraneous.
10064 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10065 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10066 isExplicitSpecialization = true;
10067 }
10068 }
10069
10070 if (Invalid) return 0;
10071
John McCall9a34edb2010-10-19 01:40:49 +000010072 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010073 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +000010074 if (TempParamLists.get()[I]->size()) {
10075 isAllExplicitSpecializations = false;
10076 break;
10077 }
10078 }
10079
10080 // FIXME: don't ignore attributes.
10081
10082 // If it's explicit specializations all the way down, just forget
10083 // about the template header and build an appropriate non-templated
10084 // friend. TODO: for source fidelity, remember the headers.
10085 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010086 if (SS.isEmpty()) {
10087 bool Owned = false;
10088 bool IsDependent = false;
10089 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10090 Attr, AS_public,
10091 /*ModulePrivateLoc=*/SourceLocation(),
10092 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010093 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010094 /*ScopedEnumUsesClassTag=*/false,
10095 /*UnderlyingType=*/TypeResult());
10096 }
10097
Douglas Gregor2494dd02011-03-01 01:34:45 +000010098 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010099 ElaboratedTypeKeyword Keyword
10100 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010101 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010102 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010103 if (T.isNull())
10104 return 0;
10105
10106 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10107 if (isa<DependentNameType>(T)) {
10108 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010109 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010110 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010111 TL.setNameLoc(NameLoc);
10112 } else {
10113 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010114 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010115 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010116 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10117 }
10118
10119 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10120 TSI, FriendLoc);
10121 Friend->setAccess(AS_public);
10122 CurContext->addDecl(Friend);
10123 return Friend;
10124 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010125
10126 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10127
10128
John McCall9a34edb2010-10-19 01:40:49 +000010129
10130 // Handle the case of a templated-scope friend class. e.g.
10131 // template <class T> class A<T>::B;
10132 // FIXME: we don't support these right now.
10133 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10134 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10135 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10136 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010137 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010138 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010139 TL.setNameLoc(NameLoc);
10140
10141 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10142 TSI, FriendLoc);
10143 Friend->setAccess(AS_public);
10144 Friend->setUnsupportedFriend(true);
10145 CurContext->addDecl(Friend);
10146 return Friend;
10147}
10148
10149
John McCalldd4a3b02009-09-16 22:47:08 +000010150/// Handle a friend type declaration. This works in tandem with
10151/// ActOnTag.
10152///
10153/// Notes on friend class templates:
10154///
10155/// We generally treat friend class declarations as if they were
10156/// declaring a class. So, for example, the elaborated type specifier
10157/// in a friend declaration is required to obey the restrictions of a
10158/// class-head (i.e. no typedefs in the scope chain), template
10159/// parameters are required to match up with simple template-ids, &c.
10160/// However, unlike when declaring a template specialization, it's
10161/// okay to refer to a template specialization without an empty
10162/// template parameter declaration, e.g.
10163/// friend class A<T>::B<unsigned>;
10164/// We permit this as a special case; if there are any template
10165/// parameters present at all, require proper matching, i.e.
10166/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010167Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010168 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +000010169 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +000010170
10171 assert(DS.isFriendSpecified());
10172 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10173
John McCalldd4a3b02009-09-16 22:47:08 +000010174 // Try to convert the decl specifier to a type. This works for
10175 // friend templates because ActOnTag never produces a ClassTemplateDecl
10176 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010177 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010178 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10179 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010180 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010181 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010182
Douglas Gregor6ccab972010-12-16 01:14:37 +000010183 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10184 return 0;
10185
John McCalldd4a3b02009-09-16 22:47:08 +000010186 // This is definitely an error in C++98. It's probably meant to
10187 // be forbidden in C++0x, too, but the specification is just
10188 // poorly written.
10189 //
10190 // The problem is with declarations like the following:
10191 // template <T> friend A<T>::foo;
10192 // where deciding whether a class C is a friend or not now hinges
10193 // on whether there exists an instantiation of A that causes
10194 // 'foo' to equal C. There are restrictions on class-heads
10195 // (which we declare (by fiat) elaborated friend declarations to
10196 // be) that makes this tractable.
10197 //
10198 // FIXME: handle "template <> friend class A<T>;", which
10199 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010200 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010201 Diag(Loc, diag::err_tagless_friend_type_template)
10202 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010203 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010204 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010205
John McCall02cace72009-08-28 07:59:38 +000010206 // C++98 [class.friend]p1: A friend of a class is a function
10207 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010208 // This is fixed in DR77, which just barely didn't make the C++03
10209 // deadline. It's also a very silly restriction that seriously
10210 // affects inner classes and which nobody else seems to implement;
10211 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010212 //
10213 // But note that we could warn about it: it's always useless to
10214 // friend one of your own members (it's not, however, worthless to
10215 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010216
John McCalldd4a3b02009-09-16 22:47:08 +000010217 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010218 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010219 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010220 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010221 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010222 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010223 DS.getFriendSpecLoc());
10224 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010225 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010226
10227 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010228 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010229
John McCalldd4a3b02009-09-16 22:47:08 +000010230 D->setAccess(AS_public);
10231 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010232
John McCalld226f652010-08-21 09:40:31 +000010233 return D;
John McCall02cace72009-08-28 07:59:38 +000010234}
10235
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010236Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010237 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010238 const DeclSpec &DS = D.getDeclSpec();
10239
10240 assert(DS.isFriendSpecified());
10241 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10242
10243 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010244 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010245
10246 // C++ [class.friend]p1
10247 // A friend of a class is a function or class....
10248 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010249 // It *doesn't* see through dependent types, which is correct
10250 // according to [temp.arg.type]p3:
10251 // If a declaration acquires a function type through a
10252 // type dependent on a template-parameter and this causes
10253 // a declaration that does not use the syntactic form of a
10254 // function declarator to have a function type, the program
10255 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010256 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010257 Diag(Loc, diag::err_unexpected_friend);
10258
10259 // It might be worthwhile to try to recover by creating an
10260 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010261 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010262 }
10263
10264 // C++ [namespace.memdef]p3
10265 // - If a friend declaration in a non-local class first declares a
10266 // class or function, the friend class or function is a member
10267 // of the innermost enclosing namespace.
10268 // - The name of the friend is not found by simple name lookup
10269 // until a matching declaration is provided in that namespace
10270 // scope (either before or after the class declaration granting
10271 // friendship).
10272 // - If a friend function is called, its name may be found by the
10273 // name lookup that considers functions from namespaces and
10274 // classes associated with the types of the function arguments.
10275 // - When looking for a prior declaration of a class or a function
10276 // declared as a friend, scopes outside the innermost enclosing
10277 // namespace scope are not considered.
10278
John McCall337ec3d2010-10-12 23:13:28 +000010279 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010280 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10281 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010282 assert(Name);
10283
Douglas Gregor6ccab972010-12-16 01:14:37 +000010284 // Check for unexpanded parameter packs.
10285 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10286 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10287 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10288 return 0;
10289
John McCall67d1a672009-08-06 02:15:43 +000010290 // The context we found the declaration in, or in which we should
10291 // create the declaration.
10292 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010293 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010294 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010295 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010296
John McCall337ec3d2010-10-12 23:13:28 +000010297 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010298
John McCall337ec3d2010-10-12 23:13:28 +000010299 // There are four cases here.
10300 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010301 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010302 // there as appropriate.
10303 // Recover from invalid scope qualifiers as if they just weren't there.
10304 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010305 // C++0x [namespace.memdef]p3:
10306 // If the name in a friend declaration is neither qualified nor
10307 // a template-id and the declaration is a function or an
10308 // elaborated-type-specifier, the lookup to determine whether
10309 // the entity has been previously declared shall not consider
10310 // any scopes outside the innermost enclosing namespace.
10311 // C++0x [class.friend]p11:
10312 // If a friend declaration appears in a local class and the name
10313 // specified is an unqualified name, a prior declaration is
10314 // looked up without considering scopes that are outside the
10315 // innermost enclosing non-class scope. For a friend function
10316 // declaration, if there is no prior declaration, the program is
10317 // ill-formed.
10318 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010319 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010320
John McCall29ae6e52010-10-13 05:45:15 +000010321 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010322 DC = CurContext;
10323 while (true) {
10324 // Skip class contexts. If someone can cite chapter and verse
10325 // for this behavior, that would be nice --- it's what GCC and
10326 // EDG do, and it seems like a reasonable intent, but the spec
10327 // really only says that checks for unqualified existing
10328 // declarations should stop at the nearest enclosing namespace,
10329 // not that they should only consider the nearest enclosing
10330 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010331 while (DC->isRecord())
10332 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010333
John McCall68263142009-11-18 22:49:29 +000010334 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010335
10336 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010337 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010338 break;
John McCall29ae6e52010-10-13 05:45:15 +000010339
John McCall8a407372010-10-14 22:22:28 +000010340 if (isTemplateId) {
10341 if (isa<TranslationUnitDecl>(DC)) break;
10342 } else {
10343 if (DC->isFileContext()) break;
10344 }
John McCall67d1a672009-08-06 02:15:43 +000010345 DC = DC->getParent();
10346 }
10347
10348 // C++ [class.friend]p1: A friend of a class is a function or
10349 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010350 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010351 // Most C++ 98 compilers do seem to give an error here, so
10352 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010353 if (!Previous.empty() && DC->Equals(CurContext))
10354 Diag(DS.getFriendSpecLoc(),
10355 getLangOptions().CPlusPlus0x ?
10356 diag::warn_cxx98_compat_friend_is_member :
10357 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010358
John McCall380aaa42010-10-13 06:22:15 +000010359 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010360
Douglas Gregor883af832011-10-10 01:11:59 +000010361 // C++ [class.friend]p6:
10362 // A function can be defined in a friend declaration of a class if and
10363 // only if the class is a non-local class (9.8), the function name is
10364 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010365 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010366 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10367 }
10368
John McCall337ec3d2010-10-12 23:13:28 +000010369 // - There's a non-dependent scope specifier, in which case we
10370 // compute it and do a previous lookup there for a function
10371 // or function template.
10372 } else if (!SS.getScopeRep()->isDependent()) {
10373 DC = computeDeclContext(SS);
10374 if (!DC) return 0;
10375
10376 if (RequireCompleteDeclContext(SS, DC)) return 0;
10377
10378 LookupQualifiedName(Previous, DC);
10379
10380 // Ignore things found implicitly in the wrong scope.
10381 // TODO: better diagnostics for this case. Suggesting the right
10382 // qualified scope would be nice...
10383 LookupResult::Filter F = Previous.makeFilter();
10384 while (F.hasNext()) {
10385 NamedDecl *D = F.next();
10386 if (!DC->InEnclosingNamespaceSetOf(
10387 D->getDeclContext()->getRedeclContext()))
10388 F.erase();
10389 }
10390 F.done();
10391
10392 if (Previous.empty()) {
10393 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010394 Diag(Loc, diag::err_qualified_friend_not_found)
10395 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010396 return 0;
10397 }
10398
10399 // C++ [class.friend]p1: A friend of a class is a function or
10400 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010401 if (DC->Equals(CurContext))
10402 Diag(DS.getFriendSpecLoc(),
10403 getLangOptions().CPlusPlus0x ?
10404 diag::warn_cxx98_compat_friend_is_member :
10405 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010406
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010407 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010408 // C++ [class.friend]p6:
10409 // A function can be defined in a friend declaration of a class if and
10410 // only if the class is a non-local class (9.8), the function name is
10411 // unqualified, and the function has namespace scope.
10412 SemaDiagnosticBuilder DB
10413 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10414
10415 DB << SS.getScopeRep();
10416 if (DC->isFileContext())
10417 DB << FixItHint::CreateRemoval(SS.getRange());
10418 SS.clear();
10419 }
John McCall337ec3d2010-10-12 23:13:28 +000010420
10421 // - There's a scope specifier that does not match any template
10422 // parameter lists, in which case we use some arbitrary context,
10423 // create a method or method template, and wait for instantiation.
10424 // - There's a scope specifier that does match some template
10425 // parameter lists, which we don't handle right now.
10426 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010427 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010428 // C++ [class.friend]p6:
10429 // A function can be defined in a friend declaration of a class if and
10430 // only if the class is a non-local class (9.8), the function name is
10431 // unqualified, and the function has namespace scope.
10432 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10433 << SS.getScopeRep();
10434 }
10435
John McCall337ec3d2010-10-12 23:13:28 +000010436 DC = CurContext;
10437 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010438 }
Douglas Gregor883af832011-10-10 01:11:59 +000010439
John McCall29ae6e52010-10-13 05:45:15 +000010440 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010441 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010442 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10443 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10444 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010445 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010446 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10447 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010448 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010449 }
John McCall67d1a672009-08-06 02:15:43 +000010450 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010451
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010452 // FIXME: This is an egregious hack to cope with cases where the scope stack
10453 // does not contain the declaration context, i.e., in an out-of-line
10454 // definition of a class.
10455 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10456 if (!DCScope) {
10457 FakeDCScope.setEntity(DC);
10458 DCScope = &FakeDCScope;
10459 }
10460
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010461 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010462 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10463 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010464 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010465
Douglas Gregor182ddf02009-09-28 00:08:27 +000010466 assert(ND->getDeclContext() == DC);
10467 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010468
John McCallab88d972009-08-31 22:39:49 +000010469 // Add the function declaration to the appropriate lookup tables,
10470 // adjusting the redeclarations list as necessary. We don't
10471 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010472 //
John McCallab88d972009-08-31 22:39:49 +000010473 // Also update the scope-based lookup if the target context's
10474 // lookup context is in lexical scope.
10475 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010476 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010477 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010478 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010479 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010480 }
John McCall02cace72009-08-28 07:59:38 +000010481
10482 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010483 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010484 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010485 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010486 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010487
John McCall337ec3d2010-10-12 23:13:28 +000010488 if (ND->isInvalidDecl())
10489 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010490 else {
10491 FunctionDecl *FD;
10492 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10493 FD = FTD->getTemplatedDecl();
10494 else
10495 FD = cast<FunctionDecl>(ND);
10496
10497 // Mark templated-scope function declarations as unsupported.
10498 if (FD->getNumTemplateParameterLists())
10499 FrD->setUnsupportedFriend(true);
10500 }
John McCall337ec3d2010-10-12 23:13:28 +000010501
John McCalld226f652010-08-21 09:40:31 +000010502 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010503}
10504
John McCalld226f652010-08-21 09:40:31 +000010505void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10506 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010507
Sebastian Redl50de12f2009-03-24 22:27:57 +000010508 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10509 if (!Fn) {
10510 Diag(DelLoc, diag::err_deleted_non_function);
10511 return;
10512 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010513 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010514 Diag(DelLoc, diag::err_deleted_decl_not_first);
10515 Diag(Prev->getLocation(), diag::note_previous_declaration);
10516 // If the declaration wasn't the first, we delete the function anyway for
10517 // recovery.
10518 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010519 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010520}
Sebastian Redl13e88542009-04-27 21:33:24 +000010521
Sean Hunte4246a62011-05-12 06:15:49 +000010522void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10523 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10524
10525 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010526 if (MD->getParent()->isDependentType()) {
10527 MD->setDefaulted();
10528 MD->setExplicitlyDefaulted();
10529 return;
10530 }
10531
Sean Hunte4246a62011-05-12 06:15:49 +000010532 CXXSpecialMember Member = getSpecialMember(MD);
10533 if (Member == CXXInvalid) {
10534 Diag(DefaultLoc, diag::err_default_special_members);
10535 return;
10536 }
10537
10538 MD->setDefaulted();
10539 MD->setExplicitlyDefaulted();
10540
Sean Huntcd10dec2011-05-23 23:14:04 +000010541 // If this definition appears within the record, do the checking when
10542 // the record is complete.
10543 const FunctionDecl *Primary = MD;
10544 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10545 // Find the uninstantiated declaration that actually had the '= default'
10546 // on it.
10547 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10548
10549 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010550 return;
10551
10552 switch (Member) {
10553 case CXXDefaultConstructor: {
10554 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10555 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010556 if (!CD->isInvalidDecl())
10557 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10558 break;
10559 }
10560
10561 case CXXCopyConstructor: {
10562 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10563 CheckExplicitlyDefaultedCopyConstructor(CD);
10564 if (!CD->isInvalidDecl())
10565 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010566 break;
10567 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010568
Sean Hunt2b188082011-05-14 05:23:28 +000010569 case CXXCopyAssignment: {
10570 CheckExplicitlyDefaultedCopyAssignment(MD);
10571 if (!MD->isInvalidDecl())
10572 DefineImplicitCopyAssignment(DefaultLoc, MD);
10573 break;
10574 }
10575
Sean Huntcb45a0f2011-05-12 22:46:25 +000010576 case CXXDestructor: {
10577 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10578 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010579 if (!DD->isInvalidDecl())
10580 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010581 break;
10582 }
10583
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010584 case CXXMoveConstructor: {
10585 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10586 CheckExplicitlyDefaultedMoveConstructor(CD);
10587 if (!CD->isInvalidDecl())
10588 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010589 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010590 }
Sean Hunt82713172011-05-25 23:16:36 +000010591
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010592 case CXXMoveAssignment: {
10593 CheckExplicitlyDefaultedMoveAssignment(MD);
10594 if (!MD->isInvalidDecl())
10595 DefineImplicitMoveAssignment(DefaultLoc, MD);
10596 break;
10597 }
10598
10599 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010600 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010601 }
10602 } else {
10603 Diag(DefaultLoc, diag::err_default_special_members);
10604 }
10605}
10606
Sebastian Redl13e88542009-04-27 21:33:24 +000010607static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010608 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010609 Stmt *SubStmt = *CI;
10610 if (!SubStmt)
10611 continue;
10612 if (isa<ReturnStmt>(SubStmt))
10613 Self.Diag(SubStmt->getSourceRange().getBegin(),
10614 diag::err_return_in_constructor_handler);
10615 if (!isa<Expr>(SubStmt))
10616 SearchForReturnInStmt(Self, SubStmt);
10617 }
10618}
10619
10620void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10621 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10622 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10623 SearchForReturnInStmt(*this, Handler);
10624 }
10625}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010626
Mike Stump1eb44332009-09-09 15:08:12 +000010627bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010628 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010629 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10630 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010631
Chandler Carruth73857792010-02-15 11:53:20 +000010632 if (Context.hasSameType(NewTy, OldTy) ||
10633 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010634 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010635
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010636 // Check if the return types are covariant
10637 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010638
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010639 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010640 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10641 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010642 NewClassTy = NewPT->getPointeeType();
10643 OldClassTy = OldPT->getPointeeType();
10644 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010645 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10646 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10647 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10648 NewClassTy = NewRT->getPointeeType();
10649 OldClassTy = OldRT->getPointeeType();
10650 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010651 }
10652 }
Mike Stump1eb44332009-09-09 15:08:12 +000010653
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010654 // The return types aren't either both pointers or references to a class type.
10655 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010656 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010657 diag::err_different_return_type_for_overriding_virtual_function)
10658 << New->getDeclName() << NewTy << OldTy;
10659 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010660
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010661 return true;
10662 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010663
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010664 // C++ [class.virtual]p6:
10665 // If the return type of D::f differs from the return type of B::f, the
10666 // class type in the return type of D::f shall be complete at the point of
10667 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010668 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10669 if (!RT->isBeingDefined() &&
10670 RequireCompleteType(New->getLocation(), NewClassTy,
10671 PDiag(diag::err_covariant_return_incomplete)
10672 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010673 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010674 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010675
Douglas Gregora4923eb2009-11-16 21:35:15 +000010676 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010677 // Check if the new class derives from the old class.
10678 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10679 Diag(New->getLocation(),
10680 diag::err_covariant_return_not_derived)
10681 << New->getDeclName() << NewTy << OldTy;
10682 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10683 return true;
10684 }
Mike Stump1eb44332009-09-09 15:08:12 +000010685
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010686 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010687 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010688 diag::err_covariant_return_inaccessible_base,
10689 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10690 // FIXME: Should this point to the return type?
10691 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010692 // FIXME: this note won't trigger for delayed access control
10693 // diagnostics, and it's impossible to get an undelayed error
10694 // here from access control during the original parse because
10695 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010696 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10697 return true;
10698 }
10699 }
Mike Stump1eb44332009-09-09 15:08:12 +000010700
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010701 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010702 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010703 Diag(New->getLocation(),
10704 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010705 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010706 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10707 return true;
10708 };
Mike Stump1eb44332009-09-09 15:08:12 +000010709
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010710
10711 // The new class type must have the same or less qualifiers as the old type.
10712 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10713 Diag(New->getLocation(),
10714 diag::err_covariant_return_type_class_type_more_qualified)
10715 << New->getDeclName() << NewTy << OldTy;
10716 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10717 return true;
10718 };
Mike Stump1eb44332009-09-09 15:08:12 +000010719
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010720 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010721}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010722
Douglas Gregor4ba31362009-12-01 17:24:26 +000010723/// \brief Mark the given method pure.
10724///
10725/// \param Method the method to be marked pure.
10726///
10727/// \param InitRange the source range that covers the "0" initializer.
10728bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010729 SourceLocation EndLoc = InitRange.getEnd();
10730 if (EndLoc.isValid())
10731 Method->setRangeEnd(EndLoc);
10732
Douglas Gregor4ba31362009-12-01 17:24:26 +000010733 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10734 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010735 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010736 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010737
10738 if (!Method->isInvalidDecl())
10739 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10740 << Method->getDeclName() << InitRange;
10741 return true;
10742}
10743
John McCall731ad842009-12-19 09:28:58 +000010744/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10745/// an initializer for the out-of-line declaration 'Dcl'. The scope
10746/// is a fresh scope pushed for just this purpose.
10747///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010748/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10749/// static data member of class X, names should be looked up in the scope of
10750/// class X.
John McCalld226f652010-08-21 09:40:31 +000010751void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010752 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010753 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010754
John McCall731ad842009-12-19 09:28:58 +000010755 // We should only get called for declarations with scope specifiers, like:
10756 // int foo::bar;
10757 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010758 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010759}
10760
10761/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010762/// initializer for the out-of-line declaration 'D'.
10763void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010764 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010765 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010766
John McCall731ad842009-12-19 09:28:58 +000010767 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010768 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010769}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010770
10771/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10772/// C++ if/switch/while/for statement.
10773/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010774DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010775 // C++ 6.4p2:
10776 // The declarator shall not specify a function or an array.
10777 // The type-specifier-seq shall not contain typedef and shall not declare a
10778 // new class or enumeration.
10779 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10780 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010781
10782 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010783 if (!Dcl)
10784 return true;
10785
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010786 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10787 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010788 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010789 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010790 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010791
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010792 return Dcl;
10793}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010794
Douglas Gregordfe65432011-07-28 19:11:31 +000010795void Sema::LoadExternalVTableUses() {
10796 if (!ExternalSource)
10797 return;
10798
10799 SmallVector<ExternalVTableUse, 4> VTables;
10800 ExternalSource->ReadUsedVTables(VTables);
10801 SmallVector<VTableUse, 4> NewUses;
10802 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10803 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10804 = VTablesUsed.find(VTables[I].Record);
10805 // Even if a definition wasn't required before, it may be required now.
10806 if (Pos != VTablesUsed.end()) {
10807 if (!Pos->second && VTables[I].DefinitionRequired)
10808 Pos->second = true;
10809 continue;
10810 }
10811
10812 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10813 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10814 }
10815
10816 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10817}
10818
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010819void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10820 bool DefinitionRequired) {
10821 // Ignore any vtable uses in unevaluated operands or for classes that do
10822 // not have a vtable.
10823 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10824 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010825 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010826 return;
10827
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010828 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010829 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010830 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10831 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10832 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10833 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010834 // If we already had an entry, check to see if we are promoting this vtable
10835 // to required a definition. If so, we need to reappend to the VTableUses
10836 // list, since we may have already processed the first entry.
10837 if (DefinitionRequired && !Pos.first->second) {
10838 Pos.first->second = true;
10839 } else {
10840 // Otherwise, we can early exit.
10841 return;
10842 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010843 }
10844
10845 // Local classes need to have their virtual members marked
10846 // immediately. For all other classes, we mark their virtual members
10847 // at the end of the translation unit.
10848 if (Class->isLocalClass())
10849 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010850 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010851 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010852}
10853
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010854bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010855 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010856 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010857 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010858
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010859 // Note: The VTableUses vector could grow as a result of marking
10860 // the members of a class as "used", so we check the size each
10861 // time through the loop and prefer indices (with are stable) to
10862 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010863 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010864 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010865 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010866 if (!Class)
10867 continue;
10868
10869 SourceLocation Loc = VTableUses[I].second;
10870
10871 // If this class has a key function, but that key function is
10872 // defined in another translation unit, we don't need to emit the
10873 // vtable even though we're using it.
10874 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010875 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010876 switch (KeyFunction->getTemplateSpecializationKind()) {
10877 case TSK_Undeclared:
10878 case TSK_ExplicitSpecialization:
10879 case TSK_ExplicitInstantiationDeclaration:
10880 // The key function is in another translation unit.
10881 continue;
10882
10883 case TSK_ExplicitInstantiationDefinition:
10884 case TSK_ImplicitInstantiation:
10885 // We will be instantiating the key function.
10886 break;
10887 }
10888 } else if (!KeyFunction) {
10889 // If we have a class with no key function that is the subject
10890 // of an explicit instantiation declaration, suppress the
10891 // vtable; it will live with the explicit instantiation
10892 // definition.
10893 bool IsExplicitInstantiationDeclaration
10894 = Class->getTemplateSpecializationKind()
10895 == TSK_ExplicitInstantiationDeclaration;
10896 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10897 REnd = Class->redecls_end();
10898 R != REnd; ++R) {
10899 TemplateSpecializationKind TSK
10900 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10901 if (TSK == TSK_ExplicitInstantiationDeclaration)
10902 IsExplicitInstantiationDeclaration = true;
10903 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10904 IsExplicitInstantiationDeclaration = false;
10905 break;
10906 }
10907 }
10908
10909 if (IsExplicitInstantiationDeclaration)
10910 continue;
10911 }
10912
10913 // Mark all of the virtual members of this class as referenced, so
10914 // that we can build a vtable. Then, tell the AST consumer that a
10915 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010916 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010917 MarkVirtualMembersReferenced(Loc, Class);
10918 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10919 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10920
10921 // Optionally warn if we're emitting a weak vtable.
10922 if (Class->getLinkage() == ExternalLinkage &&
10923 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010924 const FunctionDecl *KeyFunctionDef = 0;
10925 if (!KeyFunction ||
10926 (KeyFunction->hasBody(KeyFunctionDef) &&
10927 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010928 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10929 TSK_ExplicitInstantiationDefinition
10930 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10931 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010932 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010933 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010934 VTableUses.clear();
10935
Douglas Gregor78844032011-04-22 22:25:37 +000010936 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010937}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010938
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010939void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10940 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010941 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10942 e = RD->method_end(); i != e; ++i) {
10943 CXXMethodDecl *MD = *i;
10944
10945 // C++ [basic.def.odr]p2:
10946 // [...] A virtual member function is used if it is not pure. [...]
10947 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010948 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010949 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010950
10951 // Only classes that have virtual bases need a VTT.
10952 if (RD->getNumVBases() == 0)
10953 return;
10954
10955 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10956 e = RD->bases_end(); i != e; ++i) {
10957 const CXXRecordDecl *Base =
10958 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010959 if (Base->getNumVBases() == 0)
10960 continue;
10961 MarkVirtualMembersReferenced(Loc, Base);
10962 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010963}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010964
10965/// SetIvarInitializers - This routine builds initialization ASTs for the
10966/// Objective-C implementation whose ivars need be initialized.
10967void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10968 if (!getLangOptions().CPlusPlus)
10969 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010970 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010971 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010972 CollectIvarsToConstructOrDestruct(OID, ivars);
10973 if (ivars.empty())
10974 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010975 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010976 for (unsigned i = 0; i < ivars.size(); i++) {
10977 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010978 if (Field->isInvalidDecl())
10979 continue;
10980
Sean Huntcbb67482011-01-08 20:30:50 +000010981 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010982 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10983 InitializationKind InitKind =
10984 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10985
10986 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010987 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010988 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010989 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010990 // Note, MemberInit could actually come back empty if no initialization
10991 // is required (e.g., because it would call a trivial default constructor)
10992 if (!MemberInit.get() || MemberInit.isInvalid())
10993 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010994
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010995 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010996 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10997 SourceLocation(),
10998 MemberInit.takeAs<Expr>(),
10999 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011000 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011001
11002 // Be sure that the destructor is accessible and is marked as referenced.
11003 if (const RecordType *RecordTy
11004 = Context.getBaseElementType(Field->getType())
11005 ->getAs<RecordType>()) {
11006 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011007 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011008 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011009 CheckDestructorAccess(Field->getLocation(), Destructor,
11010 PDiag(diag::err_access_dtor_ivar)
11011 << Context.getBaseElementType(Field->getType()));
11012 }
11013 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011014 }
11015 ObjCImplementation->setIvarInitializers(Context,
11016 AllToInit.data(), AllToInit.size());
11017 }
11018}
Sean Huntfe57eef2011-05-04 05:57:24 +000011019
Sean Huntebcbe1d2011-05-04 23:29:54 +000011020static
11021void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11022 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11023 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11024 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11025 Sema &S) {
11026 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11027 CE = Current.end();
11028 if (Ctor->isInvalidDecl())
11029 return;
11030
11031 const FunctionDecl *FNTarget = 0;
11032 CXXConstructorDecl *Target;
11033
11034 // We ignore the result here since if we don't have a body, Target will be
11035 // null below.
11036 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
11037 Target
11038= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
11039
11040 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11041 // Avoid dereferencing a null pointer here.
11042 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11043
11044 if (!Current.insert(Canonical))
11045 return;
11046
11047 // We know that beyond here, we aren't chaining into a cycle.
11048 if (!Target || !Target->isDelegatingConstructor() ||
11049 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11050 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11051 Valid.insert(*CI);
11052 Current.clear();
11053 // We've hit a cycle.
11054 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11055 Current.count(TCanonical)) {
11056 // If we haven't diagnosed this cycle yet, do so now.
11057 if (!Invalid.count(TCanonical)) {
11058 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011059 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011060 << Ctor;
11061
11062 // Don't add a note for a function delegating directo to itself.
11063 if (TCanonical != Canonical)
11064 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11065
11066 CXXConstructorDecl *C = Target;
11067 while (C->getCanonicalDecl() != Canonical) {
11068 (void)C->getTargetConstructor()->hasBody(FNTarget);
11069 assert(FNTarget && "Ctor cycle through bodiless function");
11070
11071 C
11072 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11073 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11074 }
11075 }
11076
11077 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11078 Invalid.insert(*CI);
11079 Current.clear();
11080 } else {
11081 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11082 }
11083}
11084
11085
Sean Huntfe57eef2011-05-04 05:57:24 +000011086void Sema::CheckDelegatingCtorCycles() {
11087 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11088
Sean Huntebcbe1d2011-05-04 23:29:54 +000011089 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11090 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011091
Douglas Gregor0129b562011-07-27 21:57:17 +000011092 for (DelegatingCtorDeclsType::iterator
11093 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011094 E = DelegatingCtorDecls.end();
11095 I != E; ++I) {
11096 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000011097 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011098
11099 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11100 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011101}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011102
11103/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11104Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11105 // Implicitly declared functions (e.g. copy constructors) are
11106 // __host__ __device__
11107 if (D->isImplicit())
11108 return CFT_HostDevice;
11109
11110 if (D->hasAttr<CUDAGlobalAttr>())
11111 return CFT_Global;
11112
11113 if (D->hasAttr<CUDADeviceAttr>()) {
11114 if (D->hasAttr<CUDAHostAttr>())
11115 return CFT_HostDevice;
11116 else
11117 return CFT_Device;
11118 }
11119
11120 return CFT_Host;
11121}
11122
11123bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11124 CUDAFunctionTarget CalleeTarget) {
11125 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11126 // Callable from the device only."
11127 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11128 return true;
11129
11130 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11131 // Callable from the host only."
11132 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11133 // Callable from the host only."
11134 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11135 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11136 return true;
11137
11138 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11139 return true;
11140
11141 return false;
11142}