blob: f9787e85c46bf53923356cb3b8db170cfa7a713b [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"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000036#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000037#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner8123a952008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattner9e979552008-04-12 23:52:44 +000045namespace {
46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47 /// the default argument of a parameter to determine whether it
48 /// contains any ill-formed subexpressions. For example, this will
49 /// diagnose the use of local variables or parameters within the
50 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000055
Chris Lattner9e979552008-04-12 23:52:44 +000056 public:
Mike Stump1eb44332009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000063 };
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 /// VisitExpr - Visit all of the children of this expression.
66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000071 }
72
Chris Lattner9e979552008-04-12 23:52:44 +000073 /// VisitDeclRefExpr - Visit a reference to a declaration, to
74 /// determine whether this declaration can be used in the default
75 /// argument expression.
76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000078 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79 // C++ [dcl.fct.default]p9
80 // Default arguments are evaluated each time the function is
81 // called. The order of evaluation of function arguments is
82 // unspecified. Consequently, parameters of a function shall not
83 // be used in default argument expressions, even if they are not
84 // evaluated. Parameters of a function declared before a default
85 // argument expression are in scope and can hide namespace and
86 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000098 }
Chris Lattner8123a952008-04-10 02:22:51 +000099
Douglas Gregor3996f232008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattner9e979552008-04-12 23:52:44 +0000102
Douglas Gregor796da182008-11-04 14:32:21 +0000103 /// VisitCXXThisExpr - Visit a C++ "this" expression.
104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105 // C++ [dcl.fct.default]p8:
106 // The keyword this shall not be used in a default argument of a
107 // member function.
108 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000111 }
Chris Lattner8123a952008-04-10 02:22:51 +0000112}
113
Sean Hunt001cad92011-05-10 00:49:42 +0000114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000115 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith7a614d82011-06-11 17:19:42 +0000116 // If we have an MSAny or unknown spec already, don't bother.
117 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000118 return;
119
120 const FunctionProtoType *Proto
121 = Method->getType()->getAs<FunctionProtoType>();
122
123 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
124
125 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000127 ClearExceptions();
128 ComputedEST = EST;
129 return;
130 }
131
Richard Smith7a614d82011-06-11 17:19:42 +0000132 // FIXME: If the call to this decl is using any of its default arguments, we
133 // need to search them for potentially-throwing calls.
134
Sean Hunt001cad92011-05-10 00:49:42 +0000135 // If this function has a basic noexcept, it doesn't affect the outcome.
136 if (EST == EST_BasicNoexcept)
137 return;
138
139 // If we have a throw-all spec at this point, ignore the function.
140 if (ComputedEST == EST_None)
141 return;
142
143 // If we're still at noexcept(true) and there's a nothrow() callee,
144 // change to that specification.
145 if (EST == EST_DynamicNone) {
146 if (ComputedEST == EST_BasicNoexcept)
147 ComputedEST = EST_DynamicNone;
148 return;
149 }
150
151 // Check out noexcept specs.
152 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000153 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000154 assert(NR != FunctionProtoType::NR_NoNoexcept &&
155 "Must have noexcept result for EST_ComputedNoexcept.");
156 assert(NR != FunctionProtoType::NR_Dependent &&
157 "Should not generate implicit declarations for dependent cases, "
158 "and don't know how to handle them anyway.");
159
160 // noexcept(false) -> no spec on the new function
161 if (NR == FunctionProtoType::NR_Throw) {
162 ClearExceptions();
163 ComputedEST = EST_None;
164 }
165 // noexcept(true) won't change anything either.
166 return;
167 }
168
169 assert(EST == EST_Dynamic && "EST case not considered earlier.");
170 assert(ComputedEST != EST_None &&
171 "Shouldn't collect exceptions when throw-all is guaranteed.");
172 ComputedEST = EST_Dynamic;
173 // Record the exceptions in this function's exception specification.
174 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
175 EEnd = Proto->exception_end();
176 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000178 Exceptions.push_back(*E);
179}
180
Richard Smith7a614d82011-06-11 17:19:42 +0000181void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
183 return;
184
185 // FIXME:
186 //
187 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000188 // [An] implicit exception-specification specifies the type-id T if and
189 // only if T is allowed by the exception-specification of a function directly
190 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000191 // function it directly invokes allows all exceptions, and f shall allow no
192 // exceptions if every function it directly invokes allows no exceptions.
193 //
194 // Note in particular that if an implicit exception-specification is generated
195 // for a function containing a throw-expression, that specification can still
196 // be noexcept(true).
197 //
198 // Note also that 'directly invoked' is not defined in the standard, and there
199 // is no indication that we should only consider potentially-evaluated calls.
200 //
201 // Ultimately we should implement the intent of the standard: the exception
202 // specification should be the set of exceptions which can be thrown by the
203 // implicit definition. For now, we assume that any non-nothrow expression can
204 // throw any exception.
205
206 if (E->CanThrow(*Context))
207 ComputedEST = EST_None;
208}
209
Anders Carlssoned961f92009-08-25 02:29:20 +0000210bool
John McCall9ae2f072010-08-23 23:25:46 +0000211Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000212 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000213 if (RequireCompleteType(Param->getLocation(), Param->getType(),
214 diag::err_typecheck_decl_incomplete_type)) {
215 Param->setInvalidDecl();
216 return true;
217 }
218
Anders Carlssoned961f92009-08-25 02:29:20 +0000219 // C++ [dcl.fct.default]p5
220 // A default argument expression is implicitly converted (clause
221 // 4) to the parameter type. The default argument expression has
222 // the same semantic constraints as the initializer expression in
223 // a declaration of a variable of the parameter type, using the
224 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000231 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000232 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000233 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000234 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000235
John McCallb4eb64d2010-10-08 02:01:28 +0000236 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000237 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Anders Carlssoned961f92009-08-25 02:29:20 +0000239 // Okay: add the default argument to the parameter
240 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000242 // We have already instantiated this parameter; provide each of the
243 // instantiations with the uninstantiated default argument.
244 UnparsedDefaultArgInstantiationsMap::iterator InstPos
245 = UnparsedDefaultArgInstantiations.find(Param);
246 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
247 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
248 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
249
250 // We're done tracking this parameter's instantiations.
251 UnparsedDefaultArgInstantiations.erase(InstPos);
252 }
253
Anders Carlsson9351c172009-08-25 03:18:48 +0000254 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000255}
256
Chris Lattner8123a952008-04-10 02:22:51 +0000257/// ActOnParamDefaultArgument - Check whether the default argument
258/// provided for a function parameter is well-formed. If so, attach it
259/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000260void
John McCalld226f652010-08-21 09:40:31 +0000261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000262 Expr *DefaultArg) {
263 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000264 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000265
John McCalld226f652010-08-21 09:40:31 +0000266 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000267 UnparsedDefaultArgLocs.erase(Param);
268
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 // Default arguments are only permitted in C++
270 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000271 Diag(EqualLoc, diag::err_param_default_argument)
272 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000273 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000274 return;
275 }
276
Douglas Gregor6f526752010-12-16 08:48:57 +0000277 // Check for unexpanded parameter packs.
278 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279 Param->setInvalidDecl();
280 return;
281 }
282
Anders Carlsson66e30672009-08-25 01:02:06 +0000283 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000286 Param->setInvalidDecl();
287 return;
288 }
Mike Stump1eb44332009-09-09 15:08:12 +0000289
John McCall9ae2f072010-08-23 23:25:46 +0000290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000291}
292
Douglas Gregor61366e92008-12-24 00:01:03 +0000293/// ActOnParamUnparsedDefaultArgument - We've seen a default
294/// argument for a function parameter, but we can't parse it yet
295/// because we're inside a class definition. Note that this default
296/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000298 SourceLocation EqualLoc,
299 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000300 if (!param)
301 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000302
John McCalld226f652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000304 if (Param)
305 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Anders Carlsson5e300d12009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000308}
309
Douglas Gregor72b505b2008-12-16 21:30:33 +0000310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000312void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000313 if (!param)
314 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
John McCalld226f652010-08-21 09:40:31 +0000316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Anders Carlsson5e300d12009-06-12 16:51:40 +0000318 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Anders Carlsson5e300d12009-06-12 16:51:40 +0000320 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000321}
322
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000323/// CheckExtraCXXDefaultArguments - Check for any extra default
324/// arguments in the declarator, which is not a function declaration
325/// or definition and therefore is not permitted to have default
326/// arguments. This routine should be invoked for every declarator
327/// that is not a function declaration or definition.
328void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
329 // C++ [dcl.fct.default]p3
330 // A default argument expression shall be specified only in the
331 // parameter-declaration-clause of a function declaration or in a
332 // template-parameter (14.1). It shall not be specified for a
333 // parameter pack. If it is specified in a
334 // parameter-declaration-clause, it shall not occur within a
335 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000337 DeclaratorChunk &chunk = D.getTypeObject(i);
338 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param->hasUnparsedDefaultArg()) {
343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000344 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
345 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
346 delete Toks;
347 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000348 } else if (Param->getDefaultArg()) {
349 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
350 << Param->getDefaultArg()->getSourceRange();
351 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000352 }
353 }
354 }
355 }
356}
357
Chris Lattner3d1cee32008-04-08 05:04:30 +0000358// MergeCXXFunctionDecl - Merge two declarations of the same C++
359// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000360// type. Subroutine of MergeFunctionDecl. Returns true if there was an
361// error, false otherwise.
362bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363 bool Invalid = false;
364
Chris Lattner3d1cee32008-04-08 05:04:30 +0000365 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000366 // For non-template functions, default arguments can be added in
367 // later declarations of a function in the same
368 // scope. Declarations in different scopes have completely
369 // distinct sets of default arguments. That is, declarations in
370 // inner scopes do not acquire default arguments from
371 // declarations in outer scopes, and vice versa. In a given
372 // function declaration, all parameters subsequent to a
373 // parameter with a default argument shall have default
374 // arguments supplied in this or previous declarations. A
375 // default argument shall not be redefined by a later
376 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000377 //
378 // C++ [dcl.fct.default]p6:
379 // Except for member functions of class templates, the default arguments
380 // in a member function definition that appears outside of the class
381 // definition are added to the set of default arguments provided by the
382 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000383 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
384 ParmVarDecl *OldParam = Old->getParamDecl(p);
385 ParmVarDecl *NewParam = New->getParamDecl(p);
386
Douglas Gregor6cc15182009-09-11 18:44:32 +0000387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000388
Francois Pichet8d051e02011-04-10 03:03:52 +0000389 unsigned DiagDefaultParamID =
390 diag::err_param_default_argument_redefinition;
391
392 // MSVC accepts that default parameters be redefined for member functions
393 // of template class. The new default parameter's value is ignored.
394 Invalid = true;
Francois Pichet62ec1f22011-09-17 17:15:52 +0000395 if (getLangOptions().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000396 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000398 // Merge the old default argument into the new parameter.
399 NewParam->setHasInheritedDefaultArg();
400 if (OldParam->hasUninstantiatedDefaultArg())
401 NewParam->setUninstantiatedDefaultArg(
402 OldParam->getUninstantiatedDefaultArg());
403 else
404 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000406 Invalid = false;
407 }
408 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000409
Francois Pichet8cf90492011-04-10 04:58:30 +0000410 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
411 // hint here. Alternatively, we could walk the type-source information
412 // for NewParam to find the last source location in the type... but it
413 // isn't worth the effort right now. This is the kind of test case that
414 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000415 // int f(int);
416 // void g(int (*fp)(int) = f);
417 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000419 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000420
421 // Look for the function declaration where the default argument was
422 // actually written, which may be a declaration prior to Old.
423 for (FunctionDecl *Older = Old->getPreviousDeclaration();
424 Older; Older = Older->getPreviousDeclaration()) {
425 if (!Older->getParamDecl(p)->hasDefaultArg())
426 break;
427
428 OldParam = Older->getParamDecl(p);
429 }
430
431 Diag(OldParam->getLocation(), diag::note_previous_definition)
432 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000433 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000434 // Merge the old default argument into the new parameter.
435 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000436 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000437 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000438 if (OldParam->hasUninstantiatedDefaultArg())
439 NewParam->setUninstantiatedDefaultArg(
440 OldParam->getUninstantiatedDefaultArg());
441 else
John McCall3d6c1782010-05-04 01:53:42 +0000442 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000443 } else if (NewParam->hasDefaultArg()) {
444 if (New->getDescribedFunctionTemplate()) {
445 // Paragraph 4, quoted above, only applies to non-template functions.
446 Diag(NewParam->getLocation(),
447 diag::err_param_default_argument_template_redecl)
448 << NewParam->getDefaultArgRange();
449 Diag(Old->getLocation(), diag::note_template_prev_declaration)
450 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000451 } else if (New->getTemplateSpecializationKind()
452 != TSK_ImplicitInstantiation &&
453 New->getTemplateSpecializationKind() != TSK_Undeclared) {
454 // C++ [temp.expr.spec]p21:
455 // Default function arguments shall not be specified in a declaration
456 // or a definition for one of the following explicit specializations:
457 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000458 // - the explicit specialization of a member function template;
459 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000460 // template where the class template specialization to which the
461 // member function specialization belongs is implicitly
462 // instantiated.
463 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
464 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
465 << New->getDeclName()
466 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000467 } else if (New->getDeclContext()->isDependentContext()) {
468 // C++ [dcl.fct.default]p6 (DR217):
469 // Default arguments for a member function of a class template shall
470 // be specified on the initial declaration of the member function
471 // within the class template.
472 //
473 // Reading the tea leaves a bit in DR217 and its reference to DR205
474 // leads me to the conclusion that one cannot add default function
475 // arguments for an out-of-line definition of a member function of a
476 // dependent type.
477 int WhichKind = 2;
478 if (CXXRecordDecl *Record
479 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480 if (Record->getDescribedClassTemplate())
481 WhichKind = 0;
482 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
483 WhichKind = 1;
484 else
485 WhichKind = 2;
486 }
487
488 Diag(NewParam->getLocation(),
489 diag::err_param_default_argument_member_template_redecl)
490 << WhichKind
491 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000492 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
493 CXXSpecialMember NewSM = getSpecialMember(Ctor),
494 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
495 if (NewSM != OldSM) {
496 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
497 << NewParam->getDefaultArgRange() << NewSM;
498 Diag(Old->getLocation(), diag::note_previous_declaration_special)
499 << OldSM;
500 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000501 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000502 }
503 }
504
Douglas Gregore13ad832010-02-12 07:32:17 +0000505 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000506 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000507
Douglas Gregorcda9c672009-02-16 17:45:42 +0000508 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000509}
510
Sebastian Redl60618fa2011-03-12 11:50:43 +0000511/// \brief Merge the exception specifications of two variable declarations.
512///
513/// This is called when there's a redeclaration of a VarDecl. The function
514/// checks if the redeclaration might have an exception specification and
515/// validates compatibility and merges the specs if necessary.
516void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
517 // Shortcut if exceptions are disabled.
518 if (!getLangOptions().CXXExceptions)
519 return;
520
521 assert(Context.hasSameType(New->getType(), Old->getType()) &&
522 "Should only be called if types are otherwise the same.");
523
524 QualType NewType = New->getType();
525 QualType OldType = Old->getType();
526
527 // We're only interested in pointers and references to functions, as well
528 // as pointers to member functions.
529 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
530 NewType = R->getPointeeType();
531 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
532 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
533 NewType = P->getPointeeType();
534 OldType = OldType->getAs<PointerType>()->getPointeeType();
535 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
536 NewType = M->getPointeeType();
537 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
538 }
539
540 if (!NewType->isFunctionProtoType())
541 return;
542
543 // There's lots of special cases for functions. For function pointers, system
544 // libraries are hopefully not as broken so that we don't need these
545 // workarounds.
546 if (CheckEquivalentExceptionSpec(
547 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
548 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
549 New->setInvalidDecl();
550 }
551}
552
Chris Lattner3d1cee32008-04-08 05:04:30 +0000553/// CheckCXXDefaultArguments - Verify that the default arguments for a
554/// function declaration are well-formed according to C++
555/// [dcl.fct.default].
556void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
557 unsigned NumParams = FD->getNumParams();
558 unsigned p;
559
560 // Find first parameter with a default argument
561 for (p = 0; p < NumParams; ++p) {
562 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000563 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000564 break;
565 }
566
567 // C++ [dcl.fct.default]p4:
568 // In a given function declaration, all parameters
569 // subsequent to a parameter with a default argument shall
570 // have default arguments supplied in this or previous
571 // declarations. A default argument shall not be redefined
572 // by a later declaration (not even to the same value).
573 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000574 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000575 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000576 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000577 if (Param->isInvalidDecl())
578 /* We already complained about this parameter. */;
579 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000580 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000581 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000582 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000583 else
Mike Stump1eb44332009-09-09 15:08:12 +0000584 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Chris Lattner3d1cee32008-04-08 05:04:30 +0000587 LastMissingDefaultArg = p;
588 }
589 }
590
591 if (LastMissingDefaultArg > 0) {
592 // Some default arguments were missing. Clear out all of the
593 // default arguments up to (and including) the last missing
594 // default argument, so that we leave the function parameters
595 // in a semantically valid state.
596 for (p = 0; p <= LastMissingDefaultArg; ++p) {
597 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000598 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000599 Param->setDefaultArg(0);
600 }
601 }
602 }
603}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000604
Douglas Gregorb48fe382008-10-31 09:07:45 +0000605/// isCurrentClassName - Determine whether the identifier II is the
606/// name of the class type currently being defined. In the case of
607/// nested classes, this will only return true if II is the name of
608/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000609bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000611 assert(getLangOptions().CPlusPlus && "No class names in C!");
612
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000613 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000614 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000615 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000616 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
617 } else
618 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
619
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000620 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000621 return &II == CurDecl->getIdentifier();
622 else
623 return false;
624}
625
Mike Stump1eb44332009-09-09 15:08:12 +0000626/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627///
628/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
629/// and returns NULL otherwise.
630CXXBaseSpecifier *
631Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
632 SourceRange SpecifierRange,
633 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000634 TypeSourceInfo *TInfo,
635 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000636 QualType BaseType = TInfo->getType();
637
Douglas Gregor2943aed2009-03-03 04:44:36 +0000638 // C++ [class.union]p1:
639 // A union shall not have base classes.
640 if (Class->isUnion()) {
641 Diag(Class->getLocation(), diag::err_base_clause_on_union)
642 << SpecifierRange;
643 return 0;
644 }
645
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000646 if (EllipsisLoc.isValid() &&
647 !TInfo->getType()->containsUnexpandedParameterPack()) {
648 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
649 << TInfo->getTypeLoc().getSourceRange();
650 EllipsisLoc = SourceLocation();
651 }
652
Douglas Gregor2943aed2009-03-03 04:44:36 +0000653 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000654 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000655 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000656 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000657
658 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000659
660 // Base specifiers must be record types.
661 if (!BaseType->isRecordType()) {
662 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
663 return 0;
664 }
665
666 // C++ [class.union]p1:
667 // A union shall not be used as a base class.
668 if (BaseType->isUnionType()) {
669 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
670 return 0;
671 }
672
673 // C++ [class.derived]p2:
674 // The class-name in a base-specifier shall not be an incompletely
675 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000676 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000677 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000678 << SpecifierRange)) {
679 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000680 return 0;
John McCall572fc622010-08-17 07:23:57 +0000681 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000682
Eli Friedman1d954f62009-08-15 21:55:26 +0000683 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000684 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000685 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000686 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000687 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000688 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000690
Anders Carlsson1d209272011-03-25 14:55:14 +0000691 // C++ [class]p3:
692 // If a class is marked final and it appears as a base-type-specifier in
693 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000694 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000695 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
696 << CXXBaseDecl->getDeclName();
697 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
698 << CXXBaseDecl->getDeclName();
699 return 0;
700 }
701
John McCall572fc622010-08-17 07:23:57 +0000702 if (BaseDecl->isInvalidDecl())
703 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000704
705 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000706 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000707 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000708 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000709}
710
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000711/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
712/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000713/// example:
714/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000715/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000716BaseResult
John McCalld226f652010-08-21 09:40:31 +0000717Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000718 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000719 ParsedType basetype, SourceLocation BaseLoc,
720 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000721 if (!classdecl)
722 return true;
723
Douglas Gregor40808ce2009-03-09 23:48:35 +0000724 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000725 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000726 if (!Class)
727 return true;
728
Nick Lewycky56062202010-07-26 16:56:01 +0000729 TypeSourceInfo *TInfo = 0;
730 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000731
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000732 if (EllipsisLoc.isInvalid() &&
733 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000734 UPPC_BaseType))
735 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000736
Douglas Gregor2943aed2009-03-03 04:44:36 +0000737 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000738 Virtual, Access, TInfo,
739 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000740 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Douglas Gregor2943aed2009-03-03 04:44:36 +0000742 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000743}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000744
Douglas Gregor2943aed2009-03-03 04:44:36 +0000745/// \brief Performs the actual work of attaching the given base class
746/// specifiers to a C++ class.
747bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
748 unsigned NumBases) {
749 if (NumBases == 0)
750 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000751
752 // Used to keep track of which base types we have already seen, so
753 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000754 // that the key is always the unqualified canonical type of the base
755 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000756 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
757
758 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000759 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000760 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000761 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000762 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000763 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000764 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000765 if (KnownBaseTypes[NewBaseType]) {
766 // C++ [class.mi]p3:
767 // A class shall not be specified as a direct base class of a
768 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000769 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000770 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000771 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000772 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000773
774 // Delete the duplicate base class specifier; we're going to
775 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000776 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000777
778 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000779 } else {
780 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000781 KnownBaseTypes[NewBaseType] = Bases[idx];
782 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000783 }
784 }
785
786 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000787 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000788
789 // Delete the remaining (good) base class specifiers, since their
790 // data has been copied into the CXXRecordDecl.
791 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000792 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000793
794 return Invalid;
795}
796
797/// ActOnBaseSpecifiers - Attach the given base specifiers to the
798/// class, after checking whether there are any duplicate base
799/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +0000800void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000801 unsigned NumBases) {
802 if (!ClassDecl || !Bases || !NumBases)
803 return;
804
805 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000806 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000807 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000808}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000809
John McCall3cb0ebd2010-03-10 03:28:59 +0000810static CXXRecordDecl *GetClassForType(QualType T) {
811 if (const RecordType *RT = T->getAs<RecordType>())
812 return cast<CXXRecordDecl>(RT->getDecl());
813 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
814 return ICT->getDecl();
815 else
816 return 0;
817}
818
Douglas Gregora8f32e02009-10-06 17:59:45 +0000819/// \brief Determine whether the type \p Derived is a C++ class that is
820/// derived from the type \p Base.
821bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
822 if (!getLangOptions().CPlusPlus)
823 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000824
825 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
826 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000827 return false;
828
John McCall3cb0ebd2010-03-10 03:28:59 +0000829 CXXRecordDecl *BaseRD = GetClassForType(Base);
830 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000831 return false;
832
John McCall86ff3082010-02-04 22:26:26 +0000833 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
834 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000835}
836
837/// \brief Determine whether the type \p Derived is a C++ class that is
838/// derived from the type \p Base.
839bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
840 if (!getLangOptions().CPlusPlus)
841 return false;
842
John McCall3cb0ebd2010-03-10 03:28:59 +0000843 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
844 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000845 return false;
846
John McCall3cb0ebd2010-03-10 03:28:59 +0000847 CXXRecordDecl *BaseRD = GetClassForType(Base);
848 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000849 return false;
850
Douglas Gregora8f32e02009-10-06 17:59:45 +0000851 return DerivedRD->isDerivedFrom(BaseRD, Paths);
852}
853
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000854void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000855 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000856 assert(BasePathArray.empty() && "Base path array must be empty!");
857 assert(Paths.isRecordingPaths() && "Must record paths!");
858
859 const CXXBasePath &Path = Paths.front();
860
861 // We first go backward and check if we have a virtual base.
862 // FIXME: It would be better if CXXBasePath had the base specifier for
863 // the nearest virtual base.
864 unsigned Start = 0;
865 for (unsigned I = Path.size(); I != 0; --I) {
866 if (Path[I - 1].Base->isVirtual()) {
867 Start = I - 1;
868 break;
869 }
870 }
871
872 // Now add all bases.
873 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000874 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000875}
876
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000877/// \brief Determine whether the given base path includes a virtual
878/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000879bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
880 for (CXXCastPath::const_iterator B = BasePath.begin(),
881 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000882 B != BEnd; ++B)
883 if ((*B)->isVirtual())
884 return true;
885
886 return false;
887}
888
Douglas Gregora8f32e02009-10-06 17:59:45 +0000889/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
890/// conversion (where Derived and Base are class types) is
891/// well-formed, meaning that the conversion is unambiguous (and
892/// that all of the base classes are accessible). Returns true
893/// and emits a diagnostic if the code is ill-formed, returns false
894/// otherwise. Loc is the location where this routine should point to
895/// if there is an error, and Range is the source range to highlight
896/// if there is an error.
897bool
898Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000899 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000900 unsigned AmbigiousBaseConvID,
901 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000902 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000903 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000904 // First, determine whether the path from Derived to Base is
905 // ambiguous. This is slightly more expensive than checking whether
906 // the Derived to Base conversion exists, because here we need to
907 // explore multiple paths to determine if there is an ambiguity.
908 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
909 /*DetectVirtual=*/false);
910 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
911 assert(DerivationOkay &&
912 "Can only be used with a derived-to-base conversion");
913 (void)DerivationOkay;
914
915 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000916 if (InaccessibleBaseID) {
917 // Check that the base class can be accessed.
918 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
919 InaccessibleBaseID)) {
920 case AR_inaccessible:
921 return true;
922 case AR_accessible:
923 case AR_dependent:
924 case AR_delayed:
925 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000926 }
John McCall6b2accb2010-02-10 09:31:12 +0000927 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000928
929 // Build a base path if necessary.
930 if (BasePath)
931 BuildBasePathArray(Paths, *BasePath);
932 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000933 }
934
935 // We know that the derived-to-base conversion is ambiguous, and
936 // we're going to produce a diagnostic. Perform the derived-to-base
937 // search just one more time to compute all of the possible paths so
938 // that we can print them out. This is more expensive than any of
939 // the previous derived-to-base checks we've done, but at this point
940 // performance isn't as much of an issue.
941 Paths.clear();
942 Paths.setRecordingPaths(true);
943 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
944 assert(StillOkay && "Can only be used with a derived-to-base conversion");
945 (void)StillOkay;
946
947 // Build up a textual representation of the ambiguous paths, e.g.,
948 // D -> B -> A, that will be used to illustrate the ambiguous
949 // conversions in the diagnostic. We only print one of the paths
950 // to each base class subobject.
951 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
952
953 Diag(Loc, AmbigiousBaseConvID)
954 << Derived << Base << PathDisplayStr << Range << Name;
955 return true;
956}
957
958bool
959Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000960 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000961 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000962 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000963 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000964 IgnoreAccess ? 0
965 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000966 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000967 Loc, Range, DeclarationName(),
968 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000969}
970
971
972/// @brief Builds a string representing ambiguous paths from a
973/// specific derived class to different subobjects of the same base
974/// class.
975///
976/// This function builds a string that can be used in error messages
977/// to show the different paths that one can take through the
978/// inheritance hierarchy to go from the derived class to different
979/// subobjects of a base class. The result looks something like this:
980/// @code
981/// struct D -> struct B -> struct A
982/// struct D -> struct C -> struct A
983/// @endcode
984std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
985 std::string PathDisplayStr;
986 std::set<unsigned> DisplayedPaths;
987 for (CXXBasePaths::paths_iterator Path = Paths.begin();
988 Path != Paths.end(); ++Path) {
989 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
990 // We haven't displayed a path to this particular base
991 // class subobject yet.
992 PathDisplayStr += "\n ";
993 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
994 for (CXXBasePath::const_iterator Element = Path->begin();
995 Element != Path->end(); ++Element)
996 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
997 }
998 }
999
1000 return PathDisplayStr;
1001}
1002
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001003//===----------------------------------------------------------------------===//
1004// C++ class member Handling
1005//===----------------------------------------------------------------------===//
1006
Abramo Bagnara6206d532010-06-05 05:09:32 +00001007/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +00001008Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1009 SourceLocation ASLoc,
1010 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001011 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001012 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001013 ASLoc, ColonLoc);
1014 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +00001015 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +00001016}
1017
Anders Carlsson9e682d92011-01-20 05:57:14 +00001018/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001019void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001020 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001021 if (!MD || !MD->isVirtual())
1022 return;
1023
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001024 if (MD->isDependentContext())
1025 return;
1026
Anders Carlsson9e682d92011-01-20 05:57:14 +00001027 // C++0x [class.virtual]p3:
1028 // If a virtual function is marked with the virt-specifier override and does
1029 // not override a member function of a base class,
1030 // the program is ill-formed.
1031 bool HasOverriddenMethods =
1032 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001033 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001034 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001035 diag::err_function_marked_override_not_overriding)
1036 << MD->getDeclName();
1037 return;
1038 }
1039}
1040
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001041/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1042/// function overrides a virtual member function marked 'final', according to
1043/// C++0x [class.virtual]p3.
1044bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1045 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001046 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001047 return false;
1048
1049 Diag(New->getLocation(), diag::err_final_function_overridden)
1050 << New->getDeclName();
1051 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1052 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001053}
1054
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001055/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1056/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001057/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1058/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1059/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001060Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001061Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001062 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001063 Expr *BW, const VirtSpecifiers &VS,
1064 Expr *InitExpr, bool HasDeferredInit,
Richard Smith7a614d82011-06-11 17:19:42 +00001065 bool IsDefinition) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001066 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001067 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1068 DeclarationName Name = NameInfo.getName();
1069 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001070
1071 // For anonymous bitfields, the location should point to the type.
1072 if (Loc.isInvalid())
1073 Loc = D.getSourceRange().getBegin();
1074
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001075 Expr *BitWidth = static_cast<Expr*>(BW);
1076 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001077
John McCall4bde1e12010-06-04 08:34:12 +00001078 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001079 assert(!DS.isFriendSpecified());
Richard Smith7a614d82011-06-11 17:19:42 +00001080 assert(!Init || !HasDeferredInit);
John McCall67d1a672009-08-06 02:15:43 +00001081
Richard Smith1ab0d902011-06-25 02:28:38 +00001082 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001083
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001084 // C++ 9.2p6: A member shall not be declared to have automatic storage
1085 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001086 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1087 // data members and cannot be applied to names declared const or static,
1088 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001089 switch (DS.getStorageClassSpec()) {
1090 case DeclSpec::SCS_unspecified:
1091 case DeclSpec::SCS_typedef:
1092 case DeclSpec::SCS_static:
1093 // FALL THROUGH.
1094 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001095 case DeclSpec::SCS_mutable:
1096 if (isFunc) {
1097 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001098 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001099 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001100 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Sebastian Redla11f42f2008-11-17 23:24:37 +00001102 // FIXME: It would be nicer if the keyword was ignored only for this
1103 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001104 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001105 }
1106 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001107 default:
1108 if (DS.getStorageClassSpecLoc().isValid())
1109 Diag(DS.getStorageClassSpecLoc(),
1110 diag::err_storageclass_invalid_for_member);
1111 else
1112 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1113 D.getMutableDeclSpec().ClearStorageClassSpecs();
1114 }
1115
Sebastian Redl669d5d72008-11-14 23:42:31 +00001116 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1117 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001118 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001119
1120 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001121 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001122 CXXScopeSpec &SS = D.getCXXScopeSpec();
1123
Douglas Gregorf2503652011-09-21 14:40:46 +00001124 // FIXME: Check that the name is an identifier!
1125 IdentifierInfo *II = Name.getAsIdentifierInfo();
1126
1127 // Member field could not be with "template" keyword.
1128 // So TemplateParameterLists should be empty in this case.
1129 if (TemplateParameterLists.size()) {
1130 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1131 if (TemplateParams->size()) {
1132 // There is no such thing as a member field template.
1133 Diag(D.getIdentifierLoc(), diag::err_template_member)
1134 << II
1135 << SourceRange(TemplateParams->getTemplateLoc(),
1136 TemplateParams->getRAngleLoc());
1137 } else {
1138 // There is an extraneous 'template<>' for this member.
1139 Diag(TemplateParams->getTemplateLoc(),
1140 diag::err_template_member_noparams)
1141 << II
1142 << SourceRange(TemplateParams->getTemplateLoc(),
1143 TemplateParams->getRAngleLoc());
1144 }
1145 return 0;
1146 }
1147
Douglas Gregor922fff22010-10-13 22:19:53 +00001148 if (SS.isSet() && !SS.isInvalid()) {
1149 // The user provided a superfluous scope specifier inside a class
1150 // definition:
1151 //
1152 // class X {
1153 // int X::member;
1154 // };
1155 DeclContext *DC = 0;
1156 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1157 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1158 << Name << FixItHint::CreateRemoval(SS.getRange());
1159 else
1160 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1161 << Name << SS.getRange();
1162
1163 SS.clear();
1164 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001165
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001166 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001167 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001168 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001169 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001170 assert(!HasDeferredInit);
1171
Sean Hunte4246a62011-05-12 06:15:49 +00001172 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001173 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001174 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001175 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001176
1177 // Non-instance-fields can't have a bitfield.
1178 if (BitWidth) {
1179 if (Member->isInvalidDecl()) {
1180 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001181 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001182 // C++ 9.6p3: A bit-field shall not be a static member.
1183 // "static member 'A' cannot be a bit-field"
1184 Diag(Loc, diag::err_static_not_bitfield)
1185 << Name << BitWidth->getSourceRange();
1186 } else if (isa<TypedefDecl>(Member)) {
1187 // "typedef member 'x' cannot be a bit-field"
1188 Diag(Loc, diag::err_typedef_not_bitfield)
1189 << Name << BitWidth->getSourceRange();
1190 } else {
1191 // A function typedef ("typedef int f(); f a;").
1192 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1193 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001194 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001195 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001196 }
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Chris Lattner8b963ef2009-03-05 23:01:03 +00001198 BitWidth = 0;
1199 Member->setInvalidDecl();
1200 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001201
1202 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Douglas Gregor37b372b2009-08-20 22:52:58 +00001204 // If we have declared a member function template, set the access of the
1205 // templated declaration as well.
1206 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1207 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001208 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001209
Anders Carlssonaae5af22011-01-20 04:34:22 +00001210 if (VS.isOverrideSpecified()) {
1211 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1212 if (!MD || !MD->isVirtual()) {
1213 Diag(Member->getLocStart(),
1214 diag::override_keyword_only_allowed_on_virtual_member_functions)
1215 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001216 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001217 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001218 }
1219 if (VS.isFinalSpecified()) {
1220 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1221 if (!MD || !MD->isVirtual()) {
1222 Diag(Member->getLocStart(),
1223 diag::override_keyword_only_allowed_on_virtual_member_functions)
1224 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001225 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001226 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001227 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001228
Douglas Gregorf5251602011-03-08 17:10:18 +00001229 if (VS.getLastLocation().isValid()) {
1230 // Update the end location of a method that has a virt-specifiers.
1231 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1232 MD->setRangeEnd(VS.getLastLocation());
1233 }
1234
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001235 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001236
Douglas Gregor10bd3682008-11-17 22:58:34 +00001237 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001238
Douglas Gregor021c3b32009-03-11 23:00:04 +00001239 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001240 AddInitializerToDecl(Member, Init, false,
1241 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smith7a614d82011-06-11 17:19:42 +00001242 else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1243 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1244 // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1245 // data member if a brace-or-equal-initializer is provided.
1246 Diag(Loc, diag::err_auto_var_requires_init)
1247 << Name << cast<ValueDecl>(Member)->getType();
1248 Member->setInvalidDecl();
1249 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001250
Richard Smith483b9f32011-02-21 20:05:19 +00001251 FinalizeDeclaration(Member);
1252
John McCallb25b2952011-02-15 07:12:36 +00001253 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001254 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001255 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001256}
1257
Richard Smith7a614d82011-06-11 17:19:42 +00001258/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001259/// in-class initializer for a non-static C++ class member, and after
1260/// instantiating an in-class initializer in a class template. Such actions
1261/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001262void
1263Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1264 Expr *InitExpr) {
1265 FieldDecl *FD = cast<FieldDecl>(D);
1266
1267 if (!InitExpr) {
1268 FD->setInvalidDecl();
1269 FD->removeInClassInitializer();
1270 return;
1271 }
1272
1273 ExprResult Init = InitExpr;
1274 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1275 // FIXME: if there is no EqualLoc, this is list-initialization.
1276 Init = PerformCopyInitialization(
1277 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1278 if (Init.isInvalid()) {
1279 FD->setInvalidDecl();
1280 return;
1281 }
1282
1283 CheckImplicitConversions(Init.get(), EqualLoc);
1284 }
1285
1286 // C++0x [class.base.init]p7:
1287 // The initialization of each base and member constitutes a
1288 // full-expression.
1289 Init = MaybeCreateExprWithCleanups(Init);
1290 if (Init.isInvalid()) {
1291 FD->setInvalidDecl();
1292 return;
1293 }
1294
1295 InitExpr = Init.release();
1296
1297 FD->setInClassInitializer(InitExpr);
1298}
1299
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001300/// \brief Find the direct and/or virtual base specifiers that
1301/// correspond to the given base type, for use in base initialization
1302/// within a constructor.
1303static bool FindBaseInitializer(Sema &SemaRef,
1304 CXXRecordDecl *ClassDecl,
1305 QualType BaseType,
1306 const CXXBaseSpecifier *&DirectBaseSpec,
1307 const CXXBaseSpecifier *&VirtualBaseSpec) {
1308 // First, check for a direct base class.
1309 DirectBaseSpec = 0;
1310 for (CXXRecordDecl::base_class_const_iterator Base
1311 = ClassDecl->bases_begin();
1312 Base != ClassDecl->bases_end(); ++Base) {
1313 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1314 // We found a direct base of this type. That's what we're
1315 // initializing.
1316 DirectBaseSpec = &*Base;
1317 break;
1318 }
1319 }
1320
1321 // Check for a virtual base class.
1322 // FIXME: We might be able to short-circuit this if we know in advance that
1323 // there are no virtual bases.
1324 VirtualBaseSpec = 0;
1325 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1326 // We haven't found a base yet; search the class hierarchy for a
1327 // virtual base class.
1328 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1329 /*DetectVirtual=*/false);
1330 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1331 BaseType, Paths)) {
1332 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1333 Path != Paths.end(); ++Path) {
1334 if (Path->back().Base->isVirtual()) {
1335 VirtualBaseSpec = Path->back().Base;
1336 break;
1337 }
1338 }
1339 }
1340 }
1341
1342 return DirectBaseSpec || VirtualBaseSpec;
1343}
1344
Douglas Gregor7ad83902008-11-05 04:29:56 +00001345/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001346MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001347Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001348 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001349 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001350 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001351 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001352 SourceLocation IdLoc,
1353 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001354 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001355 SourceLocation RParenLoc,
1356 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001357 if (!ConstructorD)
1358 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001360 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001361
1362 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001363 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001364 if (!Constructor) {
1365 // The user wrote a constructor initializer on a function that is
1366 // not a C++ constructor. Ignore the error for now, because we may
1367 // have more member initializers coming; we'll diagnose it just
1368 // once in ActOnMemInitializers.
1369 return true;
1370 }
1371
1372 CXXRecordDecl *ClassDecl = Constructor->getParent();
1373
1374 // C++ [class.base.init]p2:
1375 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001376 // constructor's class and, if not found in that scope, are looked
1377 // up in the scope containing the constructor's definition.
1378 // [Note: if the constructor's class contains a member with the
1379 // same name as a direct or virtual base class of the class, a
1380 // mem-initializer-id naming the member or base class and composed
1381 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001382 // mem-initializer-id for the hidden base class may be specified
1383 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001384 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001385 // Look for a member, first.
1386 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001387 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001388 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001389 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001390 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001391
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001392 if (Member) {
1393 if (EllipsisLoc.isValid())
1394 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1395 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1396
Francois Pichet00eb3f92010-12-04 09:14:42 +00001397 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001398 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001399 }
1400
Francois Pichet00eb3f92010-12-04 09:14:42 +00001401 // Handle anonymous union case.
1402 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001403 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1404 if (EllipsisLoc.isValid())
1405 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1406 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1407
Francois Pichet00eb3f92010-12-04 09:14:42 +00001408 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1409 NumArgs, IdLoc,
1410 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001411 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001412 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001413 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001414 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001415 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001416 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001417
1418 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001419 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001420 } else {
1421 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1422 LookupParsedName(R, S, &SS);
1423
1424 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1425 if (!TyD) {
1426 if (R.isAmbiguous()) return true;
1427
John McCallfd225442010-04-09 19:01:14 +00001428 // We don't want access-control diagnostics here.
1429 R.suppressDiagnostics();
1430
Douglas Gregor7a886e12010-01-19 06:46:48 +00001431 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1432 bool NotUnknownSpecialization = false;
1433 DeclContext *DC = computeDeclContext(SS, false);
1434 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1435 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1436
1437 if (!NotUnknownSpecialization) {
1438 // When the scope specifier can refer to a member of an unknown
1439 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001440 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1441 SS.getWithLocInContext(Context),
1442 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001443 if (BaseType.isNull())
1444 return true;
1445
Douglas Gregor7a886e12010-01-19 06:46:48 +00001446 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001447 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001448 }
1449 }
1450
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001451 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001452 TypoCorrection Corr;
Douglas Gregor7a886e12010-01-19 06:46:48 +00001453 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001454 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1455 ClassDecl, false, CTC_NoKeywords))) {
1456 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1457 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1458 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001459 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001460 // We have found a non-static data member with a similar
1461 // name to what was typed; complain and initialize that
1462 // member.
1463 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001464 << MemberOrBase << true << CorrectedQuotedStr
1465 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001466 Diag(Member->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001467 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001468
1469 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1470 LParenLoc, RParenLoc);
1471 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001472 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001473 const CXXBaseSpecifier *DirectBaseSpec;
1474 const CXXBaseSpecifier *VirtualBaseSpec;
1475 if (FindBaseInitializer(*this, ClassDecl,
1476 Context.getTypeDeclType(Type),
1477 DirectBaseSpec, VirtualBaseSpec)) {
1478 // We have found a direct or virtual base class with a
1479 // similar name to what was typed; complain and initialize
1480 // that base class.
1481 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001482 << MemberOrBase << false << CorrectedQuotedStr
1483 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001484
1485 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1486 : VirtualBaseSpec;
1487 Diag(BaseSpec->getSourceRange().getBegin(),
1488 diag::note_base_class_specified_here)
1489 << BaseSpec->getType()
1490 << BaseSpec->getSourceRange();
1491
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001492 TyD = Type;
1493 }
1494 }
1495 }
1496
Douglas Gregor7a886e12010-01-19 06:46:48 +00001497 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001498 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1499 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1500 return true;
1501 }
John McCall2b194412009-12-21 10:41:20 +00001502 }
1503
Douglas Gregor7a886e12010-01-19 06:46:48 +00001504 if (BaseType.isNull()) {
1505 BaseType = Context.getTypeDeclType(TyD);
1506 if (SS.isSet()) {
1507 NestedNameSpecifier *Qualifier =
1508 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001509
Douglas Gregor7a886e12010-01-19 06:46:48 +00001510 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001511 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001512 }
John McCall2b194412009-12-21 10:41:20 +00001513 }
1514 }
Mike Stump1eb44332009-09-09 15:08:12 +00001515
John McCalla93c9342009-12-07 02:54:59 +00001516 if (!TInfo)
1517 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001518
John McCalla93c9342009-12-07 02:54:59 +00001519 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001520 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001521}
1522
Chandler Carruth81c64772011-09-03 01:14:15 +00001523/// Checks a member initializer expression for cases where reference (or
1524/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001525static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1526 Expr *Init,
1527 SourceLocation IdLoc) {
1528 QualType MemberTy = Member->getType();
1529
1530 // We only handle pointers and references currently.
1531 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1532 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1533 return;
1534
1535 const bool IsPointer = MemberTy->isPointerType();
1536 if (IsPointer) {
1537 if (const UnaryOperator *Op
1538 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1539 // The only case we're worried about with pointers requires taking the
1540 // address.
1541 if (Op->getOpcode() != UO_AddrOf)
1542 return;
1543
1544 Init = Op->getSubExpr();
1545 } else {
1546 // We only handle address-of expression initializers for pointers.
1547 return;
1548 }
1549 }
1550
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001551 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1552 // Taking the address of a temporary will be diagnosed as a hard error.
1553 if (IsPointer)
1554 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001555
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001556 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1557 << Member << Init->getSourceRange();
1558 } else if (const DeclRefExpr *DRE
1559 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1560 // We only warn when referring to a non-reference parameter declaration.
1561 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1562 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001563 return;
1564
1565 S.Diag(Init->getExprLoc(),
1566 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1567 : diag::warn_bind_ref_member_to_parameter)
1568 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001569 } else {
1570 // Other initializers are fine.
1571 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001572 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001573
1574 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1575 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00001576}
1577
John McCallb4190042009-11-04 23:02:40 +00001578/// Checks an initializer expression for use of uninitialized fields, such as
1579/// containing the field that is being initialized. Returns true if there is an
1580/// uninitialized field was used an updates the SourceLocation parameter; false
1581/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001582static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001583 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001584 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001585 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1586
Nick Lewycky43ad1822010-06-15 07:32:55 +00001587 if (isa<CallExpr>(S)) {
1588 // Do not descend into function calls or constructors, as the use
1589 // of an uninitialized field may be valid. One would have to inspect
1590 // the contents of the function/ctor to determine if it is safe or not.
1591 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1592 // may be safe, depending on what the function/ctor does.
1593 return false;
1594 }
1595 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1596 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001597
1598 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1599 // The member expression points to a static data member.
1600 assert(VD->isStaticDataMember() &&
1601 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001602 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001603 return false;
1604 }
1605
1606 if (isa<EnumConstantDecl>(RhsField)) {
1607 // The member expression points to an enum.
1608 return false;
1609 }
1610
John McCallb4190042009-11-04 23:02:40 +00001611 if (RhsField == LhsField) {
1612 // Initializing a field with itself. Throw a warning.
1613 // But wait; there are exceptions!
1614 // Exception #1: The field may not belong to this record.
1615 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001616 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001617 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1618 // Even though the field matches, it does not belong to this record.
1619 return false;
1620 }
1621 // None of the exceptions triggered; return true to indicate an
1622 // uninitialized field was used.
1623 *L = ME->getMemberLoc();
1624 return true;
1625 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001626 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001627 // sizeof/alignof doesn't reference contents, do not warn.
1628 return false;
1629 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1630 // address-of doesn't reference contents (the pointer may be dereferenced
1631 // in the same expression but it would be rare; and weird).
1632 if (UOE->getOpcode() == UO_AddrOf)
1633 return false;
John McCallb4190042009-11-04 23:02:40 +00001634 }
John McCall7502c1d2011-02-13 04:07:26 +00001635 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001636 if (!*it) {
1637 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001638 continue;
1639 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001640 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1641 return true;
John McCallb4190042009-11-04 23:02:40 +00001642 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001643 return false;
John McCallb4190042009-11-04 23:02:40 +00001644}
1645
John McCallf312b1e2010-08-26 23:41:50 +00001646MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001647Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001648 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001649 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001650 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001651 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1652 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1653 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001654 "Member must be a FieldDecl or IndirectFieldDecl");
1655
Douglas Gregor464b2f02010-11-05 22:21:31 +00001656 if (Member->isInvalidDecl())
1657 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001658
John McCallb4190042009-11-04 23:02:40 +00001659 // Diagnose value-uses of fields to initialize themselves, e.g.
1660 // foo(foo)
1661 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001662 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001663 for (unsigned i = 0; i < NumArgs; ++i) {
1664 SourceLocation L;
1665 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1666 // FIXME: Return true in the case when other fields are used before being
1667 // uninitialized. For example, let this field be the i'th field. When
1668 // initializing the i'th field, throw a warning if any of the >= i'th
1669 // fields are used, as they are not yet initialized.
1670 // Right now we are only handling the case where the i'th field uses
1671 // itself in its initializer.
1672 Diag(L, diag::warn_field_is_uninit);
1673 }
1674 }
1675
Eli Friedman59c04372009-07-29 19:44:27 +00001676 bool HasDependentArg = false;
1677 for (unsigned i = 0; i < NumArgs; i++)
1678 HasDependentArg |= Args[i]->isTypeDependent();
1679
Chandler Carruth894aed92010-12-06 09:23:57 +00001680 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001681 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001682 // Can't check initialization for a member of dependent type or when
1683 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001684 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001685 RParenLoc,
1686 Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001687
John McCallf85e1932011-06-15 23:02:42 +00001688 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00001689 } else {
1690 // Initialize the member.
1691 InitializedEntity MemberEntity =
1692 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1693 : InitializedEntity::InitializeMember(IndirectMember, 0);
1694 InitializationKind Kind =
1695 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001696
Chandler Carruth894aed92010-12-06 09:23:57 +00001697 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1698
1699 ExprResult MemberInit =
1700 InitSeq.Perform(*this, MemberEntity, Kind,
1701 MultiExprArg(*this, Args, NumArgs), 0);
1702 if (MemberInit.isInvalid())
1703 return true;
1704
1705 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1706
1707 // C++0x [class.base.init]p7:
1708 // The initialization of each base and member constitutes a
1709 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001710 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001711 if (MemberInit.isInvalid())
1712 return true;
1713
1714 // If we are in a dependent context, template instantiation will
1715 // perform this type-checking again. Just save the arguments that we
1716 // received in a ParenListExpr.
1717 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1718 // of the information that we have about the member
1719 // initializer. However, deconstructing the ASTs is a dicey process,
1720 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00001721 if (CurContext->isDependentContext()) {
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001722 Init = new (Context) ParenListExpr(
1723 Context, LParenLoc, Args, NumArgs, RParenLoc,
1724 Member->getType().getNonReferenceType());
Chandler Carruth81c64772011-09-03 01:14:15 +00001725 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00001726 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00001727 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
1728 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001729 }
1730
Chandler Carruth894aed92010-12-06 09:23:57 +00001731 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001732 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001733 IdLoc, LParenLoc, Init,
1734 RParenLoc);
1735 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001736 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001737 IdLoc, LParenLoc, Init,
1738 RParenLoc);
1739 }
Eli Friedman59c04372009-07-29 19:44:27 +00001740}
1741
John McCallf312b1e2010-08-26 23:41:50 +00001742MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001743Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1744 Expr **Args, unsigned NumArgs,
Sean Hunt41717662011-02-26 19:13:13 +00001745 SourceLocation NameLoc,
Sean Hunt97fcc492011-01-08 19:20:43 +00001746 SourceLocation LParenLoc,
1747 SourceLocation RParenLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001748 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001749 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1750 if (!LangOpts.CPlusPlus0x)
1751 return Diag(Loc, diag::err_delegation_0x_only)
1752 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001753
Sean Hunt41717662011-02-26 19:13:13 +00001754 // Initialize the object.
1755 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1756 QualType(ClassDecl->getTypeForDecl(), 0));
1757 InitializationKind Kind =
1758 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1759
1760 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1761
1762 ExprResult DelegationInit =
1763 InitSeq.Perform(*this, DelegationEntity, Kind,
1764 MultiExprArg(*this, Args, NumArgs), 0);
1765 if (DelegationInit.isInvalid())
1766 return true;
1767
1768 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Sean Huntfe57eef2011-05-04 05:57:24 +00001769 CXXConstructorDecl *Constructor
1770 = ConExpr->getConstructor();
Sean Hunt41717662011-02-26 19:13:13 +00001771 assert(Constructor && "Delegating constructor with no target?");
1772
1773 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1774
1775 // C++0x [class.base.init]p7:
1776 // The initialization of each base and member constitutes a
1777 // full-expression.
1778 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1779 if (DelegationInit.isInvalid())
1780 return true;
1781
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001782 assert(!CurContext->isDependentContext());
Sean Hunt41717662011-02-26 19:13:13 +00001783 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1784 DelegationInit.takeAs<Expr>(),
1785 RParenLoc);
Sean Hunt97fcc492011-01-08 19:20:43 +00001786}
1787
1788MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001789Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001790 Expr **Args, unsigned NumArgs,
1791 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001792 CXXRecordDecl *ClassDecl,
1793 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001794 bool HasDependentArg = false;
1795 for (unsigned i = 0; i < NumArgs; i++)
1796 HasDependentArg |= Args[i]->isTypeDependent();
1797
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001798 SourceLocation BaseLoc
1799 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1800
1801 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1802 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1803 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1804
1805 // C++ [class.base.init]p2:
1806 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001807 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001808 // of that class, the mem-initializer is ill-formed. A
1809 // mem-initializer-list can initialize a base class using any
1810 // name that denotes that base class type.
1811 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1812
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001813 if (EllipsisLoc.isValid()) {
1814 // This is a pack expansion.
1815 if (!BaseType->containsUnexpandedParameterPack()) {
1816 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1817 << SourceRange(BaseLoc, RParenLoc);
1818
1819 EllipsisLoc = SourceLocation();
1820 }
1821 } else {
1822 // Check for any unexpanded parameter packs.
1823 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1824 return true;
1825
1826 for (unsigned I = 0; I != NumArgs; ++I)
1827 if (DiagnoseUnexpandedParameterPack(Args[I]))
1828 return true;
1829 }
1830
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001831 // Check for direct and virtual base classes.
1832 const CXXBaseSpecifier *DirectBaseSpec = 0;
1833 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1834 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001835 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1836 BaseType))
Sean Hunt41717662011-02-26 19:13:13 +00001837 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1838 LParenLoc, RParenLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001839
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001840 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1841 VirtualBaseSpec);
1842
1843 // C++ [base.class.init]p2:
1844 // Unless the mem-initializer-id names a nonstatic data member of the
1845 // constructor's class or a direct or virtual base of that class, the
1846 // mem-initializer is ill-formed.
1847 if (!DirectBaseSpec && !VirtualBaseSpec) {
1848 // If the class has any dependent bases, then it's possible that
1849 // one of those types will resolve to the same type as
1850 // BaseType. Therefore, just treat this as a dependent base
1851 // class initialization. FIXME: Should we try to check the
1852 // initialization anyway? It seems odd.
1853 if (ClassDecl->hasAnyDependentBases())
1854 Dependent = true;
1855 else
1856 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1857 << BaseType << Context.getTypeDeclType(ClassDecl)
1858 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1859 }
1860 }
1861
1862 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001863 // Can't check initialization for a base of dependent type or when
1864 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001865 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001866 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001867 RParenLoc, BaseType));
Eli Friedman59c04372009-07-29 19:44:27 +00001868
John McCallf85e1932011-06-15 23:02:42 +00001869 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Sean Huntcbb67482011-01-08 20:30:50 +00001871 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001872 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001873 LParenLoc,
1874 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001875 RParenLoc,
1876 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001877 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001878
1879 // C++ [base.class.init]p2:
1880 // If a mem-initializer-id is ambiguous because it designates both
1881 // a direct non-virtual base class and an inherited virtual base
1882 // class, the mem-initializer is ill-formed.
1883 if (DirectBaseSpec && VirtualBaseSpec)
1884 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001885 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001886
1887 CXXBaseSpecifier *BaseSpec
1888 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1889 if (!BaseSpec)
1890 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1891
1892 // Initialize the base.
1893 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001894 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001895 InitializationKind Kind =
1896 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1897
1898 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1899
John McCall60d7b3a2010-08-24 06:29:42 +00001900 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001901 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001902 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001903 if (BaseInit.isInvalid())
1904 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001905
1906 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001907
1908 // C++0x [class.base.init]p7:
1909 // The initialization of each base and member constitutes a
1910 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001911 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001912 if (BaseInit.isInvalid())
1913 return true;
1914
1915 // If we are in a dependent context, template instantiation will
1916 // perform this type-checking again. Just save the arguments that we
1917 // received in a ParenListExpr.
1918 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1919 // of the information that we have about the base
1920 // initializer. However, deconstructing the ASTs is a dicey process,
1921 // and this approach is far more likely to get the corner cases right.
1922 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001923 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001924 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001925 RParenLoc, BaseType));
Sean Huntcbb67482011-01-08 20:30:50 +00001926 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001927 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001928 LParenLoc,
1929 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001930 RParenLoc,
1931 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001932 }
1933
Sean Huntcbb67482011-01-08 20:30:50 +00001934 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001935 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001936 LParenLoc,
1937 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001938 RParenLoc,
1939 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001940}
1941
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001942// Create a static_cast\<T&&>(expr).
1943static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
1944 QualType ExprType = E->getType();
1945 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
1946 SourceLocation ExprLoc = E->getLocStart();
1947 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
1948 TargetType, ExprLoc);
1949
1950 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1951 SourceRange(ExprLoc, ExprLoc),
1952 E->getSourceRange()).take();
1953}
1954
Anders Carlssone5ef7402010-04-23 03:10:23 +00001955/// ImplicitInitializerKind - How an implicit base or member initializer should
1956/// initialize its base or member.
1957enum ImplicitInitializerKind {
1958 IIK_Default,
1959 IIK_Copy,
1960 IIK_Move
1961};
1962
Anders Carlssondefefd22010-04-23 02:00:02 +00001963static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001964BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001965 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001966 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001967 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001968 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001969 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001970 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1971 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001972
John McCall60d7b3a2010-08-24 06:29:42 +00001973 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001974
1975 switch (ImplicitInitKind) {
1976 case IIK_Default: {
1977 InitializationKind InitKind
1978 = InitializationKind::CreateDefault(Constructor->getLocation());
1979 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1980 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001981 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001982 break;
1983 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001984
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001985 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00001986 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001987 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001988 ParmVarDecl *Param = Constructor->getParamDecl(0);
1989 QualType ParamType = Param->getType().getNonReferenceType();
1990
1991 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001992 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001993 Constructor->getLocation(), ParamType,
1994 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001995
Anders Carlssonc7957502010-04-24 22:02:54 +00001996 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001997 QualType ArgTy =
1998 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1999 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002000
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002001 if (Moving) {
2002 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2003 }
2004
John McCallf871d0c2010-08-07 06:22:56 +00002005 CXXCastPath BasePath;
2006 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002007 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2008 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002009 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002010 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002011
Anders Carlssone5ef7402010-04-23 03:10:23 +00002012 InitializationKind InitKind
2013 = InitializationKind::CreateDirect(Constructor->getLocation(),
2014 SourceLocation(), SourceLocation());
2015 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2016 &CopyCtorArg, 1);
2017 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002018 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002019 break;
2020 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002021 }
John McCall9ae2f072010-08-23 23:25:46 +00002022
Douglas Gregor53c374f2010-12-07 00:41:46 +00002023 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002024 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002025 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002026
Anders Carlssondefefd22010-04-23 02:00:02 +00002027 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002028 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002029 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2030 SourceLocation()),
2031 BaseSpec->isVirtual(),
2032 SourceLocation(),
2033 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002034 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002035 SourceLocation());
2036
Anders Carlssondefefd22010-04-23 02:00:02 +00002037 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002038}
2039
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002040static bool RefersToRValueRef(Expr *MemRef) {
2041 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2042 return Referenced->getType()->isRValueReferenceType();
2043}
2044
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002045static bool
2046BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002047 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002048 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002049 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002050 if (Field->isInvalidDecl())
2051 return true;
2052
Chandler Carruthf186b542010-06-29 23:50:44 +00002053 SourceLocation Loc = Constructor->getLocation();
2054
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002055 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2056 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002057 ParmVarDecl *Param = Constructor->getParamDecl(0);
2058 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002059
2060 // Suppress copying zero-width bitfields.
2061 if (const Expr *Width = Field->getBitWidth())
2062 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
2063 return false;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002064
2065 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00002066 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002067 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002068
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002069 if (Moving) {
2070 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2071 }
2072
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002073 // Build a reference to this field within the parameter.
2074 CXXScopeSpec SS;
2075 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2076 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002077 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2078 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002079 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002080 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002081 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002082 ParamType, Loc,
2083 /*IsArrow=*/false,
2084 SS,
2085 /*FirstQualifierInScope=*/0,
2086 MemberLookup,
2087 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002088 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002089 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002090
2091 // C++11 [class.copy]p15:
2092 // - if a member m has rvalue reference type T&&, it is direct-initialized
2093 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002094 if (RefersToRValueRef(CtorArg.get())) {
2095 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002096 }
2097
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002098 // When the field we are copying is an array, create index variables for
2099 // each dimension of the array. We use these index variables to subscript
2100 // the source array, and other clients (e.g., CodeGen) will perform the
2101 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002102 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002103 QualType BaseType = Field->getType();
2104 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002105 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002106 while (const ConstantArrayType *Array
2107 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002108 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002109 // Create the iteration variable for this array index.
2110 IdentifierInfo *IterationVarName = 0;
2111 {
2112 llvm::SmallString<8> Str;
2113 llvm::raw_svector_ostream OS(Str);
2114 OS << "__i" << IndexVariables.size();
2115 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2116 }
2117 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002118 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002119 IterationVarName, SizeType,
2120 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002121 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002122 IndexVariables.push_back(IterationVar);
2123
2124 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002125 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00002126 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002127 assert(!IterationVarRef.isInvalid() &&
2128 "Reference to invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002129
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002130 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002131 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002132 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002133 Loc);
2134 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002135 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002136
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002137 BaseType = Array->getElementType();
2138 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002139
2140 // The array subscript expression is an lvalue, which is wrong for moving.
2141 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002142 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002143
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002144 // Construct the entity that we will be initializing. For an array, this
2145 // will be first element in the array, which may require several levels
2146 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002147 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002148 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002149 if (Indirect)
2150 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2151 else
2152 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002153 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2154 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2155 0,
2156 Entities.back()));
2157
2158 // Direct-initialize to use the copy constructor.
2159 InitializationKind InitKind =
2160 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2161
Sebastian Redl74e611a2011-09-04 18:14:28 +00002162 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002163 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002164 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002165
John McCall60d7b3a2010-08-24 06:29:42 +00002166 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002167 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002168 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002169 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002170 if (MemberInit.isInvalid())
2171 return true;
2172
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002173 if (Indirect) {
2174 assert(IndexVariables.size() == 0 &&
2175 "Indirect field improperly initialized");
2176 CXXMemberInit
2177 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2178 Loc, Loc,
2179 MemberInit.takeAs<Expr>(),
2180 Loc);
2181 } else
2182 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2183 Loc, MemberInit.takeAs<Expr>(),
2184 Loc,
2185 IndexVariables.data(),
2186 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002187 return false;
2188 }
2189
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002190 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2191
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002192 QualType FieldBaseElementType =
2193 SemaRef.Context.getBaseElementType(Field->getType());
2194
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002195 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002196 InitializedEntity InitEntity
2197 = Indirect? InitializedEntity::InitializeMember(Indirect)
2198 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002199 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002200 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002201
2202 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002203 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002204 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002205
Douglas Gregor53c374f2010-12-07 00:41:46 +00002206 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002207 if (MemberInit.isInvalid())
2208 return true;
2209
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002210 if (Indirect)
2211 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2212 Indirect, Loc,
2213 Loc,
2214 MemberInit.get(),
2215 Loc);
2216 else
2217 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2218 Field, Loc, Loc,
2219 MemberInit.get(),
2220 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002221 return false;
2222 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002223
Sean Hunt1f2f3842011-05-17 00:19:05 +00002224 if (!Field->getParent()->isUnion()) {
2225 if (FieldBaseElementType->isReferenceType()) {
2226 SemaRef.Diag(Constructor->getLocation(),
2227 diag::err_uninitialized_member_in_ctor)
2228 << (int)Constructor->isImplicit()
2229 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2230 << 0 << Field->getDeclName();
2231 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2232 return true;
2233 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002234
Sean Hunt1f2f3842011-05-17 00:19:05 +00002235 if (FieldBaseElementType.isConstQualified()) {
2236 SemaRef.Diag(Constructor->getLocation(),
2237 diag::err_uninitialized_member_in_ctor)
2238 << (int)Constructor->isImplicit()
2239 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2240 << 1 << Field->getDeclName();
2241 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2242 return true;
2243 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002244 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002245
John McCallf85e1932011-06-15 23:02:42 +00002246 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2247 FieldBaseElementType->isObjCRetainableType() &&
2248 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2249 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2250 // Instant objects:
2251 // Default-initialize Objective-C pointers to NULL.
2252 CXXMemberInit
2253 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2254 Loc, Loc,
2255 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2256 Loc);
2257 return false;
2258 }
2259
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002260 // Nothing to initialize.
2261 CXXMemberInit = 0;
2262 return false;
2263}
John McCallf1860e52010-05-20 23:23:51 +00002264
2265namespace {
2266struct BaseAndFieldInfo {
2267 Sema &S;
2268 CXXConstructorDecl *Ctor;
2269 bool AnyErrorsInInits;
2270 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002271 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002272 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002273
2274 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2275 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002276 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2277 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002278 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002279 else if (Generated && Ctor->isMoveConstructor())
2280 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002281 else
2282 IIK = IIK_Default;
2283 }
2284};
2285}
2286
Richard Smitha4950662011-09-19 13:34:43 +00002287/// \brief Determine whether the given indirect field declaration is somewhere
2288/// within an anonymous union.
2289static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2290 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2291 CEnd = F->chain_end();
2292 C != CEnd; ++C)
2293 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2294 if (Record->isUnion())
2295 return true;
2296
2297 return false;
2298}
2299
Richard Smith7a614d82011-06-11 17:19:42 +00002300static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002301 FieldDecl *Field,
2302 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002303
Chandler Carruthe861c602010-06-30 02:59:29 +00002304 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002305 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002306 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002307 return false;
2308 }
2309
Richard Smith7a614d82011-06-11 17:19:42 +00002310 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2311 // has a brace-or-equal-initializer, the entity is initialized as specified
2312 // in [dcl.init].
2313 if (Field->hasInClassInitializer()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002314 CXXCtorInitializer *Init;
2315 if (Indirect)
2316 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2317 SourceLocation(),
2318 SourceLocation(), 0,
2319 SourceLocation());
2320 else
2321 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2322 SourceLocation(),
2323 SourceLocation(), 0,
2324 SourceLocation());
2325 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002326 return false;
2327 }
2328
Richard Smithc115f632011-09-18 11:14:50 +00002329 // Don't build an implicit initializer for union members if none was
2330 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002331 if (Field->getParent()->isUnion() ||
2332 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002333 return false;
2334
John McCallf1860e52010-05-20 23:23:51 +00002335 // Don't try to build an implicit initializer if there were semantic
2336 // errors in any of the initializers (and therefore we might be
2337 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002338 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002339 return false;
2340
Sean Huntcbb67482011-01-08 20:30:50 +00002341 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002342 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2343 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002344 return true;
John McCallf1860e52010-05-20 23:23:51 +00002345
Francois Pichet00eb3f92010-12-04 09:14:42 +00002346 if (Init)
2347 Info.AllToInit.push_back(Init);
2348
John McCallf1860e52010-05-20 23:23:51 +00002349 return false;
2350}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002351
2352bool
2353Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2354 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002355 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002356 Constructor->setNumCtorInitializers(1);
2357 CXXCtorInitializer **initializer =
2358 new (Context) CXXCtorInitializer*[1];
2359 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2360 Constructor->setCtorInitializers(initializer);
2361
Sean Huntb76af9c2011-05-03 23:05:34 +00002362 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2363 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2364 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2365 }
2366
Sean Huntc1598702011-05-05 00:05:47 +00002367 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002368
Sean Hunt059ce0d2011-05-01 07:04:31 +00002369 return false;
2370}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002371
John McCallb77115d2011-06-17 00:18:42 +00002372bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2373 CXXCtorInitializer **Initializers,
2374 unsigned NumInitializers,
2375 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002376 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002377 // Just store the initializers as written, they will be checked during
2378 // instantiation.
2379 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002380 Constructor->setNumCtorInitializers(NumInitializers);
2381 CXXCtorInitializer **baseOrMemberInitializers =
2382 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002383 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002384 NumInitializers * sizeof(CXXCtorInitializer*));
2385 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002386 }
2387
2388 return false;
2389 }
2390
John McCallf1860e52010-05-20 23:23:51 +00002391 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002392
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002393 // We need to build the initializer AST according to order of construction
2394 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002395 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002396 if (!ClassDecl)
2397 return true;
2398
Eli Friedman80c30da2009-11-09 19:20:36 +00002399 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002400
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002401 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002402 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002403
2404 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002405 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002406 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002407 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002408 }
2409
Anders Carlsson711f34a2010-04-21 19:52:01 +00002410 // Keep track of the direct virtual bases.
2411 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2412 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2413 E = ClassDecl->bases_end(); I != E; ++I) {
2414 if (I->isVirtual())
2415 DirectVBases.insert(I);
2416 }
2417
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002418 // Push virtual bases before others.
2419 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2420 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2421
Sean Huntcbb67482011-01-08 20:30:50 +00002422 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002423 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2424 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002425 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002426 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002427 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002428 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002429 VBase, IsInheritedVirtualBase,
2430 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002431 HadError = true;
2432 continue;
2433 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002434
John McCallf1860e52010-05-20 23:23:51 +00002435 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002436 }
2437 }
Mike Stump1eb44332009-09-09 15:08:12 +00002438
John McCallf1860e52010-05-20 23:23:51 +00002439 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002440 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2441 E = ClassDecl->bases_end(); Base != E; ++Base) {
2442 // Virtuals are in the virtual base list and already constructed.
2443 if (Base->isVirtual())
2444 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002445
Sean Huntcbb67482011-01-08 20:30:50 +00002446 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002447 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2448 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002449 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002450 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002451 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002452 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002453 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002454 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002455 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002456 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002457
John McCallf1860e52010-05-20 23:23:51 +00002458 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002459 }
2460 }
Mike Stump1eb44332009-09-09 15:08:12 +00002461
John McCallf1860e52010-05-20 23:23:51 +00002462 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002463 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2464 MemEnd = ClassDecl->decls_end();
2465 Mem != MemEnd; ++Mem) {
2466 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2467 if (F->getType()->isIncompleteArrayType()) {
2468 assert(ClassDecl->hasFlexibleArrayMember() &&
2469 "Incomplete array type is not valid");
2470 continue;
2471 }
2472
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002473 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002474 // handle anonymous struct/union fields based on their individual
2475 // indirect fields.
2476 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2477 continue;
2478
2479 if (CollectFieldInitializer(*this, Info, F))
2480 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002481 continue;
2482 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002483
2484 // Beyond this point, we only consider default initialization.
2485 if (Info.IIK != IIK_Default)
2486 continue;
2487
2488 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2489 if (F->getType()->isIncompleteArrayType()) {
2490 assert(ClassDecl->hasFlexibleArrayMember() &&
2491 "Incomplete array type is not valid");
2492 continue;
2493 }
2494
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002495 // Initialize each field of an anonymous struct individually.
2496 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2497 HadError = true;
2498
2499 continue;
2500 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002501 }
Mike Stump1eb44332009-09-09 15:08:12 +00002502
John McCallf1860e52010-05-20 23:23:51 +00002503 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002504 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002505 Constructor->setNumCtorInitializers(NumInitializers);
2506 CXXCtorInitializer **baseOrMemberInitializers =
2507 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002508 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002509 NumInitializers * sizeof(CXXCtorInitializer*));
2510 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002511
John McCallef027fe2010-03-16 21:39:52 +00002512 // Constructors implicitly reference the base and member
2513 // destructors.
2514 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2515 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002516 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002517
2518 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002519}
2520
Eli Friedman6347f422009-07-21 19:28:10 +00002521static void *GetKeyForTopLevelField(FieldDecl *Field) {
2522 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002523 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002524 if (RT->getDecl()->isAnonymousStructOrUnion())
2525 return static_cast<void *>(RT->getDecl());
2526 }
2527 return static_cast<void *>(Field);
2528}
2529
Anders Carlssonea356fb2010-04-02 05:42:15 +00002530static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002531 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002532}
2533
Anders Carlssonea356fb2010-04-02 05:42:15 +00002534static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002535 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002536 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002537 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002538
Eli Friedman6347f422009-07-21 19:28:10 +00002539 // For fields injected into the class via declaration of an anonymous union,
2540 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002541 FieldDecl *Field = Member->getAnyMember();
2542
John McCall3c3ccdb2010-04-10 09:28:51 +00002543 // If the field is a member of an anonymous struct or union, our key
2544 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002545 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002546 if (RD->isAnonymousStructOrUnion()) {
2547 while (true) {
2548 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2549 if (Parent->isAnonymousStructOrUnion())
2550 RD = Parent;
2551 else
2552 break;
2553 }
2554
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002555 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002556 }
Mike Stump1eb44332009-09-09 15:08:12 +00002557
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002558 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002559}
2560
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002561static void
2562DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002563 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002564 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002565 unsigned NumInits) {
2566 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002567 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002568
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002569 // Don't check initializers order unless the warning is enabled at the
2570 // location of at least one initializer.
2571 bool ShouldCheckOrder = false;
2572 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002573 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002574 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2575 Init->getSourceLocation())
2576 != Diagnostic::Ignored) {
2577 ShouldCheckOrder = true;
2578 break;
2579 }
2580 }
2581 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002582 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002583
John McCalld6ca8da2010-04-10 07:37:23 +00002584 // Build the list of bases and members in the order that they'll
2585 // actually be initialized. The explicit initializers should be in
2586 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002587 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002588
Anders Carlsson071d6102010-04-02 03:38:04 +00002589 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2590
John McCalld6ca8da2010-04-10 07:37:23 +00002591 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002592 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002593 ClassDecl->vbases_begin(),
2594 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002595 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002596
John McCalld6ca8da2010-04-10 07:37:23 +00002597 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002598 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002599 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002600 if (Base->isVirtual())
2601 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002602 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002603 }
Mike Stump1eb44332009-09-09 15:08:12 +00002604
John McCalld6ca8da2010-04-10 07:37:23 +00002605 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002606 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2607 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002608 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002609
John McCalld6ca8da2010-04-10 07:37:23 +00002610 unsigned NumIdealInits = IdealInitKeys.size();
2611 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002612
Sean Huntcbb67482011-01-08 20:30:50 +00002613 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002614 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002615 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002616 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002617
2618 // Scan forward to try to find this initializer in the idealized
2619 // initializers list.
2620 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2621 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002622 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002623
2624 // If we didn't find this initializer, it must be because we
2625 // scanned past it on a previous iteration. That can only
2626 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002627 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002628 Sema::SemaDiagnosticBuilder D =
2629 SemaRef.Diag(PrevInit->getSourceLocation(),
2630 diag::warn_initializer_out_of_order);
2631
Francois Pichet00eb3f92010-12-04 09:14:42 +00002632 if (PrevInit->isAnyMemberInitializer())
2633 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002634 else
2635 D << 1 << PrevInit->getBaseClassInfo()->getType();
2636
Francois Pichet00eb3f92010-12-04 09:14:42 +00002637 if (Init->isAnyMemberInitializer())
2638 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002639 else
2640 D << 1 << Init->getBaseClassInfo()->getType();
2641
2642 // Move back to the initializer's location in the ideal list.
2643 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2644 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002645 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002646
2647 assert(IdealIndex != NumIdealInits &&
2648 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002649 }
John McCalld6ca8da2010-04-10 07:37:23 +00002650
2651 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002652 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002653}
2654
John McCall3c3ccdb2010-04-10 09:28:51 +00002655namespace {
2656bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002657 CXXCtorInitializer *Init,
2658 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002659 if (!PrevInit) {
2660 PrevInit = Init;
2661 return false;
2662 }
2663
2664 if (FieldDecl *Field = Init->getMember())
2665 S.Diag(Init->getSourceLocation(),
2666 diag::err_multiple_mem_initialization)
2667 << Field->getDeclName()
2668 << Init->getSourceRange();
2669 else {
John McCallf4c73712011-01-19 06:33:43 +00002670 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002671 assert(BaseClass && "neither field nor base");
2672 S.Diag(Init->getSourceLocation(),
2673 diag::err_multiple_base_initialization)
2674 << QualType(BaseClass, 0)
2675 << Init->getSourceRange();
2676 }
2677 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2678 << 0 << PrevInit->getSourceRange();
2679
2680 return true;
2681}
2682
Sean Huntcbb67482011-01-08 20:30:50 +00002683typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002684typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2685
2686bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002687 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002688 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002689 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002690 RecordDecl *Parent = Field->getParent();
2691 if (!Parent->isAnonymousStructOrUnion())
2692 return false;
2693
2694 NamedDecl *Child = Field;
2695 do {
2696 if (Parent->isUnion()) {
2697 UnionEntry &En = Unions[Parent];
2698 if (En.first && En.first != Child) {
2699 S.Diag(Init->getSourceLocation(),
2700 diag::err_multiple_mem_union_initialization)
2701 << Field->getDeclName()
2702 << Init->getSourceRange();
2703 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2704 << 0 << En.second->getSourceRange();
2705 return true;
2706 } else if (!En.first) {
2707 En.first = Child;
2708 En.second = Init;
2709 }
2710 }
2711
2712 Child = Parent;
2713 Parent = cast<RecordDecl>(Parent->getDeclContext());
2714 } while (Parent->isAnonymousStructOrUnion());
2715
2716 return false;
2717}
2718}
2719
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002720/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002721void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002722 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00002723 CXXCtorInitializer **meminits,
2724 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002725 bool AnyErrors) {
2726 if (!ConstructorDecl)
2727 return;
2728
2729 AdjustDeclIfTemplate(ConstructorDecl);
2730
2731 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002732 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002733
2734 if (!Constructor) {
2735 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2736 return;
2737 }
2738
Sean Huntcbb67482011-01-08 20:30:50 +00002739 CXXCtorInitializer **MemInits =
2740 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002741
2742 // Mapping for the duplicate initializers check.
2743 // For member initializers, this is keyed with a FieldDecl*.
2744 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002745 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002746
2747 // Mapping for the inconsistent anonymous-union initializers check.
2748 RedundantUnionMap MemberUnions;
2749
Anders Carlssonea356fb2010-04-02 05:42:15 +00002750 bool HadError = false;
2751 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002752 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002753
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002754 // Set the source order index.
2755 Init->setSourceOrder(i);
2756
Francois Pichet00eb3f92010-12-04 09:14:42 +00002757 if (Init->isAnyMemberInitializer()) {
2758 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002759 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2760 CheckRedundantUnionInit(*this, Init, MemberUnions))
2761 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002762 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002763 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2764 if (CheckRedundantInit(*this, Init, Members[Key]))
2765 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002766 } else {
2767 assert(Init->isDelegatingInitializer());
2768 // This must be the only initializer
2769 if (i != 0 || NumMemInits > 1) {
2770 Diag(MemInits[0]->getSourceLocation(),
2771 diag::err_delegating_initializer_alone)
2772 << MemInits[0]->getSourceRange();
2773 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002774 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002775 }
Sean Huntfe57eef2011-05-04 05:57:24 +00002776 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00002777 // Return immediately as the initializer is set.
2778 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002779 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002780 }
2781
Anders Carlssonea356fb2010-04-02 05:42:15 +00002782 if (HadError)
2783 return;
2784
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002785 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002786
Sean Huntcbb67482011-01-08 20:30:50 +00002787 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002788}
2789
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002790void
John McCallef027fe2010-03-16 21:39:52 +00002791Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2792 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00002793 // Ignore dependent contexts. Also ignore unions, since their members never
2794 // have destructors implicitly called.
2795 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002796 return;
John McCall58e6f342010-03-16 05:22:47 +00002797
2798 // FIXME: all the access-control diagnostics are positioned on the
2799 // field/base declaration. That's probably good; that said, the
2800 // user might reasonably want to know why the destructor is being
2801 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002802
Anders Carlsson9f853df2009-11-17 04:44:12 +00002803 // Non-static data members.
2804 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2805 E = ClassDecl->field_end(); I != E; ++I) {
2806 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002807 if (Field->isInvalidDecl())
2808 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002809 QualType FieldType = Context.getBaseElementType(Field->getType());
2810
2811 const RecordType* RT = FieldType->getAs<RecordType>();
2812 if (!RT)
2813 continue;
2814
2815 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002816 if (FieldClassDecl->isInvalidDecl())
2817 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002818 if (FieldClassDecl->hasTrivialDestructor())
2819 continue;
2820
Douglas Gregordb89f282010-07-01 22:47:18 +00002821 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002822 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002823 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002824 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002825 << Field->getDeclName()
2826 << FieldType);
2827
John McCallef027fe2010-03-16 21:39:52 +00002828 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002829 }
2830
John McCall58e6f342010-03-16 05:22:47 +00002831 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2832
Anders Carlsson9f853df2009-11-17 04:44:12 +00002833 // Bases.
2834 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2835 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002836 // Bases are always records in a well-formed non-dependent class.
2837 const RecordType *RT = Base->getType()->getAs<RecordType>();
2838
2839 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002840 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002841 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002842
John McCall58e6f342010-03-16 05:22:47 +00002843 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002844 // If our base class is invalid, we probably can't get its dtor anyway.
2845 if (BaseClassDecl->isInvalidDecl())
2846 continue;
2847 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002848 if (BaseClassDecl->hasTrivialDestructor())
2849 continue;
John McCall58e6f342010-03-16 05:22:47 +00002850
Douglas Gregordb89f282010-07-01 22:47:18 +00002851 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002852 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002853
2854 // FIXME: caret should be on the start of the class name
2855 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002856 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002857 << Base->getType()
2858 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002859
John McCallef027fe2010-03-16 21:39:52 +00002860 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002861 }
2862
2863 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002864 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2865 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002866
2867 // Bases are always records in a well-formed non-dependent class.
2868 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2869
2870 // Ignore direct virtual bases.
2871 if (DirectVirtualBases.count(RT))
2872 continue;
2873
John McCall58e6f342010-03-16 05:22:47 +00002874 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002875 // If our base class is invalid, we probably can't get its dtor anyway.
2876 if (BaseClassDecl->isInvalidDecl())
2877 continue;
2878 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002879 if (BaseClassDecl->hasTrivialDestructor())
2880 continue;
John McCall58e6f342010-03-16 05:22:47 +00002881
Douglas Gregordb89f282010-07-01 22:47:18 +00002882 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002883 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002884 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002885 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002886 << VBase->getType());
2887
John McCallef027fe2010-03-16 21:39:52 +00002888 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002889 }
2890}
2891
John McCalld226f652010-08-21 09:40:31 +00002892void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002893 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002894 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002895
Mike Stump1eb44332009-09-09 15:08:12 +00002896 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002897 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002898 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002899}
2900
Mike Stump1eb44332009-09-09 15:08:12 +00002901bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002902 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002903 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002904 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002905 else
John McCall94c3b562010-08-18 09:41:07 +00002906 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002907}
2908
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002909bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002910 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002911 if (!getLangOptions().CPlusPlus)
2912 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002913
Anders Carlsson11f21a02009-03-23 19:10:31 +00002914 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002915 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002916
Ted Kremenek6217b802009-07-29 21:53:49 +00002917 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002918 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002919 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002920 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002921
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002922 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002923 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002924 }
Mike Stump1eb44332009-09-09 15:08:12 +00002925
Ted Kremenek6217b802009-07-29 21:53:49 +00002926 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002927 if (!RT)
2928 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002929
John McCall86ff3082010-02-04 22:26:26 +00002930 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002931
John McCall94c3b562010-08-18 09:41:07 +00002932 // We can't answer whether something is abstract until it has a
2933 // definition. If it's currently being defined, we'll walk back
2934 // over all the declarations when we have a full definition.
2935 const CXXRecordDecl *Def = RD->getDefinition();
2936 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002937 return false;
2938
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002939 if (!RD->isAbstract())
2940 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002941
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002942 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002943 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002944
John McCall94c3b562010-08-18 09:41:07 +00002945 return true;
2946}
2947
2948void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2949 // Check if we've already emitted the list of pure virtual functions
2950 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002951 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002952 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002953
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002954 CXXFinalOverriderMap FinalOverriders;
2955 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002956
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002957 // Keep a set of seen pure methods so we won't diagnose the same method
2958 // more than once.
2959 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2960
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002961 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2962 MEnd = FinalOverriders.end();
2963 M != MEnd;
2964 ++M) {
2965 for (OverridingMethods::iterator SO = M->second.begin(),
2966 SOEnd = M->second.end();
2967 SO != SOEnd; ++SO) {
2968 // C++ [class.abstract]p4:
2969 // A class is abstract if it contains or inherits at least one
2970 // pure virtual function for which the final overrider is pure
2971 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002972
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002973 //
2974 if (SO->second.size() != 1)
2975 continue;
2976
2977 if (!SO->second.front().Method->isPure())
2978 continue;
2979
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002980 if (!SeenPureMethods.insert(SO->second.front().Method))
2981 continue;
2982
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002983 Diag(SO->second.front().Method->getLocation(),
2984 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002985 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002986 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002987 }
2988
2989 if (!PureVirtualClassDiagSet)
2990 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2991 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002992}
2993
Anders Carlsson8211eff2009-03-24 01:19:16 +00002994namespace {
John McCall94c3b562010-08-18 09:41:07 +00002995struct AbstractUsageInfo {
2996 Sema &S;
2997 CXXRecordDecl *Record;
2998 CanQualType AbstractType;
2999 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003000
John McCall94c3b562010-08-18 09:41:07 +00003001 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3002 : S(S), Record(Record),
3003 AbstractType(S.Context.getCanonicalType(
3004 S.Context.getTypeDeclType(Record))),
3005 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003006
John McCall94c3b562010-08-18 09:41:07 +00003007 void DiagnoseAbstractType() {
3008 if (Invalid) return;
3009 S.DiagnoseAbstractType(Record);
3010 Invalid = true;
3011 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003012
John McCall94c3b562010-08-18 09:41:07 +00003013 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3014};
3015
3016struct CheckAbstractUsage {
3017 AbstractUsageInfo &Info;
3018 const NamedDecl *Ctx;
3019
3020 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3021 : Info(Info), Ctx(Ctx) {}
3022
3023 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3024 switch (TL.getTypeLocClass()) {
3025#define ABSTRACT_TYPELOC(CLASS, PARENT)
3026#define TYPELOC(CLASS, PARENT) \
3027 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3028#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003029 }
John McCall94c3b562010-08-18 09:41:07 +00003030 }
Mike Stump1eb44332009-09-09 15:08:12 +00003031
John McCall94c3b562010-08-18 09:41:07 +00003032 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3033 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3034 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003035 if (!TL.getArg(I))
3036 continue;
3037
John McCall94c3b562010-08-18 09:41:07 +00003038 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3039 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003040 }
John McCall94c3b562010-08-18 09:41:07 +00003041 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003042
John McCall94c3b562010-08-18 09:41:07 +00003043 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3044 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3045 }
Mike Stump1eb44332009-09-09 15:08:12 +00003046
John McCall94c3b562010-08-18 09:41:07 +00003047 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3048 // Visit the type parameters from a permissive context.
3049 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3050 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3051 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3052 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3053 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3054 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003055 }
John McCall94c3b562010-08-18 09:41:07 +00003056 }
Mike Stump1eb44332009-09-09 15:08:12 +00003057
John McCall94c3b562010-08-18 09:41:07 +00003058 // Visit pointee types from a permissive context.
3059#define CheckPolymorphic(Type) \
3060 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3061 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3062 }
3063 CheckPolymorphic(PointerTypeLoc)
3064 CheckPolymorphic(ReferenceTypeLoc)
3065 CheckPolymorphic(MemberPointerTypeLoc)
3066 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003067
John McCall94c3b562010-08-18 09:41:07 +00003068 /// Handle all the types we haven't given a more specific
3069 /// implementation for above.
3070 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3071 // Every other kind of type that we haven't called out already
3072 // that has an inner type is either (1) sugar or (2) contains that
3073 // inner type in some way as a subobject.
3074 if (TypeLoc Next = TL.getNextTypeLoc())
3075 return Visit(Next, Sel);
3076
3077 // If there's no inner type and we're in a permissive context,
3078 // don't diagnose.
3079 if (Sel == Sema::AbstractNone) return;
3080
3081 // Check whether the type matches the abstract type.
3082 QualType T = TL.getType();
3083 if (T->isArrayType()) {
3084 Sel = Sema::AbstractArrayType;
3085 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003086 }
John McCall94c3b562010-08-18 09:41:07 +00003087 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3088 if (CT != Info.AbstractType) return;
3089
3090 // It matched; do some magic.
3091 if (Sel == Sema::AbstractArrayType) {
3092 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3093 << T << TL.getSourceRange();
3094 } else {
3095 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3096 << Sel << T << TL.getSourceRange();
3097 }
3098 Info.DiagnoseAbstractType();
3099 }
3100};
3101
3102void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3103 Sema::AbstractDiagSelID Sel) {
3104 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3105}
3106
3107}
3108
3109/// Check for invalid uses of an abstract type in a method declaration.
3110static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3111 CXXMethodDecl *MD) {
3112 // No need to do the check on definitions, which require that
3113 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003114 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003115 return;
3116
3117 // For safety's sake, just ignore it if we don't have type source
3118 // information. This should never happen for non-implicit methods,
3119 // but...
3120 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3121 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3122}
3123
3124/// Check for invalid uses of an abstract type within a class definition.
3125static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3126 CXXRecordDecl *RD) {
3127 for (CXXRecordDecl::decl_iterator
3128 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3129 Decl *D = *I;
3130 if (D->isImplicit()) continue;
3131
3132 // Methods and method templates.
3133 if (isa<CXXMethodDecl>(D)) {
3134 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3135 } else if (isa<FunctionTemplateDecl>(D)) {
3136 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3137 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3138
3139 // Fields and static variables.
3140 } else if (isa<FieldDecl>(D)) {
3141 FieldDecl *FD = cast<FieldDecl>(D);
3142 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3143 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3144 } else if (isa<VarDecl>(D)) {
3145 VarDecl *VD = cast<VarDecl>(D);
3146 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3147 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3148
3149 // Nested classes and class templates.
3150 } else if (isa<CXXRecordDecl>(D)) {
3151 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3152 } else if (isa<ClassTemplateDecl>(D)) {
3153 CheckAbstractClassUsage(Info,
3154 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3155 }
3156 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003157}
3158
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003159/// \brief Perform semantic checks on a class definition that has been
3160/// completing, introducing implicitly-declared members, checking for
3161/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003162void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003163 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003164 return;
3165
John McCall94c3b562010-08-18 09:41:07 +00003166 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3167 AbstractUsageInfo Info(*this, Record);
3168 CheckAbstractClassUsage(Info, Record);
3169 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003170
3171 // If this is not an aggregate type and has no user-declared constructor,
3172 // complain about any non-static data members of reference or const scalar
3173 // type, since they will never get initializers.
3174 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3175 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3176 bool Complained = false;
3177 for (RecordDecl::field_iterator F = Record->field_begin(),
3178 FEnd = Record->field_end();
3179 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00003180 if (F->hasInClassInitializer())
3181 continue;
3182
Douglas Gregor325e5932010-04-15 00:00:53 +00003183 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003184 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003185 if (!Complained) {
3186 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3187 << Record->getTagKind() << Record;
3188 Complained = true;
3189 }
3190
3191 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3192 << F->getType()->isReferenceType()
3193 << F->getDeclName();
3194 }
3195 }
3196 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003197
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003198 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003199 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003200
3201 if (Record->getIdentifier()) {
3202 // C++ [class.mem]p13:
3203 // If T is the name of a class, then each of the following shall have a
3204 // name different from T:
3205 // - every member of every anonymous union that is a member of class T.
3206 //
3207 // C++ [class.mem]p14:
3208 // In addition, if class T has a user-declared constructor (12.1), every
3209 // non-static data member of class T shall have a name different from T.
3210 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003211 R.first != R.second; ++R.first) {
3212 NamedDecl *D = *R.first;
3213 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3214 isa<IndirectFieldDecl>(D)) {
3215 Diag(D->getLocation(), diag::err_member_name_of_class)
3216 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003217 break;
3218 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003219 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003220 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003221
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003222 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003223 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003224 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003225 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003226 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3227 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3228 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003229
3230 // See if a method overloads virtual methods in a base
3231 /// class without overriding any.
3232 if (!Record->isDependentType()) {
3233 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3234 MEnd = Record->method_end();
3235 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003236 if (!(*M)->isStatic())
3237 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003238 }
3239 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003240
3241 // Declare inherited constructors. We do this eagerly here because:
3242 // - The standard requires an eager diagnostic for conflicting inherited
3243 // constructors from different classes.
3244 // - The lazy declaration of the other implicit constructors is so as to not
3245 // waste space and performance on classes that are not meant to be
3246 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3247 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003248 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003249
Sean Hunteb88ae52011-05-23 21:07:59 +00003250 if (!Record->isDependentType())
3251 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003252}
3253
3254void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003255 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3256 ME = Record->method_end();
3257 MI != ME; ++MI) {
3258 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3259 switch (getSpecialMember(*MI)) {
3260 case CXXDefaultConstructor:
3261 CheckExplicitlyDefaultedDefaultConstructor(
3262 cast<CXXConstructorDecl>(*MI));
3263 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003264
Sean Huntcb45a0f2011-05-12 22:46:25 +00003265 case CXXDestructor:
3266 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3267 break;
3268
3269 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003270 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3271 break;
3272
Sean Huntcb45a0f2011-05-12 22:46:25 +00003273 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003274 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003275 break;
3276
Sean Hunt82713172011-05-25 23:16:36 +00003277 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003278 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003279 break;
3280
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003281 case CXXMoveAssignment:
3282 CheckExplicitlyDefaultedMoveAssignment(*MI);
3283 break;
3284
3285 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003286 llvm_unreachable("non-special member explicitly defaulted!");
3287 }
Sean Hunt001cad92011-05-10 00:49:42 +00003288 }
3289 }
3290
Sean Hunt001cad92011-05-10 00:49:42 +00003291}
3292
3293void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3294 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3295
3296 // Whether this was the first-declared instance of the constructor.
3297 // This affects whether we implicitly add an exception spec (and, eventually,
3298 // constexpr). It is also ill-formed to explicitly default a constructor such
3299 // that it would be deleted. (C++0x [decl.fct.def.default])
3300 bool First = CD == CD->getCanonicalDecl();
3301
Sean Hunt49634cf2011-05-13 06:10:58 +00003302 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003303 if (CD->getNumParams() != 0) {
3304 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3305 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003306 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003307 }
3308
3309 ImplicitExceptionSpecification Spec
3310 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3311 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003312 if (EPI.ExceptionSpecType == EST_Delayed) {
3313 // Exception specification depends on some deferred part of the class. We'll
3314 // try again when the class's definition has been fully processed.
3315 return;
3316 }
Sean Hunt001cad92011-05-10 00:49:42 +00003317 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3318 *ExceptionType = Context.getFunctionType(
3319 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3320
3321 if (CtorType->hasExceptionSpec()) {
3322 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003323 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003324 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003325 PDiag(),
3326 ExceptionType, SourceLocation(),
3327 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003328 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003329 }
3330 } else if (First) {
3331 // We set the declaration to have the computed exception spec here.
3332 // We know there are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003333 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003334 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3335 }
Sean Huntca46d132011-05-12 03:51:48 +00003336
Sean Hunt49634cf2011-05-13 06:10:58 +00003337 if (HadError) {
3338 CD->setInvalidDecl();
3339 return;
3340 }
3341
Sean Huntca46d132011-05-12 03:51:48 +00003342 if (ShouldDeleteDefaultConstructor(CD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003343 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003344 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003345 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003346 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003347 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003348 CD->setInvalidDecl();
3349 }
3350 }
3351}
3352
3353void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3354 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3355
3356 // Whether this was the first-declared instance of the constructor.
3357 bool First = CD == CD->getCanonicalDecl();
3358
3359 bool HadError = false;
3360 if (CD->getNumParams() != 1) {
3361 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3362 << CD->getSourceRange();
3363 HadError = true;
3364 }
3365
3366 ImplicitExceptionSpecification Spec(Context);
3367 bool Const;
3368 llvm::tie(Spec, Const) =
3369 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3370
3371 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3372 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3373 *ExceptionType = Context.getFunctionType(
3374 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3375
3376 // Check for parameter type matching.
3377 // This is a copy ctor so we know it's a cv-qualified reference to T.
3378 QualType ArgType = CtorType->getArgType(0);
3379 if (ArgType->getPointeeType().isVolatileQualified()) {
3380 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3381 HadError = true;
3382 }
3383 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3384 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3385 HadError = true;
3386 }
3387
3388 if (CtorType->hasExceptionSpec()) {
3389 if (CheckEquivalentExceptionSpec(
3390 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003391 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003392 PDiag(),
3393 ExceptionType, SourceLocation(),
3394 CtorType, CD->getLocation())) {
3395 HadError = true;
3396 }
3397 } else if (First) {
3398 // We set the declaration to have the computed exception spec here.
3399 // We duplicate the one parameter type.
Sean Hunt2b188082011-05-14 05:23:28 +00003400 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt49634cf2011-05-13 06:10:58 +00003401 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3402 }
3403
3404 if (HadError) {
3405 CD->setInvalidDecl();
3406 return;
3407 }
3408
3409 if (ShouldDeleteCopyConstructor(CD)) {
3410 if (First) {
3411 CD->setDeletedAsWritten();
3412 } else {
3413 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003414 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003415 CD->setInvalidDecl();
3416 }
Sean Huntca46d132011-05-12 03:51:48 +00003417 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003418}
Sean Hunt001cad92011-05-10 00:49:42 +00003419
Sean Hunt2b188082011-05-14 05:23:28 +00003420void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3421 assert(MD->isExplicitlyDefaulted());
3422
3423 // Whether this was the first-declared instance of the operator
3424 bool First = MD == MD->getCanonicalDecl();
3425
3426 bool HadError = false;
3427 if (MD->getNumParams() != 1) {
3428 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3429 << MD->getSourceRange();
3430 HadError = true;
3431 }
3432
3433 QualType ReturnType =
3434 MD->getType()->getAs<FunctionType>()->getResultType();
3435 if (!ReturnType->isLValueReferenceType() ||
3436 !Context.hasSameType(
3437 Context.getCanonicalType(ReturnType->getPointeeType()),
3438 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3439 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3440 HadError = true;
3441 }
3442
3443 ImplicitExceptionSpecification Spec(Context);
3444 bool Const;
3445 llvm::tie(Spec, Const) =
3446 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3447
3448 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3449 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3450 *ExceptionType = Context.getFunctionType(
3451 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3452
Sean Hunt2b188082011-05-14 05:23:28 +00003453 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003454 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00003455 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003456 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003457 } else {
3458 if (ArgType->getPointeeType().isVolatileQualified()) {
3459 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3460 HadError = true;
3461 }
3462 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3463 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3464 HadError = true;
3465 }
Sean Hunt2b188082011-05-14 05:23:28 +00003466 }
Sean Huntbe631222011-05-17 20:44:43 +00003467
Sean Hunt2b188082011-05-14 05:23:28 +00003468 if (OperType->getTypeQuals()) {
3469 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3470 HadError = true;
3471 }
3472
3473 if (OperType->hasExceptionSpec()) {
3474 if (CheckEquivalentExceptionSpec(
3475 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003476 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00003477 PDiag(),
3478 ExceptionType, SourceLocation(),
3479 OperType, MD->getLocation())) {
3480 HadError = true;
3481 }
3482 } else if (First) {
3483 // We set the declaration to have the computed exception spec here.
3484 // We duplicate the one parameter type.
3485 EPI.RefQualifier = OperType->getRefQualifier();
3486 EPI.ExtInfo = OperType->getExtInfo();
3487 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3488 }
3489
3490 if (HadError) {
3491 MD->setInvalidDecl();
3492 return;
3493 }
3494
3495 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3496 if (First) {
3497 MD->setDeletedAsWritten();
3498 } else {
3499 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003500 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00003501 MD->setInvalidDecl();
3502 }
3503 }
3504}
3505
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003506void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3507 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3508
3509 // Whether this was the first-declared instance of the constructor.
3510 bool First = CD == CD->getCanonicalDecl();
3511
3512 bool HadError = false;
3513 if (CD->getNumParams() != 1) {
3514 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3515 << CD->getSourceRange();
3516 HadError = true;
3517 }
3518
3519 ImplicitExceptionSpecification Spec(
3520 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3521
3522 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3523 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3524 *ExceptionType = Context.getFunctionType(
3525 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3526
3527 // Check for parameter type matching.
3528 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3529 QualType ArgType = CtorType->getArgType(0);
3530 if (ArgType->getPointeeType().isVolatileQualified()) {
3531 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3532 HadError = true;
3533 }
3534 if (ArgType->getPointeeType().isConstQualified()) {
3535 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3536 HadError = true;
3537 }
3538
3539 if (CtorType->hasExceptionSpec()) {
3540 if (CheckEquivalentExceptionSpec(
3541 PDiag(diag::err_incorrect_defaulted_exception_spec)
3542 << CXXMoveConstructor,
3543 PDiag(),
3544 ExceptionType, SourceLocation(),
3545 CtorType, CD->getLocation())) {
3546 HadError = true;
3547 }
3548 } else if (First) {
3549 // We set the declaration to have the computed exception spec here.
3550 // We duplicate the one parameter type.
3551 EPI.ExtInfo = CtorType->getExtInfo();
3552 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3553 }
3554
3555 if (HadError) {
3556 CD->setInvalidDecl();
3557 return;
3558 }
3559
3560 if (ShouldDeleteMoveConstructor(CD)) {
3561 if (First) {
3562 CD->setDeletedAsWritten();
3563 } else {
3564 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3565 << CXXMoveConstructor;
3566 CD->setInvalidDecl();
3567 }
3568 }
3569}
3570
3571void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3572 assert(MD->isExplicitlyDefaulted());
3573
3574 // Whether this was the first-declared instance of the operator
3575 bool First = MD == MD->getCanonicalDecl();
3576
3577 bool HadError = false;
3578 if (MD->getNumParams() != 1) {
3579 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3580 << MD->getSourceRange();
3581 HadError = true;
3582 }
3583
3584 QualType ReturnType =
3585 MD->getType()->getAs<FunctionType>()->getResultType();
3586 if (!ReturnType->isLValueReferenceType() ||
3587 !Context.hasSameType(
3588 Context.getCanonicalType(ReturnType->getPointeeType()),
3589 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3590 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
3591 HadError = true;
3592 }
3593
3594 ImplicitExceptionSpecification Spec(
3595 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
3596
3597 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3598 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3599 *ExceptionType = Context.getFunctionType(
3600 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3601
3602 QualType ArgType = OperType->getArgType(0);
3603 if (!ArgType->isRValueReferenceType()) {
3604 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
3605 HadError = true;
3606 } else {
3607 if (ArgType->getPointeeType().isVolatileQualified()) {
3608 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
3609 HadError = true;
3610 }
3611 if (ArgType->getPointeeType().isConstQualified()) {
3612 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
3613 HadError = true;
3614 }
3615 }
3616
3617 if (OperType->getTypeQuals()) {
3618 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
3619 HadError = true;
3620 }
3621
3622 if (OperType->hasExceptionSpec()) {
3623 if (CheckEquivalentExceptionSpec(
3624 PDiag(diag::err_incorrect_defaulted_exception_spec)
3625 << CXXMoveAssignment,
3626 PDiag(),
3627 ExceptionType, SourceLocation(),
3628 OperType, MD->getLocation())) {
3629 HadError = true;
3630 }
3631 } else if (First) {
3632 // We set the declaration to have the computed exception spec here.
3633 // We duplicate the one parameter type.
3634 EPI.RefQualifier = OperType->getRefQualifier();
3635 EPI.ExtInfo = OperType->getExtInfo();
3636 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3637 }
3638
3639 if (HadError) {
3640 MD->setInvalidDecl();
3641 return;
3642 }
3643
3644 if (ShouldDeleteMoveAssignmentOperator(MD)) {
3645 if (First) {
3646 MD->setDeletedAsWritten();
3647 } else {
3648 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3649 << CXXMoveAssignment;
3650 MD->setInvalidDecl();
3651 }
3652 }
3653}
3654
Sean Huntcb45a0f2011-05-12 22:46:25 +00003655void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3656 assert(DD->isExplicitlyDefaulted());
3657
3658 // Whether this was the first-declared instance of the destructor.
3659 bool First = DD == DD->getCanonicalDecl();
3660
3661 ImplicitExceptionSpecification Spec
3662 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3663 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3664 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3665 *ExceptionType = Context.getFunctionType(
3666 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3667
3668 if (DtorType->hasExceptionSpec()) {
3669 if (CheckEquivalentExceptionSpec(
3670 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003671 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00003672 PDiag(),
3673 ExceptionType, SourceLocation(),
3674 DtorType, DD->getLocation())) {
3675 DD->setInvalidDecl();
3676 return;
3677 }
3678 } else if (First) {
3679 // We set the declaration to have the computed exception spec here.
3680 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003681 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00003682 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3683 }
3684
3685 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003686 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003687 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003688 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003689 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003690 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003691 DD->setInvalidDecl();
3692 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003693 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003694}
3695
Sean Huntcdee3fe2011-05-11 22:34:38 +00003696bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3697 CXXRecordDecl *RD = CD->getParent();
3698 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003699 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003700 return false;
3701
Sean Hunt71a682f2011-05-18 03:41:58 +00003702 SourceLocation Loc = CD->getLocation();
3703
Sean Huntcdee3fe2011-05-11 22:34:38 +00003704 // Do access control from the constructor
3705 ContextRAII CtorContext(*this, CD);
3706
3707 bool Union = RD->isUnion();
3708 bool AllConst = true;
3709
Sean Huntcdee3fe2011-05-11 22:34:38 +00003710 // We do this because we should never actually use an anonymous
3711 // union's constructor.
3712 if (Union && RD->isAnonymousStructOrUnion())
3713 return false;
3714
3715 // FIXME: We should put some diagnostic logic right into this function.
3716
3717 // C++0x [class.ctor]/5
Sean Huntb320e0c2011-06-10 03:50:41 +00003718 // A defaulted default constructor for class X is defined as deleted if:
Sean Huntcdee3fe2011-05-11 22:34:38 +00003719
3720 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3721 BE = RD->bases_end();
3722 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003723 // We'll handle this one later
3724 if (BI->isVirtual())
3725 continue;
3726
Sean Huntcdee3fe2011-05-11 22:34:38 +00003727 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3728 assert(BaseDecl && "base isn't a CXXRecordDecl");
3729
3730 // -- any [direct base class] has a type with a destructor that is
Sean Huntb320e0c2011-06-10 03:50:41 +00003731 // deleted or inaccessible from the defaulted default constructor
Sean Huntcdee3fe2011-05-11 22:34:38 +00003732 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3733 if (BaseDtor->isDeleted())
3734 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003735 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003736 AR_accessible)
3737 return true;
3738
Sean Huntcdee3fe2011-05-11 22:34:38 +00003739 // -- any [direct base class either] has no default constructor or
3740 // overload resolution as applied to [its] default constructor
3741 // results in an ambiguity or in a function that is deleted or
3742 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003743 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3744 if (!BaseDefault || BaseDefault->isDeleted())
3745 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003746
Sean Huntb320e0c2011-06-10 03:50:41 +00003747 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3748 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003749 return true;
3750 }
3751
3752 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3753 BE = RD->vbases_end();
3754 BI != BE; ++BI) {
3755 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3756 assert(BaseDecl && "base isn't a CXXRecordDecl");
3757
3758 // -- any [virtual base class] has a type with a destructor that is
3759 // delete or inaccessible from the defaulted default constructor
3760 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3761 if (BaseDtor->isDeleted())
3762 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003763 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003764 AR_accessible)
3765 return true;
3766
3767 // -- any [virtual base class either] has no default constructor or
3768 // overload resolution as applied to [its] default constructor
3769 // results in an ambiguity or in a function that is deleted or
3770 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003771 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3772 if (!BaseDefault || BaseDefault->isDeleted())
3773 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003774
Sean Huntb320e0c2011-06-10 03:50:41 +00003775 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3776 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003777 return true;
3778 }
3779
3780 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3781 FE = RD->field_end();
3782 FI != FE; ++FI) {
Richard Smith7a614d82011-06-11 17:19:42 +00003783 if (FI->isInvalidDecl())
3784 continue;
3785
Sean Huntcdee3fe2011-05-11 22:34:38 +00003786 QualType FieldType = Context.getBaseElementType(FI->getType());
3787 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00003788
Sean Huntcdee3fe2011-05-11 22:34:38 +00003789 // -- any non-static data member with no brace-or-equal-initializer is of
3790 // reference type
Richard Smith7a614d82011-06-11 17:19:42 +00003791 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003792 return true;
3793
3794 // -- X is a union and all its variant members are of const-qualified type
3795 // (or array thereof)
3796 if (Union && !FieldType.isConstQualified())
3797 AllConst = false;
3798
3799 if (FieldRecord) {
3800 // -- X is a union-like class that has a variant member with a non-trivial
3801 // default constructor
3802 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3803 return true;
3804
3805 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3806 if (FieldDtor->isDeleted())
3807 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003808 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003809 AR_accessible)
3810 return true;
3811
3812 // -- any non-variant non-static data member of const-qualified type (or
3813 // array thereof) with no brace-or-equal-initializer does not have a
3814 // user-provided default constructor
3815 if (FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00003816 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00003817 !FieldRecord->hasUserProvidedDefaultConstructor())
3818 return true;
3819
3820 if (!Union && FieldRecord->isUnion() &&
3821 FieldRecord->isAnonymousStructOrUnion()) {
3822 // We're okay to reuse AllConst here since we only care about the
3823 // value otherwise if we're in a union.
3824 AllConst = true;
3825
3826 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3827 UE = FieldRecord->field_end();
3828 UI != UE; ++UI) {
3829 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3830 CXXRecordDecl *UnionFieldRecord =
3831 UnionFieldType->getAsCXXRecordDecl();
3832
3833 if (!UnionFieldType.isConstQualified())
3834 AllConst = false;
3835
3836 if (UnionFieldRecord &&
3837 !UnionFieldRecord->hasTrivialDefaultConstructor())
3838 return true;
3839 }
Sean Hunt2be7e902011-05-12 22:46:29 +00003840
Sean Huntcdee3fe2011-05-11 22:34:38 +00003841 if (AllConst)
3842 return true;
3843
3844 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00003845 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00003846 continue;
3847 }
Sean Huntb320e0c2011-06-10 03:50:41 +00003848
Richard Smith7a614d82011-06-11 17:19:42 +00003849 // -- any non-static data member with no brace-or-equal-initializer has
3850 // class type M (or array thereof) and either M has no default
3851 // constructor or overload resolution as applied to M's default
3852 // constructor results in an ambiguity or in a function that is deleted
3853 // or inaccessible from the defaulted default constructor.
3854 if (!FI->hasInClassInitializer()) {
3855 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3856 if (!FieldDefault || FieldDefault->isDeleted())
3857 return true;
3858 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3859 PDiag()) != AR_accessible)
3860 return true;
3861 }
3862 } else if (!Union && FieldType.isConstQualified() &&
3863 !FI->hasInClassInitializer()) {
Sean Hunte3406822011-05-20 21:43:47 +00003864 // -- any non-variant non-static data member of const-qualified type (or
3865 // array thereof) with no brace-or-equal-initializer does not have a
3866 // user-provided default constructor
3867 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003868 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003869 }
3870
3871 if (Union && AllConst)
3872 return true;
3873
3874 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003875}
3876
Sean Hunt49634cf2011-05-13 06:10:58 +00003877bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Sean Hunt493ff722011-05-18 20:57:13 +00003878 CXXRecordDecl *RD = CD->getParent();
Sean Hunt49634cf2011-05-13 06:10:58 +00003879 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003880 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt49634cf2011-05-13 06:10:58 +00003881 return false;
3882
Sean Hunt71a682f2011-05-18 03:41:58 +00003883 SourceLocation Loc = CD->getLocation();
3884
Sean Hunt49634cf2011-05-13 06:10:58 +00003885 // Do access control from the constructor
3886 ContextRAII CtorContext(*this, CD);
3887
Sean Huntc530d172011-06-10 04:44:37 +00003888 bool Union = RD->isUnion();
Sean Hunt49634cf2011-05-13 06:10:58 +00003889
Sean Hunt2b188082011-05-14 05:23:28 +00003890 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3891 "copy assignment arg has no pointee type");
Sean Huntc530d172011-06-10 04:44:37 +00003892 unsigned ArgQuals =
3893 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3894 Qualifiers::Const : 0;
Sean Hunt49634cf2011-05-13 06:10:58 +00003895
3896 // We do this because we should never actually use an anonymous
3897 // union's constructor.
3898 if (Union && RD->isAnonymousStructOrUnion())
3899 return false;
3900
3901 // FIXME: We should put some diagnostic logic right into this function.
3902
3903 // C++0x [class.copy]/11
3904 // A defaulted [copy] constructor for class X is defined as delete if X has:
3905
3906 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3907 BE = RD->bases_end();
3908 BI != BE; ++BI) {
3909 // We'll handle this one later
3910 if (BI->isVirtual())
3911 continue;
3912
3913 QualType BaseType = BI->getType();
3914 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3915 assert(BaseDecl && "base isn't a CXXRecordDecl");
3916
3917 // -- any [direct base class] of a type with a destructor that is deleted or
3918 // inaccessible from the defaulted constructor
3919 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3920 if (BaseDtor->isDeleted())
3921 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003922 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003923 AR_accessible)
3924 return true;
3925
3926 // -- a [direct base class] B that cannot be [copied] because overload
3927 // resolution, as applied to B's [copy] constructor, results in an
3928 // ambiguity or a function that is deleted or inaccessible from the
3929 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003930 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003931 if (!BaseCtor || BaseCtor->isDeleted())
3932 return true;
3933 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3934 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003935 return true;
3936 }
3937
3938 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3939 BE = RD->vbases_end();
3940 BI != BE; ++BI) {
3941 QualType BaseType = BI->getType();
3942 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3943 assert(BaseDecl && "base isn't a CXXRecordDecl");
3944
Sean Huntb320e0c2011-06-10 03:50:41 +00003945 // -- any [virtual base class] of a type with a destructor that is deleted or
Sean Hunt49634cf2011-05-13 06:10:58 +00003946 // inaccessible from the defaulted constructor
3947 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3948 if (BaseDtor->isDeleted())
3949 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003950 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003951 AR_accessible)
3952 return true;
3953
3954 // -- a [virtual base class] B that cannot be [copied] because overload
3955 // resolution, as applied to B's [copy] constructor, results in an
3956 // ambiguity or a function that is deleted or inaccessible from the
3957 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003958 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003959 if (!BaseCtor || BaseCtor->isDeleted())
3960 return true;
3961 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3962 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003963 return true;
3964 }
3965
3966 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3967 FE = RD->field_end();
3968 FI != FE; ++FI) {
3969 QualType FieldType = Context.getBaseElementType(FI->getType());
3970
3971 // -- for a copy constructor, a non-static data member of rvalue reference
3972 // type
3973 if (FieldType->isRValueReferenceType())
3974 return true;
3975
3976 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3977
3978 if (FieldRecord) {
3979 // This is an anonymous union
3980 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3981 // Anonymous unions inside unions do not variant members create
3982 if (!Union) {
3983 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3984 UE = FieldRecord->field_end();
3985 UI != UE; ++UI) {
3986 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3987 CXXRecordDecl *UnionFieldRecord =
3988 UnionFieldType->getAsCXXRecordDecl();
3989
3990 // -- a variant member with a non-trivial [copy] constructor and X
3991 // is a union-like class
3992 if (UnionFieldRecord &&
3993 !UnionFieldRecord->hasTrivialCopyConstructor())
3994 return true;
3995 }
3996 }
3997
3998 // Don't try to initalize an anonymous union
3999 continue;
4000 } else {
4001 // -- a variant member with a non-trivial [copy] constructor and X is a
4002 // union-like class
4003 if (Union && !FieldRecord->hasTrivialCopyConstructor())
4004 return true;
4005
4006 // -- any [non-static data member] of a type with a destructor that is
4007 // deleted or inaccessible from the defaulted constructor
4008 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4009 if (FieldDtor->isDeleted())
4010 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004011 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00004012 AR_accessible)
4013 return true;
4014 }
Sean Huntc530d172011-06-10 04:44:37 +00004015
4016 // -- a [non-static data member of class type (or array thereof)] B that
4017 // cannot be [copied] because overload resolution, as applied to B's
4018 // [copy] constructor, results in an ambiguity or a function that is
4019 // deleted or inaccessible from the defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00004020 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
4021 ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00004022 if (!FieldCtor || FieldCtor->isDeleted())
4023 return true;
4024 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4025 PDiag()) != AR_accessible)
4026 return true;
Sean Hunt49634cf2011-05-13 06:10:58 +00004027 }
Sean Hunt49634cf2011-05-13 06:10:58 +00004028 }
4029
4030 return false;
4031}
4032
Sean Hunt7f410192011-05-14 05:23:24 +00004033bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4034 CXXRecordDecl *RD = MD->getParent();
4035 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004036 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004037 return false;
4038
Sean Hunt71a682f2011-05-18 03:41:58 +00004039 SourceLocation Loc = MD->getLocation();
4040
Sean Hunt7f410192011-05-14 05:23:24 +00004041 // Do access control from the constructor
4042 ContextRAII MethodContext(*this, MD);
4043
4044 bool Union = RD->isUnion();
4045
Sean Hunt661c67a2011-06-21 23:42:56 +00004046 unsigned ArgQuals =
4047 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4048 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004049
4050 // We do this because we should never actually use an anonymous
4051 // union's constructor.
4052 if (Union && RD->isAnonymousStructOrUnion())
4053 return false;
4054
Sean Hunt7f410192011-05-14 05:23:24 +00004055 // FIXME: We should put some diagnostic logic right into this function.
4056
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004057 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004058 // A defaulted [copy] assignment operator for class X is defined as deleted
4059 // if X has:
4060
4061 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4062 BE = RD->bases_end();
4063 BI != BE; ++BI) {
4064 // We'll handle this one later
4065 if (BI->isVirtual())
4066 continue;
4067
4068 QualType BaseType = BI->getType();
4069 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4070 assert(BaseDecl && "base isn't a CXXRecordDecl");
4071
4072 // -- a [direct base class] B that cannot be [copied] because overload
4073 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004074 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004075 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004076 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4077 0);
4078 if (!CopyOper || CopyOper->isDeleted())
4079 return true;
4080 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004081 return true;
4082 }
4083
4084 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4085 BE = RD->vbases_end();
4086 BI != BE; ++BI) {
4087 QualType BaseType = BI->getType();
4088 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4089 assert(BaseDecl && "base isn't a CXXRecordDecl");
4090
Sean Hunt7f410192011-05-14 05:23:24 +00004091 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004092 // resolution, as applied to B's [copy] assignment operator, results in
4093 // an ambiguity or a function that is deleted or inaccessible from the
4094 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004095 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4096 0);
4097 if (!CopyOper || CopyOper->isDeleted())
4098 return true;
4099 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004100 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004101 }
4102
4103 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4104 FE = RD->field_end();
4105 FI != FE; ++FI) {
4106 QualType FieldType = Context.getBaseElementType(FI->getType());
4107
4108 // -- a non-static data member of reference type
4109 if (FieldType->isReferenceType())
4110 return true;
4111
4112 // -- a non-static data member of const non-class type (or array thereof)
4113 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4114 return true;
4115
4116 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4117
4118 if (FieldRecord) {
4119 // This is an anonymous union
4120 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4121 // Anonymous unions inside unions do not variant members create
4122 if (!Union) {
4123 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4124 UE = FieldRecord->field_end();
4125 UI != UE; ++UI) {
4126 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4127 CXXRecordDecl *UnionFieldRecord =
4128 UnionFieldType->getAsCXXRecordDecl();
4129
4130 // -- a variant member with a non-trivial [copy] assignment operator
4131 // and X is a union-like class
4132 if (UnionFieldRecord &&
4133 !UnionFieldRecord->hasTrivialCopyAssignment())
4134 return true;
4135 }
4136 }
4137
4138 // Don't try to initalize an anonymous union
4139 continue;
4140 // -- a variant member with a non-trivial [copy] assignment operator
4141 // and X is a union-like class
4142 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4143 return true;
4144 }
Sean Hunt7f410192011-05-14 05:23:24 +00004145
Sean Hunt661c67a2011-06-21 23:42:56 +00004146 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4147 false, 0);
4148 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004149 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004150 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004151 return true;
4152 }
4153 }
4154
4155 return false;
4156}
4157
4158bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) {
4159 CXXRecordDecl *RD = CD->getParent();
4160 assert(!RD->isDependentType() && "do deletion after instantiation");
4161 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4162 return false;
4163
4164 SourceLocation Loc = CD->getLocation();
4165
4166 // Do access control from the constructor
4167 ContextRAII CtorContext(*this, CD);
4168
4169 bool Union = RD->isUnion();
4170
4171 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4172 "copy assignment arg has no pointee type");
4173
4174 // We do this because we should never actually use an anonymous
4175 // union's constructor.
4176 if (Union && RD->isAnonymousStructOrUnion())
4177 return false;
4178
4179 // C++0x [class.copy]/11
4180 // A defaulted [move] constructor for class X is defined as deleted
4181 // if X has:
4182
4183 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4184 BE = RD->bases_end();
4185 BI != BE; ++BI) {
4186 // We'll handle this one later
4187 if (BI->isVirtual())
4188 continue;
4189
4190 QualType BaseType = BI->getType();
4191 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4192 assert(BaseDecl && "base isn't a CXXRecordDecl");
4193
4194 // -- any [direct base class] of a type with a destructor that is deleted or
4195 // inaccessible from the defaulted constructor
4196 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4197 if (BaseDtor->isDeleted())
4198 return true;
4199 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4200 AR_accessible)
4201 return true;
4202
4203 // -- a [direct base class] B that cannot be [moved] because overload
4204 // resolution, as applied to B's [move] constructor, results in an
4205 // ambiguity or a function that is deleted or inaccessible from the
4206 // defaulted constructor
4207 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4208 if (!BaseCtor || BaseCtor->isDeleted())
4209 return true;
4210 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4211 AR_accessible)
4212 return true;
4213
4214 // -- for a move constructor, a [direct base class] with a type that
4215 // does not have a move constructor and is not trivially copyable.
4216 // If the field isn't a record, it's always trivially copyable.
4217 // A moving constructor could be a copy constructor instead.
4218 if (!BaseCtor->isMoveConstructor() &&
4219 !BaseDecl->isTriviallyCopyable())
4220 return true;
4221 }
4222
4223 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4224 BE = RD->vbases_end();
4225 BI != BE; ++BI) {
4226 QualType BaseType = BI->getType();
4227 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4228 assert(BaseDecl && "base isn't a CXXRecordDecl");
4229
4230 // -- any [virtual base class] of a type with a destructor that is deleted
4231 // or inaccessible from the defaulted constructor
4232 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4233 if (BaseDtor->isDeleted())
4234 return true;
4235 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4236 AR_accessible)
4237 return true;
4238
4239 // -- a [virtual base class] B that cannot be [moved] because overload
4240 // resolution, as applied to B's [move] constructor, results in an
4241 // ambiguity or a function that is deleted or inaccessible from the
4242 // defaulted constructor
4243 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4244 if (!BaseCtor || BaseCtor->isDeleted())
4245 return true;
4246 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4247 AR_accessible)
4248 return true;
4249
4250 // -- for a move constructor, a [virtual base class] with a type that
4251 // does not have a move constructor and is not trivially copyable.
4252 // If the field isn't a record, it's always trivially copyable.
4253 // A moving constructor could be a copy constructor instead.
4254 if (!BaseCtor->isMoveConstructor() &&
4255 !BaseDecl->isTriviallyCopyable())
4256 return true;
4257 }
4258
4259 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4260 FE = RD->field_end();
4261 FI != FE; ++FI) {
4262 QualType FieldType = Context.getBaseElementType(FI->getType());
4263
4264 if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) {
4265 // This is an anonymous union
4266 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4267 // Anonymous unions inside unions do not variant members create
4268 if (!Union) {
4269 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4270 UE = FieldRecord->field_end();
4271 UI != UE; ++UI) {
4272 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4273 CXXRecordDecl *UnionFieldRecord =
4274 UnionFieldType->getAsCXXRecordDecl();
4275
4276 // -- a variant member with a non-trivial [move] constructor and X
4277 // is a union-like class
4278 if (UnionFieldRecord &&
4279 !UnionFieldRecord->hasTrivialMoveConstructor())
4280 return true;
4281 }
4282 }
4283
4284 // Don't try to initalize an anonymous union
4285 continue;
4286 } else {
4287 // -- a variant member with a non-trivial [move] constructor and X is a
4288 // union-like class
4289 if (Union && !FieldRecord->hasTrivialMoveConstructor())
4290 return true;
4291
4292 // -- any [non-static data member] of a type with a destructor that is
4293 // deleted or inaccessible from the defaulted constructor
4294 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4295 if (FieldDtor->isDeleted())
4296 return true;
4297 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4298 AR_accessible)
4299 return true;
4300 }
4301
4302 // -- a [non-static data member of class type (or array thereof)] B that
4303 // cannot be [moved] because overload resolution, as applied to B's
4304 // [move] constructor, results in an ambiguity or a function that is
4305 // deleted or inaccessible from the defaulted constructor
4306 CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord);
4307 if (!FieldCtor || FieldCtor->isDeleted())
4308 return true;
4309 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4310 PDiag()) != AR_accessible)
4311 return true;
4312
4313 // -- for a move constructor, a [non-static data member] with a type that
4314 // does not have a move constructor and is not trivially copyable.
4315 // If the field isn't a record, it's always trivially copyable.
4316 // A moving constructor could be a copy constructor instead.
4317 if (!FieldCtor->isMoveConstructor() &&
4318 !FieldRecord->isTriviallyCopyable())
4319 return true;
4320 }
4321 }
4322
4323 return false;
4324}
4325
4326bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4327 CXXRecordDecl *RD = MD->getParent();
4328 assert(!RD->isDependentType() && "do deletion after instantiation");
4329 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4330 return false;
4331
4332 SourceLocation Loc = MD->getLocation();
4333
4334 // Do access control from the constructor
4335 ContextRAII MethodContext(*this, MD);
4336
4337 bool Union = RD->isUnion();
4338
4339 // We do this because we should never actually use an anonymous
4340 // union's constructor.
4341 if (Union && RD->isAnonymousStructOrUnion())
4342 return false;
4343
4344 // C++0x [class.copy]/20
4345 // A defaulted [move] assignment operator for class X is defined as deleted
4346 // if X has:
4347
4348 // -- for the move constructor, [...] any direct or indirect virtual base
4349 // class.
4350 if (RD->getNumVBases() != 0)
4351 return true;
4352
4353 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4354 BE = RD->bases_end();
4355 BI != BE; ++BI) {
4356
4357 QualType BaseType = BI->getType();
4358 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4359 assert(BaseDecl && "base isn't a CXXRecordDecl");
4360
4361 // -- a [direct base class] B that cannot be [moved] because overload
4362 // resolution, as applied to B's [move] assignment operator, results in
4363 // an ambiguity or a function that is deleted or inaccessible from the
4364 // assignment operator
4365 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4366 if (!MoveOper || MoveOper->isDeleted())
4367 return true;
4368 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4369 return true;
4370
4371 // -- for the move assignment operator, a [direct base class] with a type
4372 // that does not have a move assignment operator and is not trivially
4373 // copyable.
4374 if (!MoveOper->isMoveAssignmentOperator() &&
4375 !BaseDecl->isTriviallyCopyable())
4376 return true;
4377 }
4378
4379 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4380 FE = RD->field_end();
4381 FI != FE; ++FI) {
4382 QualType FieldType = Context.getBaseElementType(FI->getType());
4383
4384 // -- a non-static data member of reference type
4385 if (FieldType->isReferenceType())
4386 return true;
4387
4388 // -- a non-static data member of const non-class type (or array thereof)
4389 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4390 return true;
4391
4392 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4393
4394 if (FieldRecord) {
4395 // This is an anonymous union
4396 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4397 // Anonymous unions inside unions do not variant members create
4398 if (!Union) {
4399 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4400 UE = FieldRecord->field_end();
4401 UI != UE; ++UI) {
4402 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4403 CXXRecordDecl *UnionFieldRecord =
4404 UnionFieldType->getAsCXXRecordDecl();
4405
4406 // -- a variant member with a non-trivial [move] assignment operator
4407 // and X is a union-like class
4408 if (UnionFieldRecord &&
4409 !UnionFieldRecord->hasTrivialMoveAssignment())
4410 return true;
4411 }
4412 }
4413
4414 // Don't try to initalize an anonymous union
4415 continue;
4416 // -- a variant member with a non-trivial [move] assignment operator
4417 // and X is a union-like class
4418 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4419 return true;
4420 }
4421
4422 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4423 if (!MoveOper || MoveOper->isDeleted())
4424 return true;
4425 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4426 return true;
4427
4428 // -- for the move assignment operator, a [non-static data member] with a
4429 // type that does not have a move assignment operator and is not
4430 // trivially copyable.
4431 if (!MoveOper->isMoveAssignmentOperator() &&
4432 !FieldRecord->isTriviallyCopyable())
4433 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004434 }
Sean Hunt7f410192011-05-14 05:23:24 +00004435 }
4436
4437 return false;
4438}
4439
Sean Huntcb45a0f2011-05-12 22:46:25 +00004440bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4441 CXXRecordDecl *RD = DD->getParent();
4442 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004443 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004444 return false;
4445
Sean Hunt71a682f2011-05-18 03:41:58 +00004446 SourceLocation Loc = DD->getLocation();
4447
Sean Huntcb45a0f2011-05-12 22:46:25 +00004448 // Do access control from the destructor
4449 ContextRAII CtorContext(*this, DD);
4450
4451 bool Union = RD->isUnion();
4452
Sean Hunt49634cf2011-05-13 06:10:58 +00004453 // We do this because we should never actually use an anonymous
4454 // union's destructor.
4455 if (Union && RD->isAnonymousStructOrUnion())
4456 return false;
4457
Sean Huntcb45a0f2011-05-12 22:46:25 +00004458 // C++0x [class.dtor]p5
4459 // A defaulted destructor for a class X is defined as deleted if:
4460 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4461 BE = RD->bases_end();
4462 BI != BE; ++BI) {
4463 // We'll handle this one later
4464 if (BI->isVirtual())
4465 continue;
4466
4467 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4468 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4469 assert(BaseDtor && "base has no destructor");
4470
4471 // -- any direct or virtual base class has a deleted destructor or
4472 // a destructor that is inaccessible from the defaulted destructor
4473 if (BaseDtor->isDeleted())
4474 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004475 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004476 AR_accessible)
4477 return true;
4478 }
4479
4480 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4481 BE = RD->vbases_end();
4482 BI != BE; ++BI) {
4483 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4484 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4485 assert(BaseDtor && "base has no destructor");
4486
4487 // -- any direct or virtual base class has a deleted destructor or
4488 // a destructor that is inaccessible from the defaulted destructor
4489 if (BaseDtor->isDeleted())
4490 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004491 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004492 AR_accessible)
4493 return true;
4494 }
4495
4496 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4497 FE = RD->field_end();
4498 FI != FE; ++FI) {
4499 QualType FieldType = Context.getBaseElementType(FI->getType());
4500 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4501 if (FieldRecord) {
4502 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4503 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4504 UE = FieldRecord->field_end();
4505 UI != UE; ++UI) {
4506 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4507 CXXRecordDecl *UnionFieldRecord =
4508 UnionFieldType->getAsCXXRecordDecl();
4509
4510 // -- X is a union-like class that has a variant member with a non-
4511 // trivial destructor.
4512 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4513 return true;
4514 }
4515 // Technically we are supposed to do this next check unconditionally.
4516 // But that makes absolutely no sense.
4517 } else {
4518 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4519
4520 // -- any of the non-static data members has class type M (or array
4521 // thereof) and M has a deleted destructor or a destructor that is
4522 // inaccessible from the defaulted destructor
4523 if (FieldDtor->isDeleted())
4524 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004525 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004526 AR_accessible)
4527 return true;
4528
4529 // -- X is a union-like class that has a variant member with a non-
4530 // trivial destructor.
4531 if (Union && !FieldDtor->isTrivial())
4532 return true;
4533 }
4534 }
4535 }
4536
4537 if (DD->isVirtual()) {
4538 FunctionDecl *OperatorDelete = 0;
4539 DeclarationName Name =
4540 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004541 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004542 false))
4543 return true;
4544 }
4545
4546
4547 return false;
4548}
4549
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004550/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004551namespace {
4552 struct FindHiddenVirtualMethodData {
4553 Sema *S;
4554 CXXMethodDecl *Method;
4555 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004556 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004557 };
4558}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004559
4560/// \brief Member lookup function that determines whether a given C++
4561/// method overloads virtual methods in a base class without overriding any,
4562/// to be used with CXXRecordDecl::lookupInBases().
4563static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4564 CXXBasePath &Path,
4565 void *UserData) {
4566 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4567
4568 FindHiddenVirtualMethodData &Data
4569 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4570
4571 DeclarationName Name = Data.Method->getDeclName();
4572 assert(Name.getNameKind() == DeclarationName::Identifier);
4573
4574 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004575 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004576 for (Path.Decls = BaseRecord->lookup(Name);
4577 Path.Decls.first != Path.Decls.second;
4578 ++Path.Decls.first) {
4579 NamedDecl *D = *Path.Decls.first;
4580 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004581 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004582 foundSameNameMethod = true;
4583 // Interested only in hidden virtual methods.
4584 if (!MD->isVirtual())
4585 continue;
4586 // If the method we are checking overrides a method from its base
4587 // don't warn about the other overloaded methods.
4588 if (!Data.S->IsOverload(Data.Method, MD, false))
4589 return true;
4590 // Collect the overload only if its hidden.
4591 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4592 overloadedMethods.push_back(MD);
4593 }
4594 }
4595
4596 if (foundSameNameMethod)
4597 Data.OverloadedMethods.append(overloadedMethods.begin(),
4598 overloadedMethods.end());
4599 return foundSameNameMethod;
4600}
4601
4602/// \brief See if a method overloads virtual methods in a base class without
4603/// overriding any.
4604void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4605 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4606 MD->getLocation()) == Diagnostic::Ignored)
4607 return;
4608 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4609 return;
4610
4611 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4612 /*bool RecordPaths=*/false,
4613 /*bool DetectVirtual=*/false);
4614 FindHiddenVirtualMethodData Data;
4615 Data.Method = MD;
4616 Data.S = this;
4617
4618 // Keep the base methods that were overriden or introduced in the subclass
4619 // by 'using' in a set. A base method not in this set is hidden.
4620 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4621 res.first != res.second; ++res.first) {
4622 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4623 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4624 E = MD->end_overridden_methods();
4625 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004626 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004627 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4628 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004629 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004630 }
4631
4632 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4633 !Data.OverloadedMethods.empty()) {
4634 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4635 << MD << (Data.OverloadedMethods.size() > 1);
4636
4637 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4638 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4639 Diag(overloadedMD->getLocation(),
4640 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4641 }
4642 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004643}
4644
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004645void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004646 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004647 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004648 SourceLocation RBrac,
4649 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004650 if (!TagDecl)
4651 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004652
Douglas Gregor42af25f2009-05-11 19:58:34 +00004653 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004654
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004655 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00004656 // strict aliasing violation!
4657 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004658 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004659
Douglas Gregor23c94db2010-07-02 17:43:08 +00004660 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004661 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004662}
4663
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004664/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4665/// special functions, such as the default constructor, copy
4666/// constructor, or destructor, to the given C++ class (C++
4667/// [special]p1). This routine can only be executed just before the
4668/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004669void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004670 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004671 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004672
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004673 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004674 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004675
Douglas Gregora376d102010-07-02 21:50:04 +00004676 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4677 ++ASTContext::NumImplicitCopyAssignmentOperators;
4678
4679 // If we have a dynamic class, then the copy assignment operator may be
4680 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4681 // it shows up in the right place in the vtable and that we diagnose
4682 // problems with the implicit exception specification.
4683 if (ClassDecl->isDynamicClass())
4684 DeclareImplicitCopyAssignment(ClassDecl);
4685 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004686
Douglas Gregor4923aa22010-07-02 20:37:36 +00004687 if (!ClassDecl->hasUserDeclaredDestructor()) {
4688 ++ASTContext::NumImplicitDestructors;
4689
4690 // If we have a dynamic class, then the destructor may be virtual, so we
4691 // have to declare the destructor immediately. This ensures that, e.g., it
4692 // shows up in the right place in the vtable and that we diagnose problems
4693 // with the implicit exception specification.
4694 if (ClassDecl->isDynamicClass())
4695 DeclareImplicitDestructor(ClassDecl);
4696 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004697}
4698
Francois Pichet8387e2a2011-04-22 22:18:13 +00004699void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4700 if (!D)
4701 return;
4702
4703 int NumParamList = D->getNumTemplateParameterLists();
4704 for (int i = 0; i < NumParamList; i++) {
4705 TemplateParameterList* Params = D->getTemplateParameterList(i);
4706 for (TemplateParameterList::iterator Param = Params->begin(),
4707 ParamEnd = Params->end();
4708 Param != ParamEnd; ++Param) {
4709 NamedDecl *Named = cast<NamedDecl>(*Param);
4710 if (Named->getDeclName()) {
4711 S->AddDecl(Named);
4712 IdResolver.AddDecl(Named);
4713 }
4714 }
4715 }
4716}
4717
John McCalld226f652010-08-21 09:40:31 +00004718void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004719 if (!D)
4720 return;
4721
4722 TemplateParameterList *Params = 0;
4723 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4724 Params = Template->getTemplateParameters();
4725 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4726 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4727 Params = PartialSpec->getTemplateParameters();
4728 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004729 return;
4730
Douglas Gregor6569d682009-05-27 23:11:45 +00004731 for (TemplateParameterList::iterator Param = Params->begin(),
4732 ParamEnd = Params->end();
4733 Param != ParamEnd; ++Param) {
4734 NamedDecl *Named = cast<NamedDecl>(*Param);
4735 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004736 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004737 IdResolver.AddDecl(Named);
4738 }
4739 }
4740}
4741
John McCalld226f652010-08-21 09:40:31 +00004742void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004743 if (!RecordD) return;
4744 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004745 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004746 PushDeclContext(S, Record);
4747}
4748
John McCalld226f652010-08-21 09:40:31 +00004749void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004750 if (!RecordD) return;
4751 PopDeclContext();
4752}
4753
Douglas Gregor72b505b2008-12-16 21:30:33 +00004754/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4755/// parsing a top-level (non-nested) C++ class, and we are now
4756/// parsing those parts of the given Method declaration that could
4757/// not be parsed earlier (C++ [class.mem]p2), such as default
4758/// arguments. This action should enter the scope of the given
4759/// Method declaration as if we had just parsed the qualified method
4760/// name. However, it should not bring the parameters into scope;
4761/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004762void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004763}
4764
4765/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4766/// C++ method declaration. We're (re-)introducing the given
4767/// function parameter into scope for use in parsing later parts of
4768/// the method declaration. For example, we could see an
4769/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004770void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004771 if (!ParamD)
4772 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004773
John McCalld226f652010-08-21 09:40:31 +00004774 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004775
4776 // If this parameter has an unparsed default argument, clear it out
4777 // to make way for the parsed default argument.
4778 if (Param->hasUnparsedDefaultArg())
4779 Param->setDefaultArg(0);
4780
John McCalld226f652010-08-21 09:40:31 +00004781 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004782 if (Param->getDeclName())
4783 IdResolver.AddDecl(Param);
4784}
4785
4786/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4787/// processing the delayed method declaration for Method. The method
4788/// declaration is now considered finished. There may be a separate
4789/// ActOnStartOfFunctionDef action later (not necessarily
4790/// immediately!) for this method, if it was also defined inside the
4791/// class body.
John McCalld226f652010-08-21 09:40:31 +00004792void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004793 if (!MethodD)
4794 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004795
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004796 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004797
John McCalld226f652010-08-21 09:40:31 +00004798 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004799
4800 // Now that we have our default arguments, check the constructor
4801 // again. It could produce additional diagnostics or affect whether
4802 // the class has implicitly-declared destructors, among other
4803 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004804 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4805 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004806
4807 // Check the default arguments, which we may have added.
4808 if (!Method->isInvalidDecl())
4809 CheckCXXDefaultArguments(Method);
4810}
4811
Douglas Gregor42a552f2008-11-05 20:51:48 +00004812/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004813/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004814/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004815/// emit diagnostics and set the invalid bit to true. In any case, the type
4816/// will be updated to reflect a well-formed type for the constructor and
4817/// returned.
4818QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004819 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004820 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004821
4822 // C++ [class.ctor]p3:
4823 // A constructor shall not be virtual (10.3) or static (9.4). A
4824 // constructor can be invoked for a const, volatile or const
4825 // volatile object. A constructor shall not be declared const,
4826 // volatile, or const volatile (9.3.2).
4827 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004828 if (!D.isInvalidType())
4829 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4830 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4831 << SourceRange(D.getIdentifierLoc());
4832 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004833 }
John McCalld931b082010-08-26 03:08:43 +00004834 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004835 if (!D.isInvalidType())
4836 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4837 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4838 << SourceRange(D.getIdentifierLoc());
4839 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004840 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004841 }
Mike Stump1eb44332009-09-09 15:08:12 +00004842
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004843 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004844 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004845 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004846 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4847 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004848 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004849 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4850 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004851 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004852 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4853 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004854 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004855 }
Mike Stump1eb44332009-09-09 15:08:12 +00004856
Douglas Gregorc938c162011-01-26 05:01:58 +00004857 // C++0x [class.ctor]p4:
4858 // A constructor shall not be declared with a ref-qualifier.
4859 if (FTI.hasRefQualifier()) {
4860 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4861 << FTI.RefQualifierIsLValueRef
4862 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4863 D.setInvalidType();
4864 }
4865
Douglas Gregor42a552f2008-11-05 20:51:48 +00004866 // Rebuild the function type "R" without any type qualifiers (in
4867 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004868 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004869 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004870 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4871 return R;
4872
4873 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4874 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004875 EPI.RefQualifier = RQ_None;
4876
Chris Lattner65401802009-04-25 08:28:21 +00004877 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004878 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004879}
4880
Douglas Gregor72b505b2008-12-16 21:30:33 +00004881/// CheckConstructor - Checks a fully-formed constructor for
4882/// well-formedness, issuing any diagnostics required. Returns true if
4883/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004884void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004885 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004886 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4887 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004888 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004889
4890 // C++ [class.copy]p3:
4891 // A declaration of a constructor for a class X is ill-formed if
4892 // its first parameter is of type (optionally cv-qualified) X and
4893 // either there are no other parameters or else all other
4894 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004895 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004896 ((Constructor->getNumParams() == 1) ||
4897 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004898 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4899 Constructor->getTemplateSpecializationKind()
4900 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004901 QualType ParamType = Constructor->getParamDecl(0)->getType();
4902 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4903 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00004904 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004905 const char *ConstRef
4906 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4907 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00004908 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004909 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00004910
4911 // FIXME: Rather that making the constructor invalid, we should endeavor
4912 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00004913 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004914 }
4915 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00004916}
4917
John McCall15442822010-08-04 01:04:25 +00004918/// CheckDestructor - Checks a fully-formed destructor definition for
4919/// well-formedness, issuing any diagnostics required. Returns true
4920/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004921bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00004922 CXXRecordDecl *RD = Destructor->getParent();
4923
4924 if (Destructor->isVirtual()) {
4925 SourceLocation Loc;
4926
4927 if (!Destructor->isImplicit())
4928 Loc = Destructor->getLocation();
4929 else
4930 Loc = RD->getLocation();
4931
4932 // If we have a virtual destructor, look up the deallocation function
4933 FunctionDecl *OperatorDelete = 0;
4934 DeclarationName Name =
4935 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004936 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00004937 return true;
John McCall5efd91a2010-07-03 18:33:00 +00004938
4939 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00004940
4941 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00004942 }
Anders Carlsson37909802009-11-30 21:24:50 +00004943
4944 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00004945}
4946
Mike Stump1eb44332009-09-09 15:08:12 +00004947static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004948FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4949 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4950 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00004951 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004952}
4953
Douglas Gregor42a552f2008-11-05 20:51:48 +00004954/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4955/// the well-formednes of the destructor declarator @p D with type @p
4956/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004957/// emit diagnostics and set the declarator to invalid. Even if this happens,
4958/// will be updated to reflect a well-formed type for the destructor and
4959/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00004960QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004961 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004962 // C++ [class.dtor]p1:
4963 // [...] A typedef-name that names a class is a class-name
4964 // (7.1.3); however, a typedef-name that names a class shall not
4965 // be used as the identifier in the declarator for a destructor
4966 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004967 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00004968 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00004969 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00004970 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00004971 else if (const TemplateSpecializationType *TST =
4972 DeclaratorType->getAs<TemplateSpecializationType>())
4973 if (TST->isTypeAlias())
4974 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4975 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004976
4977 // C++ [class.dtor]p2:
4978 // A destructor is used to destroy objects of its class type. A
4979 // destructor takes no parameters, and no return type can be
4980 // specified for it (not even void). The address of a destructor
4981 // shall not be taken. A destructor shall not be static. A
4982 // destructor can be invoked for a const, volatile or const
4983 // volatile object. A destructor shall not be declared const,
4984 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00004985 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004986 if (!D.isInvalidType())
4987 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4988 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00004989 << SourceRange(D.getIdentifierLoc())
4990 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4991
John McCalld931b082010-08-26 03:08:43 +00004992 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004993 }
Chris Lattner65401802009-04-25 08:28:21 +00004994 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004995 // Destructors don't have return types, but the parser will
4996 // happily parse something like:
4997 //
4998 // class X {
4999 // float ~X();
5000 // };
5001 //
5002 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005003 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5004 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5005 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005006 }
Mike Stump1eb44332009-09-09 15:08:12 +00005007
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005008 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005009 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005010 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005011 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5012 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005013 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005014 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5015 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005016 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005017 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5018 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005019 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005020 }
5021
Douglas Gregorc938c162011-01-26 05:01:58 +00005022 // C++0x [class.dtor]p2:
5023 // A destructor shall not be declared with a ref-qualifier.
5024 if (FTI.hasRefQualifier()) {
5025 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5026 << FTI.RefQualifierIsLValueRef
5027 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5028 D.setInvalidType();
5029 }
5030
Douglas Gregor42a552f2008-11-05 20:51:48 +00005031 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005032 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005033 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5034
5035 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005036 FTI.freeArgs();
5037 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005038 }
5039
Mike Stump1eb44332009-09-09 15:08:12 +00005040 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005041 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005042 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005043 D.setInvalidType();
5044 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005045
5046 // Rebuild the function type "R" without any type qualifiers or
5047 // parameters (in case any of the errors above fired) and with
5048 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005049 // types.
John McCalle23cf432010-12-14 08:05:40 +00005050 if (!D.isInvalidType())
5051 return R;
5052
Douglas Gregord92ec472010-07-01 05:10:53 +00005053 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005054 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5055 EPI.Variadic = false;
5056 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005057 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005058 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005059}
5060
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005061/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5062/// well-formednes of the conversion function declarator @p D with
5063/// type @p R. If there are any errors in the declarator, this routine
5064/// will emit diagnostics and return true. Otherwise, it will return
5065/// false. Either way, the type @p R will be updated to reflect a
5066/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005067void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005068 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005069 // C++ [class.conv.fct]p1:
5070 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005071 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005072 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005073 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005074 if (!D.isInvalidType())
5075 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5076 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5077 << SourceRange(D.getIdentifierLoc());
5078 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005079 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005080 }
John McCalla3f81372010-04-13 00:04:31 +00005081
5082 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5083
Chris Lattner6e475012009-04-25 08:35:12 +00005084 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005085 // Conversion functions don't have return types, but the parser will
5086 // happily parse something like:
5087 //
5088 // class X {
5089 // float operator bool();
5090 // };
5091 //
5092 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005093 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5094 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5095 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005096 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005097 }
5098
John McCalla3f81372010-04-13 00:04:31 +00005099 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5100
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005101 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005102 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005103 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5104
5105 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005106 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005107 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005108 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005109 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005110 D.setInvalidType();
5111 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005112
John McCalla3f81372010-04-13 00:04:31 +00005113 // Diagnose "&operator bool()" and other such nonsense. This
5114 // is actually a gcc extension which we don't support.
5115 if (Proto->getResultType() != ConvType) {
5116 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5117 << Proto->getResultType();
5118 D.setInvalidType();
5119 ConvType = Proto->getResultType();
5120 }
5121
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005122 // C++ [class.conv.fct]p4:
5123 // The conversion-type-id shall not represent a function type nor
5124 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005125 if (ConvType->isArrayType()) {
5126 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5127 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005128 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005129 } else if (ConvType->isFunctionType()) {
5130 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5131 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005132 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005133 }
5134
5135 // Rebuild the function type "R" without any parameters (in case any
5136 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005137 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005138 if (D.isInvalidType())
5139 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005140
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005141 // C++0x explicit conversion operators.
5142 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00005143 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005144 diag::warn_explicit_conversion_functions)
5145 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005146}
5147
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005148/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5149/// the declaration of the given C++ conversion function. This routine
5150/// is responsible for recording the conversion function in the C++
5151/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005152Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005153 assert(Conversion && "Expected to receive a conversion function declaration");
5154
Douglas Gregor9d350972008-12-12 08:25:50 +00005155 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005156
5157 // Make sure we aren't redeclaring the conversion function.
5158 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005159
5160 // C++ [class.conv.fct]p1:
5161 // [...] A conversion function is never used to convert a
5162 // (possibly cv-qualified) object to the (possibly cv-qualified)
5163 // same object type (or a reference to it), to a (possibly
5164 // cv-qualified) base class of that type (or a reference to it),
5165 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005166 // FIXME: Suppress this warning if the conversion function ends up being a
5167 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005168 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005169 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005170 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005171 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005172 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5173 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005174 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005175 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005176 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5177 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005178 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005179 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005180 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005181 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005182 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005183 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005184 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005185 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005186 }
5187
Douglas Gregore80622f2010-09-29 04:25:11 +00005188 if (FunctionTemplateDecl *ConversionTemplate
5189 = Conversion->getDescribedFunctionTemplate())
5190 return ConversionTemplate;
5191
John McCalld226f652010-08-21 09:40:31 +00005192 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005193}
5194
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005195//===----------------------------------------------------------------------===//
5196// Namespace Handling
5197//===----------------------------------------------------------------------===//
5198
John McCallea318642010-08-26 09:15:37 +00005199
5200
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005201/// ActOnStartNamespaceDef - This is called at the start of a namespace
5202/// definition.
John McCalld226f652010-08-21 09:40:31 +00005203Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005204 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005205 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005206 SourceLocation IdentLoc,
5207 IdentifierInfo *II,
5208 SourceLocation LBrace,
5209 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005210 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5211 // For anonymous namespace, take the location of the left brace.
5212 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00005213 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005214 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005215 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005216
5217 Scope *DeclRegionScope = NamespcScope->getParent();
5218
Anders Carlsson2a3503d2010-02-07 01:09:23 +00005219 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5220
John McCall90f14502010-12-10 02:59:44 +00005221 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5222 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005223
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005224 if (II) {
5225 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005226 // The identifier in an original-namespace-definition shall not
5227 // have been previously defined in the declarative region in
5228 // which the original-namespace-definition appears. The
5229 // identifier in an original-namespace-definition is the name of
5230 // the namespace. Subsequently in that declarative region, it is
5231 // treated as an original-namespace-name.
5232 //
5233 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005234 // look through using directives, just look for any ordinary names.
5235
5236 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5237 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5238 Decl::IDNS_Namespace;
5239 NamedDecl *PrevDecl = 0;
5240 for (DeclContext::lookup_result R
5241 = CurContext->getRedeclContext()->lookup(II);
5242 R.first != R.second; ++R.first) {
5243 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5244 PrevDecl = *R.first;
5245 break;
5246 }
5247 }
5248
Douglas Gregor44b43212008-12-11 16:49:14 +00005249 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5250 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005251 if (Namespc->isInline() != OrigNS->isInline()) {
5252 // inline-ness must match
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005253 if (OrigNS->isInline()) {
5254 // The user probably just forgot the 'inline', so suggest that it
5255 // be added back.
5256 Diag(Namespc->getLocation(),
5257 diag::warn_inline_namespace_reopened_noninline)
5258 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5259 } else {
5260 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5261 << Namespc->isInline();
5262 }
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005263 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005264
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005265 // Recover by ignoring the new namespace's inline status.
5266 Namespc->setInline(OrigNS->isInline());
5267 }
5268
Douglas Gregor44b43212008-12-11 16:49:14 +00005269 // Attach this namespace decl to the chain of extended namespace
5270 // definitions.
5271 OrigNS->setNextNamespace(Namespc);
5272 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005273
Mike Stump1eb44332009-09-09 15:08:12 +00005274 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00005275 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00005276 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00005277 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005278 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005279 } else if (PrevDecl) {
5280 // This is an invalid name redefinition.
5281 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5282 << Namespc->getDeclName();
5283 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5284 Namespc->setInvalidDecl();
5285 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005286 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005287 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005288 // This is the first "real" definition of the namespace "std", so update
5289 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005290 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005291 // We had already defined a dummy namespace "std". Link this new
5292 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005293 StdNS->setNextNamespace(Namespc);
5294 StdNS->setLocation(IdentLoc);
5295 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005296 }
5297
5298 // Make our StdNamespace cache point at the first real definition of the
5299 // "std" namespace.
5300 StdNamespace = Namespc;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005301
5302 // Add this instance of "std" to the set of known namespaces
5303 KnownNamespaces[Namespc] = false;
5304 } else if (!Namespc->isInline()) {
5305 // Since this is an "original" namespace, add it to the known set of
5306 // namespaces if it is not an inline namespace.
5307 KnownNamespaces[Namespc] = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005308 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005309
5310 PushOnScopeChains(Namespc, DeclRegionScope);
5311 } else {
John McCall9aeed322009-10-01 00:25:31 +00005312 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00005313 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00005314
5315 // Link the anonymous namespace into its parent.
5316 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005317 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005318 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5319 PrevDecl = TU->getAnonymousNamespace();
5320 TU->setAnonymousNamespace(Namespc);
5321 } else {
5322 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5323 PrevDecl = ND->getAnonymousNamespace();
5324 ND->setAnonymousNamespace(Namespc);
5325 }
5326
5327 // Link the anonymous namespace with its previous declaration.
5328 if (PrevDecl) {
5329 assert(PrevDecl->isAnonymousNamespace());
5330 assert(!PrevDecl->getNextNamespace());
5331 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5332 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005333
5334 if (Namespc->isInline() != PrevDecl->isInline()) {
5335 // inline-ness must match
5336 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5337 << Namespc->isInline();
5338 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5339 Namespc->setInvalidDecl();
5340 // Recover by ignoring the new namespace's inline status.
5341 Namespc->setInline(PrevDecl->isInline());
5342 }
John McCall5fdd7642009-12-16 02:06:49 +00005343 }
John McCall9aeed322009-10-01 00:25:31 +00005344
Douglas Gregora4181472010-03-24 00:46:35 +00005345 CurContext->addDecl(Namespc);
5346
John McCall9aeed322009-10-01 00:25:31 +00005347 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5348 // behaves as if it were replaced by
5349 // namespace unique { /* empty body */ }
5350 // using namespace unique;
5351 // namespace unique { namespace-body }
5352 // where all occurrences of 'unique' in a translation unit are
5353 // replaced by the same identifier and this identifier differs
5354 // from all other identifiers in the entire program.
5355
5356 // We just create the namespace with an empty name and then add an
5357 // implicit using declaration, just like the standard suggests.
5358 //
5359 // CodeGen enforces the "universally unique" aspect by giving all
5360 // declarations semantically contained within an anonymous
5361 // namespace internal linkage.
5362
John McCall5fdd7642009-12-16 02:06:49 +00005363 if (!PrevDecl) {
5364 UsingDirectiveDecl* UD
5365 = UsingDirectiveDecl::Create(Context, CurContext,
5366 /* 'using' */ LBrace,
5367 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005368 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005369 /* identifier */ SourceLocation(),
5370 Namespc,
5371 /* Ancestor */ CurContext);
5372 UD->setImplicit();
5373 CurContext->addDecl(UD);
5374 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005375 }
5376
5377 // Although we could have an invalid decl (i.e. the namespace name is a
5378 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005379 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5380 // for the namespace has the declarations that showed up in that particular
5381 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005382 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005383 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005384}
5385
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005386/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5387/// is a namespace alias, returns the namespace it points to.
5388static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5389 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5390 return AD->getNamespace();
5391 return dyn_cast_or_null<NamespaceDecl>(D);
5392}
5393
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005394/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5395/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005396void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005397 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5398 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005399 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005400 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005401 if (Namespc->hasAttr<VisibilityAttr>())
5402 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005403}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005404
John McCall384aff82010-08-25 07:42:41 +00005405CXXRecordDecl *Sema::getStdBadAlloc() const {
5406 return cast_or_null<CXXRecordDecl>(
5407 StdBadAlloc.get(Context.getExternalSource()));
5408}
5409
5410NamespaceDecl *Sema::getStdNamespace() const {
5411 return cast_or_null<NamespaceDecl>(
5412 StdNamespace.get(Context.getExternalSource()));
5413}
5414
Douglas Gregor66992202010-06-29 17:53:46 +00005415/// \brief Retrieve the special "std" namespace, which may require us to
5416/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005417NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005418 if (!StdNamespace) {
5419 // The "std" namespace has not yet been defined, so build one implicitly.
5420 StdNamespace = NamespaceDecl::Create(Context,
5421 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005422 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00005423 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005424 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005425 }
5426
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005427 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005428}
5429
Douglas Gregor9172aa62011-03-26 22:25:30 +00005430/// \brief Determine whether a using statement is in a context where it will be
5431/// apply in all contexts.
5432static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5433 switch (CurContext->getDeclKind()) {
5434 case Decl::TranslationUnit:
5435 return true;
5436 case Decl::LinkageSpec:
5437 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5438 default:
5439 return false;
5440 }
5441}
5442
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005443static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5444 CXXScopeSpec &SS,
5445 SourceLocation IdentLoc,
5446 IdentifierInfo *Ident) {
5447 R.clear();
5448 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5449 R.getLookupKind(), Sc, &SS, NULL,
5450 false, S.CTC_NoKeywords, NULL)) {
5451 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5452 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5453 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5454 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5455 if (DeclContext *DC = S.computeDeclContext(SS, false))
5456 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5457 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5458 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5459 else
5460 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5461 << Ident << CorrectedQuotedStr
5462 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5463
5464 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5465 diag::note_namespace_defined_here) << CorrectedQuotedStr;
5466
5467 Ident = Corrected.getCorrectionAsIdentifierInfo();
5468 R.addDecl(Corrected.getCorrectionDecl());
5469 return true;
5470 }
5471 R.setLookupName(Ident);
5472 }
5473 return false;
5474}
5475
John McCalld226f652010-08-21 09:40:31 +00005476Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005477 SourceLocation UsingLoc,
5478 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005479 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005480 SourceLocation IdentLoc,
5481 IdentifierInfo *NamespcName,
5482 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005483 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5484 assert(NamespcName && "Invalid NamespcName.");
5485 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005486
5487 // This can only happen along a recovery path.
5488 while (S->getFlags() & Scope::TemplateParamScope)
5489 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005490 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005491
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005492 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005493 NestedNameSpecifier *Qualifier = 0;
5494 if (SS.isSet())
5495 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5496
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005497 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005498 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5499 LookupParsedName(R, S, &SS);
5500 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005501 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005502
Douglas Gregor66992202010-06-29 17:53:46 +00005503 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005504 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005505 // Allow "using namespace std;" or "using namespace ::std;" even if
5506 // "std" hasn't been defined yet, for GCC compatibility.
5507 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5508 NamespcName->isStr("std")) {
5509 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005510 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005511 R.resolveKind();
5512 }
5513 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005514 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005515 }
5516
John McCallf36e02d2009-10-09 21:13:30 +00005517 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005518 NamedDecl *Named = R.getFoundDecl();
5519 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5520 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005521 // C++ [namespace.udir]p1:
5522 // A using-directive specifies that the names in the nominated
5523 // namespace can be used in the scope in which the
5524 // using-directive appears after the using-directive. During
5525 // unqualified name lookup (3.4.1), the names appear as if they
5526 // were declared in the nearest enclosing namespace which
5527 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005528 // namespace. [Note: in this context, "contains" means "contains
5529 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005530
5531 // Find enclosing context containing both using-directive and
5532 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005533 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005534 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5535 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5536 CommonAncestor = CommonAncestor->getParent();
5537
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005538 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005539 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005540 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005541
Douglas Gregor9172aa62011-03-26 22:25:30 +00005542 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005543 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005544 Diag(IdentLoc, diag::warn_using_directive_in_header);
5545 }
5546
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005547 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005548 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005549 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005550 }
5551
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005552 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005553 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005554}
5555
5556void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5557 // If scope has associated entity, then using directive is at namespace
5558 // or translation unit scope. We add UsingDirectiveDecls, into
5559 // it's lookup structure.
5560 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005561 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005562 else
5563 // Otherwise it is block-sope. using-directives will affect lookup
5564 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00005565 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005566}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005567
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005568
John McCalld226f652010-08-21 09:40:31 +00005569Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005570 AccessSpecifier AS,
5571 bool HasUsingKeyword,
5572 SourceLocation UsingLoc,
5573 CXXScopeSpec &SS,
5574 UnqualifiedId &Name,
5575 AttributeList *AttrList,
5576 bool IsTypeName,
5577 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005578 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005579
Douglas Gregor12c118a2009-11-04 16:30:06 +00005580 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005581 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005582 case UnqualifiedId::IK_Identifier:
5583 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005584 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005585 case UnqualifiedId::IK_ConversionFunctionId:
5586 break;
5587
5588 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005589 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005590 // C++0x inherited constructors.
5591 if (getLangOptions().CPlusPlus0x) break;
5592
Douglas Gregor12c118a2009-11-04 16:30:06 +00005593 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5594 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005595 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005596
5597 case UnqualifiedId::IK_DestructorName:
5598 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5599 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005600 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005601
5602 case UnqualifiedId::IK_TemplateId:
5603 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5604 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005605 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005606 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005607
5608 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5609 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005610 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005611 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005612
John McCall60fa3cf2009-12-11 02:10:03 +00005613 // Warn about using declarations.
5614 // TODO: store that the declaration was written without 'using' and
5615 // talk about access decls instead of using decls in the
5616 // diagnostics.
5617 if (!HasUsingKeyword) {
5618 UsingLoc = Name.getSourceRange().getBegin();
5619
5620 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005621 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005622 }
5623
Douglas Gregor56c04582010-12-16 00:46:58 +00005624 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5625 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5626 return 0;
5627
John McCall9488ea12009-11-17 05:59:44 +00005628 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005629 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005630 /* IsInstantiation */ false,
5631 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005632 if (UD)
5633 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005634
John McCalld226f652010-08-21 09:40:31 +00005635 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005636}
5637
Douglas Gregor09acc982010-07-07 23:08:52 +00005638/// \brief Determine whether a using declaration considers the given
5639/// declarations as "equivalent", e.g., if they are redeclarations of
5640/// the same entity or are both typedefs of the same type.
5641static bool
5642IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5643 bool &SuppressRedeclaration) {
5644 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5645 SuppressRedeclaration = false;
5646 return true;
5647 }
5648
Richard Smith162e1c12011-04-15 14:24:37 +00005649 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5650 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005651 SuppressRedeclaration = true;
5652 return Context.hasSameType(TD1->getUnderlyingType(),
5653 TD2->getUnderlyingType());
5654 }
5655
5656 return false;
5657}
5658
5659
John McCall9f54ad42009-12-10 09:41:52 +00005660/// Determines whether to create a using shadow decl for a particular
5661/// decl, given the set of decls existing prior to this using lookup.
5662bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5663 const LookupResult &Previous) {
5664 // Diagnose finding a decl which is not from a base class of the
5665 // current class. We do this now because there are cases where this
5666 // function will silently decide not to build a shadow decl, which
5667 // will pre-empt further diagnostics.
5668 //
5669 // We don't need to do this in C++0x because we do the check once on
5670 // the qualifier.
5671 //
5672 // FIXME: diagnose the following if we care enough:
5673 // struct A { int foo; };
5674 // struct B : A { using A::foo; };
5675 // template <class T> struct C : A {};
5676 // template <class T> struct D : C<T> { using B::foo; } // <---
5677 // This is invalid (during instantiation) in C++03 because B::foo
5678 // resolves to the using decl in B, which is not a base class of D<T>.
5679 // We can't diagnose it immediately because C<T> is an unknown
5680 // specialization. The UsingShadowDecl in D<T> then points directly
5681 // to A::foo, which will look well-formed when we instantiate.
5682 // The right solution is to not collapse the shadow-decl chain.
5683 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5684 DeclContext *OrigDC = Orig->getDeclContext();
5685
5686 // Handle enums and anonymous structs.
5687 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5688 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5689 while (OrigRec->isAnonymousStructOrUnion())
5690 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5691
5692 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5693 if (OrigDC == CurContext) {
5694 Diag(Using->getLocation(),
5695 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005696 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005697 Diag(Orig->getLocation(), diag::note_using_decl_target);
5698 return true;
5699 }
5700
Douglas Gregordc355712011-02-25 00:36:19 +00005701 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005702 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005703 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005704 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005705 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005706 Diag(Orig->getLocation(), diag::note_using_decl_target);
5707 return true;
5708 }
5709 }
5710
5711 if (Previous.empty()) return false;
5712
5713 NamedDecl *Target = Orig;
5714 if (isa<UsingShadowDecl>(Target))
5715 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5716
John McCalld7533ec2009-12-11 02:33:26 +00005717 // If the target happens to be one of the previous declarations, we
5718 // don't have a conflict.
5719 //
5720 // FIXME: but we might be increasing its access, in which case we
5721 // should redeclare it.
5722 NamedDecl *NonTag = 0, *Tag = 0;
5723 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5724 I != E; ++I) {
5725 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005726 bool Result;
5727 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5728 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005729
5730 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5731 }
5732
John McCall9f54ad42009-12-10 09:41:52 +00005733 if (Target->isFunctionOrFunctionTemplate()) {
5734 FunctionDecl *FD;
5735 if (isa<FunctionTemplateDecl>(Target))
5736 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5737 else
5738 FD = cast<FunctionDecl>(Target);
5739
5740 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005741 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005742 case Ovl_Overload:
5743 return false;
5744
5745 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005746 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005747 break;
5748
5749 // We found a decl with the exact signature.
5750 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005751 // If we're in a record, we want to hide the target, so we
5752 // return true (without a diagnostic) to tell the caller not to
5753 // build a shadow decl.
5754 if (CurContext->isRecord())
5755 return true;
5756
5757 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005758 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005759 break;
5760 }
5761
5762 Diag(Target->getLocation(), diag::note_using_decl_target);
5763 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5764 return true;
5765 }
5766
5767 // Target is not a function.
5768
John McCall9f54ad42009-12-10 09:41:52 +00005769 if (isa<TagDecl>(Target)) {
5770 // No conflict between a tag and a non-tag.
5771 if (!Tag) return false;
5772
John McCall41ce66f2009-12-10 19:51:03 +00005773 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005774 Diag(Target->getLocation(), diag::note_using_decl_target);
5775 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5776 return true;
5777 }
5778
5779 // No conflict between a tag and a non-tag.
5780 if (!NonTag) return false;
5781
John McCall41ce66f2009-12-10 19:51:03 +00005782 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005783 Diag(Target->getLocation(), diag::note_using_decl_target);
5784 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5785 return true;
5786}
5787
John McCall9488ea12009-11-17 05:59:44 +00005788/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00005789UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00005790 UsingDecl *UD,
5791 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00005792
5793 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00005794 NamedDecl *Target = Orig;
5795 if (isa<UsingShadowDecl>(Target)) {
5796 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5797 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00005798 }
5799
5800 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00005801 = UsingShadowDecl::Create(Context, CurContext,
5802 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00005803 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00005804
5805 Shadow->setAccess(UD->getAccess());
5806 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5807 Shadow->setInvalidDecl();
5808
John McCall9488ea12009-11-17 05:59:44 +00005809 if (S)
John McCall604e7f12009-12-08 07:46:18 +00005810 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00005811 else
John McCall604e7f12009-12-08 07:46:18 +00005812 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00005813
John McCall604e7f12009-12-08 07:46:18 +00005814
John McCall9f54ad42009-12-10 09:41:52 +00005815 return Shadow;
5816}
John McCall604e7f12009-12-08 07:46:18 +00005817
John McCall9f54ad42009-12-10 09:41:52 +00005818/// Hides a using shadow declaration. This is required by the current
5819/// using-decl implementation when a resolvable using declaration in a
5820/// class is followed by a declaration which would hide or override
5821/// one or more of the using decl's targets; for example:
5822///
5823/// struct Base { void foo(int); };
5824/// struct Derived : Base {
5825/// using Base::foo;
5826/// void foo(int);
5827/// };
5828///
5829/// The governing language is C++03 [namespace.udecl]p12:
5830///
5831/// When a using-declaration brings names from a base class into a
5832/// derived class scope, member functions in the derived class
5833/// override and/or hide member functions with the same name and
5834/// parameter types in a base class (rather than conflicting).
5835///
5836/// There are two ways to implement this:
5837/// (1) optimistically create shadow decls when they're not hidden
5838/// by existing declarations, or
5839/// (2) don't create any shadow decls (or at least don't make them
5840/// visible) until we've fully parsed/instantiated the class.
5841/// The problem with (1) is that we might have to retroactively remove
5842/// a shadow decl, which requires several O(n) operations because the
5843/// decl structures are (very reasonably) not designed for removal.
5844/// (2) avoids this but is very fiddly and phase-dependent.
5845void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00005846 if (Shadow->getDeclName().getNameKind() ==
5847 DeclarationName::CXXConversionFunctionName)
5848 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5849
John McCall9f54ad42009-12-10 09:41:52 +00005850 // Remove it from the DeclContext...
5851 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005852
John McCall9f54ad42009-12-10 09:41:52 +00005853 // ...and the scope, if applicable...
5854 if (S) {
John McCalld226f652010-08-21 09:40:31 +00005855 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00005856 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005857 }
5858
John McCall9f54ad42009-12-10 09:41:52 +00005859 // ...and the using decl.
5860 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5861
5862 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00005863 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00005864}
5865
John McCall7ba107a2009-11-18 02:36:19 +00005866/// Builds a using declaration.
5867///
5868/// \param IsInstantiation - Whether this call arises from an
5869/// instantiation of an unresolved using declaration. We treat
5870/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00005871NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5872 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005873 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005874 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00005875 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005876 bool IsInstantiation,
5877 bool IsTypeName,
5878 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00005879 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005880 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00005881 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00005882
Anders Carlsson550b14b2009-08-28 05:49:21 +00005883 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00005884
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005885 if (SS.isEmpty()) {
5886 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00005887 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005888 }
Mike Stump1eb44332009-09-09 15:08:12 +00005889
John McCall9f54ad42009-12-10 09:41:52 +00005890 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005891 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00005892 ForRedeclaration);
5893 Previous.setHideTags(false);
5894 if (S) {
5895 LookupName(Previous, S);
5896
5897 // It is really dumb that we have to do this.
5898 LookupResult::Filter F = Previous.makeFilter();
5899 while (F.hasNext()) {
5900 NamedDecl *D = F.next();
5901 if (!isDeclInScope(D, CurContext, S))
5902 F.erase();
5903 }
5904 F.done();
5905 } else {
5906 assert(IsInstantiation && "no scope in non-instantiation");
5907 assert(CurContext->isRecord() && "scope not record in instantiation");
5908 LookupQualifiedName(Previous, CurContext);
5909 }
5910
John McCall9f54ad42009-12-10 09:41:52 +00005911 // Check for invalid redeclarations.
5912 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5913 return 0;
5914
5915 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00005916 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5917 return 0;
5918
John McCallaf8e6ed2009-11-12 03:15:40 +00005919 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005920 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00005921 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00005922 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00005923 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00005924 // FIXME: not all declaration name kinds are legal here
5925 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5926 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00005927 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005928 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00005929 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005930 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5931 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00005932 }
John McCalled976492009-12-04 22:46:56 +00005933 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005934 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5935 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00005936 }
John McCalled976492009-12-04 22:46:56 +00005937 D->setAccess(AS);
5938 CurContext->addDecl(D);
5939
5940 if (!LookupContext) return D;
5941 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00005942
John McCall77bb1aa2010-05-01 00:40:08 +00005943 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00005944 UD->setInvalidDecl();
5945 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005946 }
5947
Sebastian Redlf677ea32011-02-05 19:23:19 +00005948 // Constructor inheriting using decls get special treatment.
5949 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00005950 if (CheckInheritedConstructorUsingDecl(UD))
5951 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005952 return UD;
5953 }
5954
5955 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00005956
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005957 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00005958
John McCall604e7f12009-12-08 07:46:18 +00005959 // Unlike most lookups, we don't always want to hide tag
5960 // declarations: tag names are visible through the using declaration
5961 // even if hidden by ordinary names, *except* in a dependent context
5962 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00005963 if (!IsInstantiation)
5964 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00005965
John McCalla24dc2e2009-11-17 02:14:36 +00005966 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005967
John McCallf36e02d2009-10-09 21:13:30 +00005968 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00005969 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005970 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005971 UD->setInvalidDecl();
5972 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005973 }
5974
John McCalled976492009-12-04 22:46:56 +00005975 if (R.isAmbiguous()) {
5976 UD->setInvalidDecl();
5977 return UD;
5978 }
Mike Stump1eb44332009-09-09 15:08:12 +00005979
John McCall7ba107a2009-11-18 02:36:19 +00005980 if (IsTypeName) {
5981 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00005982 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005983 Diag(IdentLoc, diag::err_using_typename_non_type);
5984 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5985 Diag((*I)->getUnderlyingDecl()->getLocation(),
5986 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005987 UD->setInvalidDecl();
5988 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005989 }
5990 } else {
5991 // If we asked for a non-typename and we got a type, error out,
5992 // but only if this is an instantiation of an unresolved using
5993 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00005994 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005995 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5996 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005997 UD->setInvalidDecl();
5998 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005999 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006000 }
6001
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006002 // C++0x N2914 [namespace.udecl]p6:
6003 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006004 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006005 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6006 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006007 UD->setInvalidDecl();
6008 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006009 }
Mike Stump1eb44332009-09-09 15:08:12 +00006010
John McCall9f54ad42009-12-10 09:41:52 +00006011 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6012 if (!CheckUsingShadowDecl(UD, *I, Previous))
6013 BuildUsingShadowDecl(S, UD, *I);
6014 }
John McCall9488ea12009-11-17 05:59:44 +00006015
6016 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006017}
6018
Sebastian Redlf677ea32011-02-05 19:23:19 +00006019/// Additional checks for a using declaration referring to a constructor name.
6020bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6021 if (UD->isTypeName()) {
6022 // FIXME: Cannot specify typename when specifying constructor
6023 return true;
6024 }
6025
Douglas Gregordc355712011-02-25 00:36:19 +00006026 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006027 assert(SourceType &&
6028 "Using decl naming constructor doesn't have type in scope spec.");
6029 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6030
6031 // Check whether the named type is a direct base class.
6032 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6033 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6034 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6035 BaseIt != BaseE; ++BaseIt) {
6036 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6037 if (CanonicalSourceType == BaseType)
6038 break;
6039 }
6040
6041 if (BaseIt == BaseE) {
6042 // Did not find SourceType in the bases.
6043 Diag(UD->getUsingLocation(),
6044 diag::err_using_decl_constructor_not_in_direct_base)
6045 << UD->getNameInfo().getSourceRange()
6046 << QualType(SourceType, 0) << TargetClass;
6047 return true;
6048 }
6049
6050 BaseIt->setInheritConstructors();
6051
6052 return false;
6053}
6054
John McCall9f54ad42009-12-10 09:41:52 +00006055/// Checks that the given using declaration is not an invalid
6056/// redeclaration. Note that this is checking only for the using decl
6057/// itself, not for any ill-formedness among the UsingShadowDecls.
6058bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6059 bool isTypeName,
6060 const CXXScopeSpec &SS,
6061 SourceLocation NameLoc,
6062 const LookupResult &Prev) {
6063 // C++03 [namespace.udecl]p8:
6064 // C++0x [namespace.udecl]p10:
6065 // A using-declaration is a declaration and can therefore be used
6066 // repeatedly where (and only where) multiple declarations are
6067 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006068 //
John McCall8a726212010-11-29 18:01:58 +00006069 // That's in non-member contexts.
6070 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006071 return false;
6072
6073 NestedNameSpecifier *Qual
6074 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6075
6076 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6077 NamedDecl *D = *I;
6078
6079 bool DTypename;
6080 NestedNameSpecifier *DQual;
6081 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6082 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006083 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006084 } else if (UnresolvedUsingValueDecl *UD
6085 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6086 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006087 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006088 } else if (UnresolvedUsingTypenameDecl *UD
6089 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6090 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006091 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006092 } else continue;
6093
6094 // using decls differ if one says 'typename' and the other doesn't.
6095 // FIXME: non-dependent using decls?
6096 if (isTypeName != DTypename) continue;
6097
6098 // using decls differ if they name different scopes (but note that
6099 // template instantiation can cause this check to trigger when it
6100 // didn't before instantiation).
6101 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6102 Context.getCanonicalNestedNameSpecifier(DQual))
6103 continue;
6104
6105 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006106 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006107 return true;
6108 }
6109
6110 return false;
6111}
6112
John McCall604e7f12009-12-08 07:46:18 +00006113
John McCalled976492009-12-04 22:46:56 +00006114/// Checks that the given nested-name qualifier used in a using decl
6115/// in the current context is appropriately related to the current
6116/// scope. If an error is found, diagnoses it and returns true.
6117bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6118 const CXXScopeSpec &SS,
6119 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006120 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006121
John McCall604e7f12009-12-08 07:46:18 +00006122 if (!CurContext->isRecord()) {
6123 // C++03 [namespace.udecl]p3:
6124 // C++0x [namespace.udecl]p8:
6125 // A using-declaration for a class member shall be a member-declaration.
6126
6127 // If we weren't able to compute a valid scope, it must be a
6128 // dependent class scope.
6129 if (!NamedContext || NamedContext->isRecord()) {
6130 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6131 << SS.getRange();
6132 return true;
6133 }
6134
6135 // Otherwise, everything is known to be fine.
6136 return false;
6137 }
6138
6139 // The current scope is a record.
6140
6141 // If the named context is dependent, we can't decide much.
6142 if (!NamedContext) {
6143 // FIXME: in C++0x, we can diagnose if we can prove that the
6144 // nested-name-specifier does not refer to a base class, which is
6145 // still possible in some cases.
6146
6147 // Otherwise we have to conservatively report that things might be
6148 // okay.
6149 return false;
6150 }
6151
6152 if (!NamedContext->isRecord()) {
6153 // Ideally this would point at the last name in the specifier,
6154 // but we don't have that level of source info.
6155 Diag(SS.getRange().getBegin(),
6156 diag::err_using_decl_nested_name_specifier_is_not_class)
6157 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6158 return true;
6159 }
6160
Douglas Gregor6fb07292010-12-21 07:41:49 +00006161 if (!NamedContext->isDependentContext() &&
6162 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6163 return true;
6164
John McCall604e7f12009-12-08 07:46:18 +00006165 if (getLangOptions().CPlusPlus0x) {
6166 // C++0x [namespace.udecl]p3:
6167 // In a using-declaration used as a member-declaration, the
6168 // nested-name-specifier shall name a base class of the class
6169 // being defined.
6170
6171 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6172 cast<CXXRecordDecl>(NamedContext))) {
6173 if (CurContext == NamedContext) {
6174 Diag(NameLoc,
6175 diag::err_using_decl_nested_name_specifier_is_current_class)
6176 << SS.getRange();
6177 return true;
6178 }
6179
6180 Diag(SS.getRange().getBegin(),
6181 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6182 << (NestedNameSpecifier*) SS.getScopeRep()
6183 << cast<CXXRecordDecl>(CurContext)
6184 << SS.getRange();
6185 return true;
6186 }
6187
6188 return false;
6189 }
6190
6191 // C++03 [namespace.udecl]p4:
6192 // A using-declaration used as a member-declaration shall refer
6193 // to a member of a base class of the class being defined [etc.].
6194
6195 // Salient point: SS doesn't have to name a base class as long as
6196 // lookup only finds members from base classes. Therefore we can
6197 // diagnose here only if we can prove that that can't happen,
6198 // i.e. if the class hierarchies provably don't intersect.
6199
6200 // TODO: it would be nice if "definitely valid" results were cached
6201 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6202 // need to be repeated.
6203
6204 struct UserData {
6205 llvm::DenseSet<const CXXRecordDecl*> Bases;
6206
6207 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6208 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6209 Data->Bases.insert(Base);
6210 return true;
6211 }
6212
6213 bool hasDependentBases(const CXXRecordDecl *Class) {
6214 return !Class->forallBases(collect, this);
6215 }
6216
6217 /// Returns true if the base is dependent or is one of the
6218 /// accumulated base classes.
6219 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6220 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6221 return !Data->Bases.count(Base);
6222 }
6223
6224 bool mightShareBases(const CXXRecordDecl *Class) {
6225 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6226 }
6227 };
6228
6229 UserData Data;
6230
6231 // Returns false if we find a dependent base.
6232 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6233 return false;
6234
6235 // Returns false if the class has a dependent base or if it or one
6236 // of its bases is present in the base set of the current context.
6237 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6238 return false;
6239
6240 Diag(SS.getRange().getBegin(),
6241 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6242 << (NestedNameSpecifier*) SS.getScopeRep()
6243 << cast<CXXRecordDecl>(CurContext)
6244 << SS.getRange();
6245
6246 return true;
John McCalled976492009-12-04 22:46:56 +00006247}
6248
Richard Smith162e1c12011-04-15 14:24:37 +00006249Decl *Sema::ActOnAliasDeclaration(Scope *S,
6250 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006251 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006252 SourceLocation UsingLoc,
6253 UnqualifiedId &Name,
6254 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006255 // Skip up to the relevant declaration scope.
6256 while (S->getFlags() & Scope::TemplateParamScope)
6257 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006258 assert((S->getFlags() & Scope::DeclScope) &&
6259 "got alias-declaration outside of declaration scope");
6260
6261 if (Type.isInvalid())
6262 return 0;
6263
6264 bool Invalid = false;
6265 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6266 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006267 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006268
6269 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6270 return 0;
6271
6272 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006273 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006274 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006275 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6276 TInfo->getTypeLoc().getBeginLoc());
6277 }
Richard Smith162e1c12011-04-15 14:24:37 +00006278
6279 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6280 LookupName(Previous, S);
6281
6282 // Warn about shadowing the name of a template parameter.
6283 if (Previous.isSingleResult() &&
6284 Previous.getFoundDecl()->isTemplateParameter()) {
6285 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6286 Previous.getFoundDecl()))
6287 Invalid = true;
6288 Previous.clear();
6289 }
6290
6291 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6292 "name in alias declaration must be an identifier");
6293 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6294 Name.StartLocation,
6295 Name.Identifier, TInfo);
6296
6297 NewTD->setAccess(AS);
6298
6299 if (Invalid)
6300 NewTD->setInvalidDecl();
6301
Richard Smith3e4c6c42011-05-05 21:57:07 +00006302 CheckTypedefForVariablyModifiedType(S, NewTD);
6303 Invalid |= NewTD->isInvalidDecl();
6304
Richard Smith162e1c12011-04-15 14:24:37 +00006305 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006306
6307 NamedDecl *NewND;
6308 if (TemplateParamLists.size()) {
6309 TypeAliasTemplateDecl *OldDecl = 0;
6310 TemplateParameterList *OldTemplateParams = 0;
6311
6312 if (TemplateParamLists.size() != 1) {
6313 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6314 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6315 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6316 }
6317 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6318
6319 // Only consider previous declarations in the same scope.
6320 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6321 /*ExplicitInstantiationOrSpecialization*/false);
6322 if (!Previous.empty()) {
6323 Redeclaration = true;
6324
6325 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6326 if (!OldDecl && !Invalid) {
6327 Diag(UsingLoc, diag::err_redefinition_different_kind)
6328 << Name.Identifier;
6329
6330 NamedDecl *OldD = Previous.getRepresentativeDecl();
6331 if (OldD->getLocation().isValid())
6332 Diag(OldD->getLocation(), diag::note_previous_definition);
6333
6334 Invalid = true;
6335 }
6336
6337 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6338 if (TemplateParameterListsAreEqual(TemplateParams,
6339 OldDecl->getTemplateParameters(),
6340 /*Complain=*/true,
6341 TPL_TemplateMatch))
6342 OldTemplateParams = OldDecl->getTemplateParameters();
6343 else
6344 Invalid = true;
6345
6346 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6347 if (!Invalid &&
6348 !Context.hasSameType(OldTD->getUnderlyingType(),
6349 NewTD->getUnderlyingType())) {
6350 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6351 // but we can't reasonably accept it.
6352 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6353 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6354 if (OldTD->getLocation().isValid())
6355 Diag(OldTD->getLocation(), diag::note_previous_definition);
6356 Invalid = true;
6357 }
6358 }
6359 }
6360
6361 // Merge any previous default template arguments into our parameters,
6362 // and check the parameter list.
6363 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6364 TPC_TypeAliasTemplate))
6365 return 0;
6366
6367 TypeAliasTemplateDecl *NewDecl =
6368 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6369 Name.Identifier, TemplateParams,
6370 NewTD);
6371
6372 NewDecl->setAccess(AS);
6373
6374 if (Invalid)
6375 NewDecl->setInvalidDecl();
6376 else if (OldDecl)
6377 NewDecl->setPreviousDeclaration(OldDecl);
6378
6379 NewND = NewDecl;
6380 } else {
6381 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6382 NewND = NewTD;
6383 }
Richard Smith162e1c12011-04-15 14:24:37 +00006384
6385 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006386 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006387
Richard Smith3e4c6c42011-05-05 21:57:07 +00006388 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006389}
6390
John McCalld226f652010-08-21 09:40:31 +00006391Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006392 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006393 SourceLocation AliasLoc,
6394 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006395 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006396 SourceLocation IdentLoc,
6397 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006398
Anders Carlsson81c85c42009-03-28 23:53:49 +00006399 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006400 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6401 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006402
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006403 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006404 NamedDecl *PrevDecl
6405 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6406 ForRedeclaration);
6407 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6408 PrevDecl = 0;
6409
6410 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006411 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006412 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006413 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006414 // FIXME: At some point, we'll want to create the (redundant)
6415 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006416 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006417 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006418 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006419 }
Mike Stump1eb44332009-09-09 15:08:12 +00006420
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006421 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6422 diag::err_redefinition_different_kind;
6423 Diag(AliasLoc, DiagID) << Alias;
6424 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006425 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006426 }
6427
John McCalla24dc2e2009-11-17 02:14:36 +00006428 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006429 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006430
John McCallf36e02d2009-10-09 21:13:30 +00006431 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006432 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006433 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006434 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006435 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006436 }
Mike Stump1eb44332009-09-09 15:08:12 +00006437
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006438 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006439 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006440 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006441 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006442
John McCall3dbd3d52010-02-16 06:53:13 +00006443 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006444 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006445}
6446
Douglas Gregor39957dc2010-05-01 15:04:51 +00006447namespace {
6448 /// \brief Scoped object used to handle the state changes required in Sema
6449 /// to implicitly define the body of a C++ member function;
6450 class ImplicitlyDefinedFunctionScope {
6451 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006452 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006453
6454 public:
6455 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006456 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006457 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006458 S.PushFunctionScope();
6459 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6460 }
6461
6462 ~ImplicitlyDefinedFunctionScope() {
6463 S.PopExpressionEvaluationContext();
6464 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006465 }
6466 };
6467}
6468
Sean Hunt001cad92011-05-10 00:49:42 +00006469Sema::ImplicitExceptionSpecification
6470Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006471 // C++ [except.spec]p14:
6472 // An implicitly declared special member function (Clause 12) shall have an
6473 // exception-specification. [...]
6474 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006475 if (ClassDecl->isInvalidDecl())
6476 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006477
Sebastian Redl60618fa2011-03-12 11:50:43 +00006478 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006479 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6480 BEnd = ClassDecl->bases_end();
6481 B != BEnd; ++B) {
6482 if (B->isVirtual()) // Handled below.
6483 continue;
6484
Douglas Gregor18274032010-07-03 00:47:00 +00006485 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6486 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006487 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6488 // If this is a deleted function, add it anyway. This might be conformant
6489 // with the standard. This might not. I'm not sure. It might not matter.
6490 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006491 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006492 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006493 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006494
6495 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006496 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6497 BEnd = ClassDecl->vbases_end();
6498 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006499 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6500 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006501 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6502 // If this is a deleted function, add it anyway. This might be conformant
6503 // with the standard. This might not. I'm not sure. It might not matter.
6504 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006505 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006506 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006507 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006508
6509 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006510 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6511 FEnd = ClassDecl->field_end();
6512 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006513 if (F->hasInClassInitializer()) {
6514 if (Expr *E = F->getInClassInitializer())
6515 ExceptSpec.CalledExpr(E);
6516 else if (!F->isInvalidDecl())
6517 ExceptSpec.SetDelayed();
6518 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006519 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006520 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6521 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6522 // If this is a deleted function, add it anyway. This might be conformant
6523 // with the standard. This might not. I'm not sure. It might not matter.
6524 // In particular, the problem is that this function never gets called. It
6525 // might just be ill-formed because this function attempts to refer to
6526 // a deleted function here.
6527 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006528 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006529 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006530 }
John McCalle23cf432010-12-14 08:05:40 +00006531
Sean Hunt001cad92011-05-10 00:49:42 +00006532 return ExceptSpec;
6533}
6534
6535CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6536 CXXRecordDecl *ClassDecl) {
6537 // C++ [class.ctor]p5:
6538 // A default constructor for a class X is a constructor of class X
6539 // that can be called without an argument. If there is no
6540 // user-declared constructor for class X, a default constructor is
6541 // implicitly declared. An implicitly-declared default constructor
6542 // is an inline public member of its class.
6543 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6544 "Should not build implicit default constructor!");
6545
6546 ImplicitExceptionSpecification Spec =
6547 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6548 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006549
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006550 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006551 CanQualType ClassType
6552 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006553 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006554 DeclarationName Name
6555 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006556 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006557 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006558 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00006559 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00006560 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00006561 /*TInfo=*/0,
6562 /*isExplicit=*/false,
6563 /*isInline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006564 /*isImplicitlyDeclared=*/true,
6565 // FIXME: apply the rules for definitions here
6566 /*isConstexpr=*/false);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006567 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006568 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006569 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006570 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006571
6572 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006573 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6574
Douglas Gregor23c94db2010-07-02 17:43:08 +00006575 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006576 PushOnScopeChains(DefaultCon, S, false);
6577 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006578
6579 if (ShouldDeleteDefaultConstructor(DefaultCon))
6580 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006581
Douglas Gregor32df23e2010-07-01 22:02:46 +00006582 return DefaultCon;
6583}
6584
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006585void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6586 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006587 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006588 !Constructor->doesThisDeclarationHaveABody() &&
6589 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006590 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006591
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006592 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006593 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006594
Douglas Gregor39957dc2010-05-01 15:04:51 +00006595 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006596 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006597 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006598 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006599 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006600 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006601 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006602 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006603 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006604
6605 SourceLocation Loc = Constructor->getLocation();
6606 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6607
6608 Constructor->setUsed();
6609 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006610
6611 if (ASTMutationListener *L = getASTMutationListener()) {
6612 L->CompletedImplicitDefinition(Constructor);
6613 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006614}
6615
Richard Smith7a614d82011-06-11 17:19:42 +00006616/// Get any existing defaulted default constructor for the given class. Do not
6617/// implicitly define one if it does not exist.
6618static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6619 CXXRecordDecl *D) {
6620 ASTContext &Context = Self.Context;
6621 QualType ClassType = Context.getTypeDeclType(D);
6622 DeclarationName ConstructorName
6623 = Context.DeclarationNames.getCXXConstructorName(
6624 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6625
6626 DeclContext::lookup_const_iterator Con, ConEnd;
6627 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6628 Con != ConEnd; ++Con) {
6629 // A function template cannot be defaulted.
6630 if (isa<FunctionTemplateDecl>(*Con))
6631 continue;
6632
6633 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6634 if (Constructor->isDefaultConstructor())
6635 return Constructor->isDefaulted() ? Constructor : 0;
6636 }
6637 return 0;
6638}
6639
6640void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6641 if (!D) return;
6642 AdjustDeclIfTemplate(D);
6643
6644 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6645 CXXConstructorDecl *CtorDecl
6646 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6647
6648 if (!CtorDecl) return;
6649
6650 // Compute the exception specification for the default constructor.
6651 const FunctionProtoType *CtorTy =
6652 CtorDecl->getType()->castAs<FunctionProtoType>();
6653 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6654 ImplicitExceptionSpecification Spec =
6655 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6656 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6657 assert(EPI.ExceptionSpecType != EST_Delayed);
6658
6659 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6660 }
6661
6662 // If the default constructor is explicitly defaulted, checking the exception
6663 // specification is deferred until now.
6664 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6665 !ClassDecl->isDependentType())
6666 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6667}
6668
Sebastian Redlf677ea32011-02-05 19:23:19 +00006669void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6670 // We start with an initial pass over the base classes to collect those that
6671 // inherit constructors from. If there are none, we can forgo all further
6672 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006673 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006674 BasesVector BasesToInheritFrom;
6675 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6676 BaseE = ClassDecl->bases_end();
6677 BaseIt != BaseE; ++BaseIt) {
6678 if (BaseIt->getInheritConstructors()) {
6679 QualType Base = BaseIt->getType();
6680 if (Base->isDependentType()) {
6681 // If we inherit constructors from anything that is dependent, just
6682 // abort processing altogether. We'll get another chance for the
6683 // instantiations.
6684 return;
6685 }
6686 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6687 }
6688 }
6689 if (BasesToInheritFrom.empty())
6690 return;
6691
6692 // Now collect the constructors that we already have in the current class.
6693 // Those take precedence over inherited constructors.
6694 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6695 // unless there is a user-declared constructor with the same signature in
6696 // the class where the using-declaration appears.
6697 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6698 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6699 CtorE = ClassDecl->ctor_end();
6700 CtorIt != CtorE; ++CtorIt) {
6701 ExistingConstructors.insert(
6702 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6703 }
6704
6705 Scope *S = getScopeForContext(ClassDecl);
6706 DeclarationName CreatedCtorName =
6707 Context.DeclarationNames.getCXXConstructorName(
6708 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6709
6710 // Now comes the true work.
6711 // First, we keep a map from constructor types to the base that introduced
6712 // them. Needed for finding conflicting constructors. We also keep the
6713 // actually inserted declarations in there, for pretty diagnostics.
6714 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6715 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6716 ConstructorToSourceMap InheritedConstructors;
6717 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6718 BaseE = BasesToInheritFrom.end();
6719 BaseIt != BaseE; ++BaseIt) {
6720 const RecordType *Base = *BaseIt;
6721 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6722 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6723 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6724 CtorE = BaseDecl->ctor_end();
6725 CtorIt != CtorE; ++CtorIt) {
6726 // Find the using declaration for inheriting this base's constructors.
6727 DeclarationName Name =
6728 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6729 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6730 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6731 SourceLocation UsingLoc = UD ? UD->getLocation() :
6732 ClassDecl->getLocation();
6733
6734 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6735 // from the class X named in the using-declaration consists of actual
6736 // constructors and notional constructors that result from the
6737 // transformation of defaulted parameters as follows:
6738 // - all non-template default constructors of X, and
6739 // - for each non-template constructor of X that has at least one
6740 // parameter with a default argument, the set of constructors that
6741 // results from omitting any ellipsis parameter specification and
6742 // successively omitting parameters with a default argument from the
6743 // end of the parameter-type-list.
6744 CXXConstructorDecl *BaseCtor = *CtorIt;
6745 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6746 const FunctionProtoType *BaseCtorType =
6747 BaseCtor->getType()->getAs<FunctionProtoType>();
6748
6749 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6750 maxParams = BaseCtor->getNumParams();
6751 params <= maxParams; ++params) {
6752 // Skip default constructors. They're never inherited.
6753 if (params == 0)
6754 continue;
6755 // Skip copy and move constructors for the same reason.
6756 if (CanBeCopyOrMove && params == 1)
6757 continue;
6758
6759 // Build up a function type for this particular constructor.
6760 // FIXME: The working paper does not consider that the exception spec
6761 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006762 // source. This code doesn't yet, either. When it does, this code will
6763 // need to be delayed until after exception specifications and in-class
6764 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006765 const Type *NewCtorType;
6766 if (params == maxParams)
6767 NewCtorType = BaseCtorType;
6768 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006769 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006770 for (unsigned i = 0; i < params; ++i) {
6771 Args.push_back(BaseCtorType->getArgType(i));
6772 }
6773 FunctionProtoType::ExtProtoInfo ExtInfo =
6774 BaseCtorType->getExtProtoInfo();
6775 ExtInfo.Variadic = false;
6776 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6777 Args.data(), params, ExtInfo)
6778 .getTypePtr();
6779 }
6780 const Type *CanonicalNewCtorType =
6781 Context.getCanonicalType(NewCtorType);
6782
6783 // Now that we have the type, first check if the class already has a
6784 // constructor with this signature.
6785 if (ExistingConstructors.count(CanonicalNewCtorType))
6786 continue;
6787
6788 // Then we check if we have already declared an inherited constructor
6789 // with this signature.
6790 std::pair<ConstructorToSourceMap::iterator, bool> result =
6791 InheritedConstructors.insert(std::make_pair(
6792 CanonicalNewCtorType,
6793 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6794 if (!result.second) {
6795 // Already in the map. If it came from a different class, that's an
6796 // error. Not if it's from the same.
6797 CanQualType PreviousBase = result.first->second.first;
6798 if (CanonicalBase != PreviousBase) {
6799 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6800 const CXXConstructorDecl *PrevBaseCtor =
6801 PrevCtor->getInheritedConstructor();
6802 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6803
6804 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6805 Diag(BaseCtor->getLocation(),
6806 diag::note_using_decl_constructor_conflict_current_ctor);
6807 Diag(PrevBaseCtor->getLocation(),
6808 diag::note_using_decl_constructor_conflict_previous_ctor);
6809 Diag(PrevCtor->getLocation(),
6810 diag::note_using_decl_constructor_conflict_previous_using);
6811 }
6812 continue;
6813 }
6814
6815 // OK, we're there, now add the constructor.
6816 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006817 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00006818 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6819 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006820 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6821 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006822 /*ImplicitlyDeclared=*/true,
6823 // FIXME: Due to a defect in the standard, we treat inherited
6824 // constructors as constexpr even if that makes them ill-formed.
6825 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00006826 NewCtor->setAccess(BaseCtor->getAccess());
6827
6828 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006829 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006830 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006831 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6832 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006833 /*IdentifierInfo=*/0,
6834 BaseCtorType->getArgType(i),
6835 /*TInfo=*/0, SC_None,
6836 SC_None, /*DefaultArg=*/0));
6837 }
David Blaikie4278c652011-09-21 18:16:56 +00006838 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006839 NewCtor->setInheritedConstructor(BaseCtor);
6840
6841 PushOnScopeChains(NewCtor, S, false);
6842 ClassDecl->addDecl(NewCtor);
6843 result.first->second.second = NewCtor;
6844 }
6845 }
6846 }
6847}
6848
Sean Huntcb45a0f2011-05-12 22:46:25 +00006849Sema::ImplicitExceptionSpecification
6850Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006851 // C++ [except.spec]p14:
6852 // An implicitly declared special member function (Clause 12) shall have
6853 // an exception-specification.
6854 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006855 if (ClassDecl->isInvalidDecl())
6856 return ExceptSpec;
6857
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006858 // Direct base-class destructors.
6859 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6860 BEnd = ClassDecl->bases_end();
6861 B != BEnd; ++B) {
6862 if (B->isVirtual()) // Handled below.
6863 continue;
6864
6865 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6866 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006867 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006868 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006869
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006870 // Virtual base-class destructors.
6871 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6872 BEnd = ClassDecl->vbases_end();
6873 B != BEnd; ++B) {
6874 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6875 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006876 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006877 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006878
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006879 // Field destructors.
6880 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6881 FEnd = ClassDecl->field_end();
6882 F != FEnd; ++F) {
6883 if (const RecordType *RecordTy
6884 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6885 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006886 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006887 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006888
Sean Huntcb45a0f2011-05-12 22:46:25 +00006889 return ExceptSpec;
6890}
6891
6892CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6893 // C++ [class.dtor]p2:
6894 // If a class has no user-declared destructor, a destructor is
6895 // declared implicitly. An implicitly-declared destructor is an
6896 // inline public member of its class.
6897
6898 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00006899 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006900 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6901
Douglas Gregor4923aa22010-07-02 20:37:36 +00006902 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00006903 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00006904
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006905 CanQualType ClassType
6906 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006907 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006908 DeclarationName Name
6909 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006910 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006911 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00006912 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6913 /*isInline=*/true,
6914 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006915 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006916 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006917 Destructor->setImplicit();
6918 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00006919
6920 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00006921 ++ASTContext::NumImplicitDestructorsDeclared;
6922
6923 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006924 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00006925 PushOnScopeChains(Destructor, S, false);
6926 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006927
6928 // This could be uniqued if it ever proves significant.
6929 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00006930
6931 if (ShouldDeleteDestructor(Destructor))
6932 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006933
6934 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00006935
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006936 return Destructor;
6937}
6938
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006939void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00006940 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00006941 assert((Destructor->isDefaulted() &&
6942 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006943 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00006944 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006945 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006946
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006947 if (Destructor->isInvalidDecl())
6948 return;
6949
Douglas Gregor39957dc2010-05-01 15:04:51 +00006950 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006951
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006952 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00006953 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6954 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00006955
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006956 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006957 Diag(CurrentLocation, diag::note_member_synthesized_at)
6958 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6959
6960 Destructor->setInvalidDecl();
6961 return;
6962 }
6963
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006964 SourceLocation Loc = Destructor->getLocation();
6965 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6966
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006967 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006968 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006969
6970 if (ASTMutationListener *L = getASTMutationListener()) {
6971 L->CompletedImplicitDefinition(Destructor);
6972 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006973}
6974
Sebastian Redl0ee33912011-05-19 05:13:44 +00006975void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6976 CXXDestructorDecl *destructor) {
6977 // C++11 [class.dtor]p3:
6978 // A declaration of a destructor that does not have an exception-
6979 // specification is implicitly considered to have the same exception-
6980 // specification as an implicit declaration.
6981 const FunctionProtoType *dtorType = destructor->getType()->
6982 getAs<FunctionProtoType>();
6983 if (dtorType->hasExceptionSpec())
6984 return;
6985
6986 ImplicitExceptionSpecification exceptSpec =
6987 ComputeDefaultedDtorExceptionSpec(classDecl);
6988
Chandler Carruth3f224b22011-09-20 04:55:26 +00006989 // Replace the destructor's type, building off the existing one. Fortunately,
6990 // the only thing of interest in the destructor type is its extended info.
6991 // The return and arguments are fixed.
6992 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00006993 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6994 epi.NumExceptions = exceptSpec.size();
6995 epi.Exceptions = exceptSpec.data();
6996 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6997
6998 destructor->setType(ty);
6999
7000 // FIXME: If the destructor has a body that could throw, and the newly created
7001 // spec doesn't allow exceptions, we should emit a warning, because this
7002 // change in behavior can break conforming C++03 programs at runtime.
7003 // However, we don't have a body yet, so it needs to be done somewhere else.
7004}
7005
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007006/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007007/// \c To.
7008///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007009/// This routine is used to copy/move the members of a class with an
7010/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007011/// copied are arrays, this routine builds for loops to copy them.
7012///
7013/// \param S The Sema object used for type-checking.
7014///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007015/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007016///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007017/// \param T The type of the expressions being copied/moved. Both expressions
7018/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007019///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007020/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007021///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007022/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007023///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007024/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007025/// Otherwise, it's a non-static member subobject.
7026///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007027/// \param Copying Whether we're copying or moving.
7028///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007029/// \param Depth Internal parameter recording the depth of the recursion.
7030///
7031/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007032static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007033BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007034 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007035 bool CopyingBaseSubobject, bool Copying,
7036 unsigned Depth = 0) {
7037 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007038 // Each subobject is assigned in the manner appropriate to its type:
7039 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007040 // - if the subobject is of class type, as if by a call to operator= with
7041 // the subobject as the object expression and the corresponding
7042 // subobject of x as a single function argument (as if by explicit
7043 // qualification; that is, ignoring any possible virtual overriding
7044 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007045 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7046 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7047
7048 // Look for operator=.
7049 DeclarationName Name
7050 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7051 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7052 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7053
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007054 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007055 LookupResult::Filter F = OpLookup.makeFilter();
7056 while (F.hasNext()) {
7057 NamedDecl *D = F.next();
7058 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007059 if (Copying ? Method->isCopyAssignmentOperator() :
7060 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007061 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007062
Douglas Gregor06a9f362010-05-01 20:49:11 +00007063 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007064 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007065 F.done();
7066
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007067 // Suppress the protected check (C++ [class.protected]) for each of the
7068 // assignment operators we found. This strange dance is required when
7069 // we're assigning via a base classes's copy-assignment operator. To
7070 // ensure that we're getting the right base class subobject (without
7071 // ambiguities), we need to cast "this" to that subobject type; to
7072 // ensure that we don't go through the virtual call mechanism, we need
7073 // to qualify the operator= name with the base class (see below). However,
7074 // this means that if the base class has a protected copy assignment
7075 // operator, the protected member access check will fail. So, we
7076 // rewrite "protected" access to "public" access in this case, since we
7077 // know by construction that we're calling from a derived class.
7078 if (CopyingBaseSubobject) {
7079 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7080 L != LEnd; ++L) {
7081 if (L.getAccess() == AS_protected)
7082 L.setAccess(AS_public);
7083 }
7084 }
7085
Douglas Gregor06a9f362010-05-01 20:49:11 +00007086 // Create the nested-name-specifier that will be used to qualify the
7087 // reference to operator=; this is required to suppress the virtual
7088 // call mechanism.
7089 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00007090 SS.MakeTrivial(S.Context,
7091 NestedNameSpecifier::Create(S.Context, 0, false,
7092 T.getTypePtr()),
7093 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007094
7095 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007096 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007097 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007098 /*FirstQualifierInScope=*/0, OpLookup,
7099 /*TemplateArgs=*/0,
7100 /*SuppressQualifierCheck=*/true);
7101 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007102 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007103
7104 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007105
John McCall60d7b3a2010-08-24 06:29:42 +00007106 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007107 OpEqualRef.takeAs<Expr>(),
7108 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007109 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007110 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007111
7112 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007113 }
John McCallb0207482010-03-16 06:11:48 +00007114
Douglas Gregor06a9f362010-05-01 20:49:11 +00007115 // - if the subobject is of scalar type, the built-in assignment
7116 // operator is used.
7117 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7118 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007119 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007120 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007121 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007122
7123 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007124 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007125
7126 // - if the subobject is an array, each element is assigned, in the
7127 // manner appropriate to the element type;
7128
7129 // Construct a loop over the array bounds, e.g.,
7130 //
7131 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7132 //
7133 // that will copy each of the array elements.
7134 QualType SizeType = S.Context.getSizeType();
7135
7136 // Create the iteration variable.
7137 IdentifierInfo *IterationVarName = 0;
7138 {
7139 llvm::SmallString<8> Str;
7140 llvm::raw_svector_ostream OS(Str);
7141 OS << "__i" << Depth;
7142 IterationVarName = &S.Context.Idents.get(OS.str());
7143 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007144 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007145 IterationVarName, SizeType,
7146 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007147 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007148
7149 // Initialize the iteration variable to zero.
7150 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007151 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007152
7153 // Create a reference to the iteration variable; we'll use this several
7154 // times throughout.
7155 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00007156 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007157 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7158
7159 // Create the DeclStmt that holds the iteration variable.
7160 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7161
7162 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007163 llvm::APInt Upper
7164 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007165 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00007166 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00007167 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7168 BO_NE, S.Context.BoolTy,
7169 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007170
7171 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007172 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007173 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7174 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007175
7176 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007177 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7178 IterationVarRef, Loc));
7179 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7180 IterationVarRef, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007181 if (!Copying) // Cast to rvalue
7182 From = CastForMoving(S, From);
7183
7184 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007185 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7186 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007187 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007188 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007189 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007190
7191 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007192 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007193 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007194 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007195 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007196}
7197
Sean Hunt30de05c2011-05-14 05:23:20 +00007198std::pair<Sema::ImplicitExceptionSpecification, bool>
7199Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7200 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007201 if (ClassDecl->isInvalidDecl())
7202 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7203
Douglas Gregord3c35902010-07-01 16:36:15 +00007204 // C++ [class.copy]p10:
7205 // If the class definition does not explicitly declare a copy
7206 // assignment operator, one is declared implicitly.
7207 // The implicitly-defined copy assignment operator for a class X
7208 // will have the form
7209 //
7210 // X& X::operator=(const X&)
7211 //
7212 // if
7213 bool HasConstCopyAssignment = true;
7214
7215 // -- each direct base class B of X has a copy assignment operator
7216 // whose parameter is of type const B&, const volatile B& or B,
7217 // and
7218 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7219 BaseEnd = ClassDecl->bases_end();
7220 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007221 // We'll handle this below
7222 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7223 continue;
7224
Douglas Gregord3c35902010-07-01 16:36:15 +00007225 assert(!Base->getType()->isDependentType() &&
7226 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007227 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7228 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7229 &HasConstCopyAssignment);
7230 }
7231
7232 // In C++0x, the above citation has "or virtual added"
7233 if (LangOpts.CPlusPlus0x) {
7234 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7235 BaseEnd = ClassDecl->vbases_end();
7236 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7237 assert(!Base->getType()->isDependentType() &&
7238 "Cannot generate implicit members for class with dependent bases.");
7239 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7240 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7241 &HasConstCopyAssignment);
7242 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007243 }
7244
7245 // -- for all the nonstatic data members of X that are of a class
7246 // type M (or array thereof), each such class type has a copy
7247 // assignment operator whose parameter is of type const M&,
7248 // const volatile M& or M.
7249 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7250 FieldEnd = ClassDecl->field_end();
7251 HasConstCopyAssignment && Field != FieldEnd;
7252 ++Field) {
7253 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007254 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7255 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7256 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007257 }
7258 }
7259
7260 // Otherwise, the implicitly declared copy assignment operator will
7261 // have the form
7262 //
7263 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007264
Douglas Gregorb87786f2010-07-01 17:48:08 +00007265 // C++ [except.spec]p14:
7266 // An implicitly declared special member function (Clause 12) shall have an
7267 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007268
7269 // It is unspecified whether or not an implicit copy assignment operator
7270 // attempts to deduplicate calls to assignment operators of virtual bases are
7271 // made. As such, this exception specification is effectively unspecified.
7272 // Based on a similar decision made for constness in C++0x, we're erring on
7273 // the side of assuming such calls to be made regardless of whether they
7274 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007275 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007276 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007277 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7278 BaseEnd = ClassDecl->bases_end();
7279 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007280 if (Base->isVirtual())
7281 continue;
7282
Douglas Gregora376d102010-07-02 21:50:04 +00007283 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007284 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007285 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7286 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007287 ExceptSpec.CalledDecl(CopyAssign);
7288 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007289
7290 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7291 BaseEnd = ClassDecl->vbases_end();
7292 Base != BaseEnd; ++Base) {
7293 CXXRecordDecl *BaseClassDecl
7294 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7295 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7296 ArgQuals, false, 0))
7297 ExceptSpec.CalledDecl(CopyAssign);
7298 }
7299
Douglas Gregorb87786f2010-07-01 17:48:08 +00007300 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7301 FieldEnd = ClassDecl->field_end();
7302 Field != FieldEnd;
7303 ++Field) {
7304 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007305 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7306 if (CXXMethodDecl *CopyAssign =
7307 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7308 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007309 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007310 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007311
Sean Hunt30de05c2011-05-14 05:23:20 +00007312 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7313}
7314
7315CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7316 // Note: The following rules are largely analoguous to the copy
7317 // constructor rules. Note that virtual bases are not taken into account
7318 // for determining the argument type of the operator. Note also that
7319 // operators taking an object instead of a reference are allowed.
7320
7321 ImplicitExceptionSpecification Spec(Context);
7322 bool Const;
7323 llvm::tie(Spec, Const) =
7324 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7325
7326 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7327 QualType RetType = Context.getLValueReferenceType(ArgType);
7328 if (Const)
7329 ArgType = ArgType.withConst();
7330 ArgType = Context.getLValueReferenceType(ArgType);
7331
Douglas Gregord3c35902010-07-01 16:36:15 +00007332 // An implicitly-declared copy assignment operator is an inline public
7333 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007334 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007335 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007336 SourceLocation ClassLoc = ClassDecl->getLocation();
7337 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007338 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007339 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007340 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007341 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007342 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007343 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007344 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007345 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007346 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007347 CopyAssignment->setImplicit();
7348 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007349
7350 // Add the parameter to the operator.
7351 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007352 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007353 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007354 SC_None,
7355 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007356 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007357
Douglas Gregora376d102010-07-02 21:50:04 +00007358 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007359 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007360
Douglas Gregor23c94db2010-07-02 17:43:08 +00007361 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007362 PushOnScopeChains(CopyAssignment, S, false);
7363 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007364
Sean Hunt1ccbc542011-06-22 01:05:13 +00007365 // C++0x [class.copy]p18:
7366 // ... If the class definition declares a move constructor or move
7367 // assignment operator, the implicitly declared copy assignment operator is
7368 // defined as deleted; ...
7369 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7370 ClassDecl->hasUserDeclaredMoveAssignment() ||
7371 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007372 CopyAssignment->setDeletedAsWritten();
7373
Douglas Gregord3c35902010-07-01 16:36:15 +00007374 AddOverriddenMethods(ClassDecl, CopyAssignment);
7375 return CopyAssignment;
7376}
7377
Douglas Gregor06a9f362010-05-01 20:49:11 +00007378void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7379 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007380 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007381 CopyAssignOperator->isOverloadedOperator() &&
7382 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007383 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007384 "DefineImplicitCopyAssignment called for wrong function");
7385
7386 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7387
7388 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7389 CopyAssignOperator->setInvalidDecl();
7390 return;
7391 }
7392
7393 CopyAssignOperator->setUsed();
7394
7395 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007396 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007397
7398 // C++0x [class.copy]p30:
7399 // The implicitly-defined or explicitly-defaulted copy assignment operator
7400 // for a non-union class X performs memberwise copy assignment of its
7401 // subobjects. The direct base classes of X are assigned first, in the
7402 // order of their declaration in the base-specifier-list, and then the
7403 // immediate non-static data members of X are assigned, in the order in
7404 // which they were declared in the class definition.
7405
7406 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007407 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007408
7409 // The parameter for the "other" object, which we are copying from.
7410 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7411 Qualifiers OtherQuals = Other->getType().getQualifiers();
7412 QualType OtherRefType = Other->getType();
7413 if (const LValueReferenceType *OtherRef
7414 = OtherRefType->getAs<LValueReferenceType>()) {
7415 OtherRefType = OtherRef->getPointeeType();
7416 OtherQuals = OtherRefType.getQualifiers();
7417 }
7418
7419 // Our location for everything implicitly-generated.
7420 SourceLocation Loc = CopyAssignOperator->getLocation();
7421
7422 // Construct a reference to the "other" object. We'll be using this
7423 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007424 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007425 assert(OtherRef && "Reference to parameter cannot fail!");
7426
7427 // Construct the "this" pointer. We'll be using this throughout the generated
7428 // ASTs.
7429 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7430 assert(This && "Reference to this cannot fail!");
7431
7432 // Assign base classes.
7433 bool Invalid = false;
7434 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7435 E = ClassDecl->bases_end(); Base != E; ++Base) {
7436 // Form the assignment:
7437 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7438 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007439 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007440 Invalid = true;
7441 continue;
7442 }
7443
John McCallf871d0c2010-08-07 06:22:56 +00007444 CXXCastPath BasePath;
7445 BasePath.push_back(Base);
7446
Douglas Gregor06a9f362010-05-01 20:49:11 +00007447 // Construct the "from" expression, which is an implicit cast to the
7448 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007449 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007450 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7451 CK_UncheckedDerivedToBase,
7452 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007453
7454 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007455 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007456
7457 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007458 To = ImpCastExprToType(To.take(),
7459 Context.getCVRQualifiedType(BaseType,
7460 CopyAssignOperator->getTypeQualifiers()),
7461 CK_UncheckedDerivedToBase,
7462 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007463
7464 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007465 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007466 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007467 /*CopyingBaseSubobject=*/true,
7468 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007469 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007470 Diag(CurrentLocation, diag::note_member_synthesized_at)
7471 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7472 CopyAssignOperator->setInvalidDecl();
7473 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007474 }
7475
7476 // Success! Record the copy.
7477 Statements.push_back(Copy.takeAs<Expr>());
7478 }
7479
7480 // \brief Reference to the __builtin_memcpy function.
7481 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007482 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007483 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007484
7485 // Assign non-static members.
7486 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7487 FieldEnd = ClassDecl->field_end();
7488 Field != FieldEnd; ++Field) {
7489 // Check for members of reference type; we can't copy those.
7490 if (Field->getType()->isReferenceType()) {
7491 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7492 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7493 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007494 Diag(CurrentLocation, diag::note_member_synthesized_at)
7495 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007496 Invalid = true;
7497 continue;
7498 }
7499
7500 // Check for members of const-qualified, non-class type.
7501 QualType BaseType = Context.getBaseElementType(Field->getType());
7502 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7503 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7504 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7505 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007506 Diag(CurrentLocation, diag::note_member_synthesized_at)
7507 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007508 Invalid = true;
7509 continue;
7510 }
John McCallb77115d2011-06-17 00:18:42 +00007511
7512 // Suppress assigning zero-width bitfields.
7513 if (const Expr *Width = Field->getBitWidth())
7514 if (Width->EvaluateAsInt(Context) == 0)
7515 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007516
7517 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007518 if (FieldType->isIncompleteArrayType()) {
7519 assert(ClassDecl->hasFlexibleArrayMember() &&
7520 "Incomplete array type is not valid");
7521 continue;
7522 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007523
7524 // Build references to the field in the object we're copying from and to.
7525 CXXScopeSpec SS; // Intentionally empty
7526 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7527 LookupMemberName);
7528 MemberLookup.addDecl(*Field);
7529 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007530 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007531 Loc, /*IsArrow=*/false,
7532 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007533 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007534 Loc, /*IsArrow=*/true,
7535 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007536 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7537 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7538
7539 // If the field should be copied with __builtin_memcpy rather than via
7540 // explicit assignments, do so. This optimization only applies for arrays
7541 // of scalars and arrays of class type with trivial copy-assignment
7542 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007543 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007544 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007545 // Compute the size of the memory buffer to be copied.
7546 QualType SizeType = Context.getSizeType();
7547 llvm::APInt Size(Context.getTypeSize(SizeType),
7548 Context.getTypeSizeInChars(BaseType).getQuantity());
7549 for (const ConstantArrayType *Array
7550 = Context.getAsConstantArrayType(FieldType);
7551 Array;
7552 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007553 llvm::APInt ArraySize
7554 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007555 Size *= ArraySize;
7556 }
7557
7558 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007559 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7560 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007561
7562 bool NeedsCollectableMemCpy =
7563 (BaseType->isRecordType() &&
7564 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7565
7566 if (NeedsCollectableMemCpy) {
7567 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007568 // Create a reference to the __builtin_objc_memmove_collectable function.
7569 LookupResult R(*this,
7570 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007571 Loc, LookupOrdinaryName);
7572 LookupName(R, TUScope, true);
7573
7574 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7575 if (!CollectableMemCpy) {
7576 // Something went horribly wrong earlier, and we will have
7577 // complained about it.
7578 Invalid = true;
7579 continue;
7580 }
7581
7582 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7583 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007584 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007585 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7586 }
7587 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007588 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007589 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007590 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7591 LookupOrdinaryName);
7592 LookupName(R, TUScope, true);
7593
7594 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7595 if (!BuiltinMemCpy) {
7596 // Something went horribly wrong earlier, and we will have complained
7597 // about it.
7598 Invalid = true;
7599 continue;
7600 }
7601
7602 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7603 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007604 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007605 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7606 }
7607
John McCallca0408f2010-08-23 06:44:23 +00007608 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007609 CallArgs.push_back(To.takeAs<Expr>());
7610 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007611 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007612 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007613 if (NeedsCollectableMemCpy)
7614 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007615 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007616 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007617 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007618 else
7619 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007620 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007621 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007622 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007623
Douglas Gregor06a9f362010-05-01 20:49:11 +00007624 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7625 Statements.push_back(Call.takeAs<Expr>());
7626 continue;
7627 }
7628
7629 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007630 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007631 To.get(), From.get(),
7632 /*CopyingBaseSubobject=*/false,
7633 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007634 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007635 Diag(CurrentLocation, diag::note_member_synthesized_at)
7636 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7637 CopyAssignOperator->setInvalidDecl();
7638 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007639 }
7640
7641 // Success! Record the copy.
7642 Statements.push_back(Copy.takeAs<Stmt>());
7643 }
7644
7645 if (!Invalid) {
7646 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007647 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007648
John McCall60d7b3a2010-08-24 06:29:42 +00007649 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007650 if (Return.isInvalid())
7651 Invalid = true;
7652 else {
7653 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007654
7655 if (Trap.hasErrorOccurred()) {
7656 Diag(CurrentLocation, diag::note_member_synthesized_at)
7657 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7658 Invalid = true;
7659 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007660 }
7661 }
7662
7663 if (Invalid) {
7664 CopyAssignOperator->setInvalidDecl();
7665 return;
7666 }
7667
John McCall60d7b3a2010-08-24 06:29:42 +00007668 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00007669 /*isStmtExpr=*/false);
7670 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7671 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007672
7673 if (ASTMutationListener *L = getASTMutationListener()) {
7674 L->CompletedImplicitDefinition(CopyAssignOperator);
7675 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007676}
7677
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007678Sema::ImplicitExceptionSpecification
7679Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7680 ImplicitExceptionSpecification ExceptSpec(Context);
7681
7682 if (ClassDecl->isInvalidDecl())
7683 return ExceptSpec;
7684
7685 // C++0x [except.spec]p14:
7686 // An implicitly declared special member function (Clause 12) shall have an
7687 // exception-specification. [...]
7688
7689 // It is unspecified whether or not an implicit move assignment operator
7690 // attempts to deduplicate calls to assignment operators of virtual bases are
7691 // made. As such, this exception specification is effectively unspecified.
7692 // Based on a similar decision made for constness in C++0x, we're erring on
7693 // the side of assuming such calls to be made regardless of whether they
7694 // actually happen.
7695 // Note that a move constructor is not implicitly declared when there are
7696 // virtual bases, but it can still be user-declared and explicitly defaulted.
7697 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7698 BaseEnd = ClassDecl->bases_end();
7699 Base != BaseEnd; ++Base) {
7700 if (Base->isVirtual())
7701 continue;
7702
7703 CXXRecordDecl *BaseClassDecl
7704 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7705 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7706 false, 0))
7707 ExceptSpec.CalledDecl(MoveAssign);
7708 }
7709
7710 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7711 BaseEnd = ClassDecl->vbases_end();
7712 Base != BaseEnd; ++Base) {
7713 CXXRecordDecl *BaseClassDecl
7714 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7715 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7716 false, 0))
7717 ExceptSpec.CalledDecl(MoveAssign);
7718 }
7719
7720 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7721 FieldEnd = ClassDecl->field_end();
7722 Field != FieldEnd;
7723 ++Field) {
7724 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7725 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7726 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7727 false, 0))
7728 ExceptSpec.CalledDecl(MoveAssign);
7729 }
7730 }
7731
7732 return ExceptSpec;
7733}
7734
7735CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
7736 // Note: The following rules are largely analoguous to the move
7737 // constructor rules.
7738
7739 ImplicitExceptionSpecification Spec(
7740 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7741
7742 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7743 QualType RetType = Context.getLValueReferenceType(ArgType);
7744 ArgType = Context.getRValueReferenceType(ArgType);
7745
7746 // An implicitly-declared move assignment operator is an inline public
7747 // member of its class.
7748 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7749 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7750 SourceLocation ClassLoc = ClassDecl->getLocation();
7751 DeclarationNameInfo NameInfo(Name, ClassLoc);
7752 CXXMethodDecl *MoveAssignment
7753 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7754 Context.getFunctionType(RetType, &ArgType, 1, EPI),
7755 /*TInfo=*/0, /*isStatic=*/false,
7756 /*StorageClassAsWritten=*/SC_None,
7757 /*isInline=*/true,
7758 /*isConstexpr=*/false,
7759 SourceLocation());
7760 MoveAssignment->setAccess(AS_public);
7761 MoveAssignment->setDefaulted();
7762 MoveAssignment->setImplicit();
7763 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
7764
7765 // Add the parameter to the operator.
7766 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
7767 ClassLoc, ClassLoc, /*Id=*/0,
7768 ArgType, /*TInfo=*/0,
7769 SC_None,
7770 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007771 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007772
7773 // Note that we have added this copy-assignment operator.
7774 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
7775
7776 // C++0x [class.copy]p9:
7777 // If the definition of a class X does not explicitly declare a move
7778 // assignment operator, one will be implicitly declared as defaulted if and
7779 // only if:
7780 // [...]
7781 // - the move assignment operator would not be implicitly defined as
7782 // deleted.
7783 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
7784 // Cache this result so that we don't try to generate this over and over
7785 // on every lookup, leaking memory and wasting time.
7786 ClassDecl->setFailedImplicitMoveAssignment();
7787 return 0;
7788 }
7789
7790 if (Scope *S = getScopeForContext(ClassDecl))
7791 PushOnScopeChains(MoveAssignment, S, false);
7792 ClassDecl->addDecl(MoveAssignment);
7793
7794 AddOverriddenMethods(ClassDecl, MoveAssignment);
7795 return MoveAssignment;
7796}
7797
7798void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
7799 CXXMethodDecl *MoveAssignOperator) {
7800 assert((MoveAssignOperator->isDefaulted() &&
7801 MoveAssignOperator->isOverloadedOperator() &&
7802 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
7803 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
7804 "DefineImplicitMoveAssignment called for wrong function");
7805
7806 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
7807
7808 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
7809 MoveAssignOperator->setInvalidDecl();
7810 return;
7811 }
7812
7813 MoveAssignOperator->setUsed();
7814
7815 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
7816 DiagnosticErrorTrap Trap(Diags);
7817
7818 // C++0x [class.copy]p28:
7819 // The implicitly-defined or move assignment operator for a non-union class
7820 // X performs memberwise move assignment of its subobjects. The direct base
7821 // classes of X are assigned first, in the order of their declaration in the
7822 // base-specifier-list, and then the immediate non-static data members of X
7823 // are assigned, in the order in which they were declared in the class
7824 // definition.
7825
7826 // The statements that form the synthesized function body.
7827 ASTOwningVector<Stmt*> Statements(*this);
7828
7829 // The parameter for the "other" object, which we are move from.
7830 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
7831 QualType OtherRefType = Other->getType()->
7832 getAs<RValueReferenceType>()->getPointeeType();
7833 assert(OtherRefType.getQualifiers() == 0 &&
7834 "Bad argument type of defaulted move assignment");
7835
7836 // Our location for everything implicitly-generated.
7837 SourceLocation Loc = MoveAssignOperator->getLocation();
7838
7839 // Construct a reference to the "other" object. We'll be using this
7840 // throughout the generated ASTs.
7841 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7842 assert(OtherRef && "Reference to parameter cannot fail!");
7843 // Cast to rvalue.
7844 OtherRef = CastForMoving(*this, OtherRef);
7845
7846 // Construct the "this" pointer. We'll be using this throughout the generated
7847 // ASTs.
7848 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7849 assert(This && "Reference to this cannot fail!");
7850
7851 // Assign base classes.
7852 bool Invalid = false;
7853 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7854 E = ClassDecl->bases_end(); Base != E; ++Base) {
7855 // Form the assignment:
7856 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
7857 QualType BaseType = Base->getType().getUnqualifiedType();
7858 if (!BaseType->isRecordType()) {
7859 Invalid = true;
7860 continue;
7861 }
7862
7863 CXXCastPath BasePath;
7864 BasePath.push_back(Base);
7865
7866 // Construct the "from" expression, which is an implicit cast to the
7867 // appropriately-qualified base type.
7868 Expr *From = OtherRef;
7869 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00007870 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007871
7872 // Dereference "this".
7873 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7874
7875 // Implicitly cast "this" to the appropriately-qualified base type.
7876 To = ImpCastExprToType(To.take(),
7877 Context.getCVRQualifiedType(BaseType,
7878 MoveAssignOperator->getTypeQualifiers()),
7879 CK_UncheckedDerivedToBase,
7880 VK_LValue, &BasePath);
7881
7882 // Build the move.
7883 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
7884 To.get(), From,
7885 /*CopyingBaseSubobject=*/true,
7886 /*Copying=*/false);
7887 if (Move.isInvalid()) {
7888 Diag(CurrentLocation, diag::note_member_synthesized_at)
7889 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7890 MoveAssignOperator->setInvalidDecl();
7891 return;
7892 }
7893
7894 // Success! Record the move.
7895 Statements.push_back(Move.takeAs<Expr>());
7896 }
7897
7898 // \brief Reference to the __builtin_memcpy function.
7899 Expr *BuiltinMemCpyRef = 0;
7900 // \brief Reference to the __builtin_objc_memmove_collectable function.
7901 Expr *CollectableMemCpyRef = 0;
7902
7903 // Assign non-static members.
7904 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7905 FieldEnd = ClassDecl->field_end();
7906 Field != FieldEnd; ++Field) {
7907 // Check for members of reference type; we can't move those.
7908 if (Field->getType()->isReferenceType()) {
7909 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7910 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7911 Diag(Field->getLocation(), diag::note_declared_at);
7912 Diag(CurrentLocation, diag::note_member_synthesized_at)
7913 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7914 Invalid = true;
7915 continue;
7916 }
7917
7918 // Check for members of const-qualified, non-class type.
7919 QualType BaseType = Context.getBaseElementType(Field->getType());
7920 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7921 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7922 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7923 Diag(Field->getLocation(), diag::note_declared_at);
7924 Diag(CurrentLocation, diag::note_member_synthesized_at)
7925 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7926 Invalid = true;
7927 continue;
7928 }
7929
7930 // Suppress assigning zero-width bitfields.
7931 if (const Expr *Width = Field->getBitWidth())
7932 if (Width->EvaluateAsInt(Context) == 0)
7933 continue;
7934
7935 QualType FieldType = Field->getType().getNonReferenceType();
7936 if (FieldType->isIncompleteArrayType()) {
7937 assert(ClassDecl->hasFlexibleArrayMember() &&
7938 "Incomplete array type is not valid");
7939 continue;
7940 }
7941
7942 // Build references to the field in the object we're copying from and to.
7943 CXXScopeSpec SS; // Intentionally empty
7944 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7945 LookupMemberName);
7946 MemberLookup.addDecl(*Field);
7947 MemberLookup.resolveKind();
7948 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7949 Loc, /*IsArrow=*/false,
7950 SS, 0, MemberLookup, 0);
7951 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7952 Loc, /*IsArrow=*/true,
7953 SS, 0, MemberLookup, 0);
7954 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7955 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7956
7957 assert(!From.get()->isLValue() && // could be xvalue or prvalue
7958 "Member reference with rvalue base must be rvalue except for reference "
7959 "members, which aren't allowed for move assignment.");
7960
7961 // If the field should be copied with __builtin_memcpy rather than via
7962 // explicit assignments, do so. This optimization only applies for arrays
7963 // of scalars and arrays of class type with trivial move-assignment
7964 // operators.
7965 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7966 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
7967 // Compute the size of the memory buffer to be copied.
7968 QualType SizeType = Context.getSizeType();
7969 llvm::APInt Size(Context.getTypeSize(SizeType),
7970 Context.getTypeSizeInChars(BaseType).getQuantity());
7971 for (const ConstantArrayType *Array
7972 = Context.getAsConstantArrayType(FieldType);
7973 Array;
7974 Array = Context.getAsConstantArrayType(Array->getElementType())) {
7975 llvm::APInt ArraySize
7976 = Array->getSize().zextOrTrunc(Size.getBitWidth());
7977 Size *= ArraySize;
7978 }
7979
Douglas Gregor45d3d712011-09-01 02:09:07 +00007980 // Take the address of the field references for "from" and "to". We
7981 // directly construct UnaryOperators here because semantic analysis
7982 // does not permit us to take the address of an xvalue.
7983 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
7984 Context.getPointerType(From.get()->getType()),
7985 VK_RValue, OK_Ordinary, Loc);
7986 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
7987 Context.getPointerType(To.get()->getType()),
7988 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007989
7990 bool NeedsCollectableMemCpy =
7991 (BaseType->isRecordType() &&
7992 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7993
7994 if (NeedsCollectableMemCpy) {
7995 if (!CollectableMemCpyRef) {
7996 // Create a reference to the __builtin_objc_memmove_collectable function.
7997 LookupResult R(*this,
7998 &Context.Idents.get("__builtin_objc_memmove_collectable"),
7999 Loc, LookupOrdinaryName);
8000 LookupName(R, TUScope, true);
8001
8002 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8003 if (!CollectableMemCpy) {
8004 // Something went horribly wrong earlier, and we will have
8005 // complained about it.
8006 Invalid = true;
8007 continue;
8008 }
8009
8010 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8011 CollectableMemCpy->getType(),
8012 VK_LValue, Loc, 0).take();
8013 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8014 }
8015 }
8016 // Create a reference to the __builtin_memcpy builtin function.
8017 else if (!BuiltinMemCpyRef) {
8018 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8019 LookupOrdinaryName);
8020 LookupName(R, TUScope, true);
8021
8022 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8023 if (!BuiltinMemCpy) {
8024 // Something went horribly wrong earlier, and we will have complained
8025 // about it.
8026 Invalid = true;
8027 continue;
8028 }
8029
8030 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8031 BuiltinMemCpy->getType(),
8032 VK_LValue, Loc, 0).take();
8033 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8034 }
8035
8036 ASTOwningVector<Expr*> CallArgs(*this);
8037 CallArgs.push_back(To.takeAs<Expr>());
8038 CallArgs.push_back(From.takeAs<Expr>());
8039 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8040 ExprResult Call = ExprError();
8041 if (NeedsCollectableMemCpy)
8042 Call = ActOnCallExpr(/*Scope=*/0,
8043 CollectableMemCpyRef,
8044 Loc, move_arg(CallArgs),
8045 Loc);
8046 else
8047 Call = ActOnCallExpr(/*Scope=*/0,
8048 BuiltinMemCpyRef,
8049 Loc, move_arg(CallArgs),
8050 Loc);
8051
8052 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8053 Statements.push_back(Call.takeAs<Expr>());
8054 continue;
8055 }
8056
8057 // Build the move of this field.
8058 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8059 To.get(), From.get(),
8060 /*CopyingBaseSubobject=*/false,
8061 /*Copying=*/false);
8062 if (Move.isInvalid()) {
8063 Diag(CurrentLocation, diag::note_member_synthesized_at)
8064 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8065 MoveAssignOperator->setInvalidDecl();
8066 return;
8067 }
8068
8069 // Success! Record the copy.
8070 Statements.push_back(Move.takeAs<Stmt>());
8071 }
8072
8073 if (!Invalid) {
8074 // Add a "return *this;"
8075 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8076
8077 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8078 if (Return.isInvalid())
8079 Invalid = true;
8080 else {
8081 Statements.push_back(Return.takeAs<Stmt>());
8082
8083 if (Trap.hasErrorOccurred()) {
8084 Diag(CurrentLocation, diag::note_member_synthesized_at)
8085 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8086 Invalid = true;
8087 }
8088 }
8089 }
8090
8091 if (Invalid) {
8092 MoveAssignOperator->setInvalidDecl();
8093 return;
8094 }
8095
8096 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8097 /*isStmtExpr=*/false);
8098 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8099 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8100
8101 if (ASTMutationListener *L = getASTMutationListener()) {
8102 L->CompletedImplicitDefinition(MoveAssignOperator);
8103 }
8104}
8105
Sean Hunt49634cf2011-05-13 06:10:58 +00008106std::pair<Sema::ImplicitExceptionSpecification, bool>
8107Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008108 if (ClassDecl->isInvalidDecl())
8109 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8110
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008111 // C++ [class.copy]p5:
8112 // The implicitly-declared copy constructor for a class X will
8113 // have the form
8114 //
8115 // X::X(const X&)
8116 //
8117 // if
Sean Huntc530d172011-06-10 04:44:37 +00008118 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008119 bool HasConstCopyConstructor = true;
8120
8121 // -- each direct or virtual base class B of X has a copy
8122 // constructor whose first parameter is of type const B& or
8123 // const volatile B&, and
8124 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8125 BaseEnd = ClassDecl->bases_end();
8126 HasConstCopyConstructor && Base != BaseEnd;
8127 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008128 // Virtual bases are handled below.
8129 if (Base->isVirtual())
8130 continue;
8131
Douglas Gregor22584312010-07-02 23:41:54 +00008132 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008133 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008134 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8135 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008136 }
8137
8138 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8139 BaseEnd = ClassDecl->vbases_end();
8140 HasConstCopyConstructor && Base != BaseEnd;
8141 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008142 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008143 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008144 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8145 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008146 }
8147
8148 // -- for all the nonstatic data members of X that are of a
8149 // class type M (or array thereof), each such class type
8150 // has a copy constructor whose first parameter is of type
8151 // const M& or const volatile M&.
8152 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8153 FieldEnd = ClassDecl->field_end();
8154 HasConstCopyConstructor && Field != FieldEnd;
8155 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008156 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008157 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008158 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8159 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008160 }
8161 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008162 // Otherwise, the implicitly declared copy constructor will have
8163 // the form
8164 //
8165 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008166
Douglas Gregor0d405db2010-07-01 20:59:04 +00008167 // C++ [except.spec]p14:
8168 // An implicitly declared special member function (Clause 12) shall have an
8169 // exception-specification. [...]
8170 ImplicitExceptionSpecification ExceptSpec(Context);
8171 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8172 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8173 BaseEnd = ClassDecl->bases_end();
8174 Base != BaseEnd;
8175 ++Base) {
8176 // Virtual bases are handled below.
8177 if (Base->isVirtual())
8178 continue;
8179
Douglas Gregor22584312010-07-02 23:41:54 +00008180 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008181 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008182 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008183 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008184 ExceptSpec.CalledDecl(CopyConstructor);
8185 }
8186 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8187 BaseEnd = ClassDecl->vbases_end();
8188 Base != BaseEnd;
8189 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008190 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008191 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008192 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008193 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008194 ExceptSpec.CalledDecl(CopyConstructor);
8195 }
8196 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8197 FieldEnd = ClassDecl->field_end();
8198 Field != FieldEnd;
8199 ++Field) {
8200 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008201 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8202 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008203 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008204 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008205 }
8206 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008207
Sean Hunt49634cf2011-05-13 06:10:58 +00008208 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8209}
8210
8211CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8212 CXXRecordDecl *ClassDecl) {
8213 // C++ [class.copy]p4:
8214 // If the class definition does not explicitly declare a copy
8215 // constructor, one is declared implicitly.
8216
8217 ImplicitExceptionSpecification Spec(Context);
8218 bool Const;
8219 llvm::tie(Spec, Const) =
8220 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8221
8222 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8223 QualType ArgType = ClassType;
8224 if (Const)
8225 ArgType = ArgType.withConst();
8226 ArgType = Context.getLValueReferenceType(ArgType);
8227
8228 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8229
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008230 DeclarationName Name
8231 = Context.DeclarationNames.getCXXConstructorName(
8232 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008233 SourceLocation ClassLoc = ClassDecl->getLocation();
8234 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008235
8236 // An implicitly-declared copy constructor is an inline public
8237 // member of its class.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008238 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008239 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008240 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00008241 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008242 /*TInfo=*/0,
8243 /*isExplicit=*/false,
8244 /*isInline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008245 /*isImplicitlyDeclared=*/true,
8246 // FIXME: apply the rules for definitions here
8247 /*isConstexpr=*/false);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008248 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008249 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008250 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8251
Douglas Gregor22584312010-07-02 23:41:54 +00008252 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008253 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8254
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008255 // Add the parameter to the constructor.
8256 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008257 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008258 /*IdentifierInfo=*/0,
8259 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008260 SC_None,
8261 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008262 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008263
Douglas Gregor23c94db2010-07-02 17:43:08 +00008264 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008265 PushOnScopeChains(CopyConstructor, S, false);
8266 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008267
Sean Hunt1ccbc542011-06-22 01:05:13 +00008268 // C++0x [class.copy]p7:
8269 // ... If the class definition declares a move constructor or move
8270 // assignment operator, the implicitly declared constructor is defined as
8271 // deleted; ...
8272 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8273 ClassDecl->hasUserDeclaredMoveAssignment() ||
8274 ShouldDeleteCopyConstructor(CopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008275 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008276
8277 return CopyConstructor;
8278}
8279
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008280void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008281 CXXConstructorDecl *CopyConstructor) {
8282 assert((CopyConstructor->isDefaulted() &&
8283 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008284 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008285 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008286
Anders Carlsson63010a72010-04-23 16:24:12 +00008287 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008288 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008289
Douglas Gregor39957dc2010-05-01 15:04:51 +00008290 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008291 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008292
Sean Huntcbb67482011-01-08 20:30:50 +00008293 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008294 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008295 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008296 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008297 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008298 } else {
8299 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8300 CopyConstructor->getLocation(),
8301 MultiStmtArg(*this, 0, 0),
8302 /*isStmtExpr=*/false)
8303 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008304 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008305
8306 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008307
8308 if (ASTMutationListener *L = getASTMutationListener()) {
8309 L->CompletedImplicitDefinition(CopyConstructor);
8310 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008311}
8312
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008313Sema::ImplicitExceptionSpecification
8314Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8315 // C++ [except.spec]p14:
8316 // An implicitly declared special member function (Clause 12) shall have an
8317 // exception-specification. [...]
8318 ImplicitExceptionSpecification ExceptSpec(Context);
8319 if (ClassDecl->isInvalidDecl())
8320 return ExceptSpec;
8321
8322 // Direct base-class constructors.
8323 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8324 BEnd = ClassDecl->bases_end();
8325 B != BEnd; ++B) {
8326 if (B->isVirtual()) // Handled below.
8327 continue;
8328
8329 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8330 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8331 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8332 // If this is a deleted function, add it anyway. This might be conformant
8333 // with the standard. This might not. I'm not sure. It might not matter.
8334 if (Constructor)
8335 ExceptSpec.CalledDecl(Constructor);
8336 }
8337 }
8338
8339 // Virtual base-class constructors.
8340 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8341 BEnd = ClassDecl->vbases_end();
8342 B != BEnd; ++B) {
8343 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8344 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8345 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8346 // If this is a deleted function, add it anyway. This might be conformant
8347 // with the standard. This might not. I'm not sure. It might not matter.
8348 if (Constructor)
8349 ExceptSpec.CalledDecl(Constructor);
8350 }
8351 }
8352
8353 // Field constructors.
8354 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8355 FEnd = ClassDecl->field_end();
8356 F != FEnd; ++F) {
8357 if (F->hasInClassInitializer()) {
8358 if (Expr *E = F->getInClassInitializer())
8359 ExceptSpec.CalledExpr(E);
8360 else if (!F->isInvalidDecl())
8361 ExceptSpec.SetDelayed();
8362 } else if (const RecordType *RecordTy
8363 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8364 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8365 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8366 // If this is a deleted function, add it anyway. This might be conformant
8367 // with the standard. This might not. I'm not sure. It might not matter.
8368 // In particular, the problem is that this function never gets called. It
8369 // might just be ill-formed because this function attempts to refer to
8370 // a deleted function here.
8371 if (Constructor)
8372 ExceptSpec.CalledDecl(Constructor);
8373 }
8374 }
8375
8376 return ExceptSpec;
8377}
8378
8379CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8380 CXXRecordDecl *ClassDecl) {
8381 ImplicitExceptionSpecification Spec(
8382 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8383
8384 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8385 QualType ArgType = Context.getRValueReferenceType(ClassType);
8386
8387 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8388
8389 DeclarationName Name
8390 = Context.DeclarationNames.getCXXConstructorName(
8391 Context.getCanonicalType(ClassType));
8392 SourceLocation ClassLoc = ClassDecl->getLocation();
8393 DeclarationNameInfo NameInfo(Name, ClassLoc);
8394
8395 // C++0x [class.copy]p11:
8396 // An implicitly-declared copy/move constructor is an inline public
8397 // member of its class.
8398 CXXConstructorDecl *MoveConstructor
8399 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8400 Context.getFunctionType(Context.VoidTy,
8401 &ArgType, 1, EPI),
8402 /*TInfo=*/0,
8403 /*isExplicit=*/false,
8404 /*isInline=*/true,
8405 /*isImplicitlyDeclared=*/true,
8406 // FIXME: apply the rules for definitions here
8407 /*isConstexpr=*/false);
8408 MoveConstructor->setAccess(AS_public);
8409 MoveConstructor->setDefaulted();
8410 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8411
8412 // Add the parameter to the constructor.
8413 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8414 ClassLoc, ClassLoc,
8415 /*IdentifierInfo=*/0,
8416 ArgType, /*TInfo=*/0,
8417 SC_None,
8418 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008419 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008420
8421 // C++0x [class.copy]p9:
8422 // If the definition of a class X does not explicitly declare a move
8423 // constructor, one will be implicitly declared as defaulted if and only if:
8424 // [...]
8425 // - the move constructor would not be implicitly defined as deleted.
8426 if (ShouldDeleteMoveConstructor(MoveConstructor)) {
8427 // Cache this result so that we don't try to generate this over and over
8428 // on every lookup, leaking memory and wasting time.
8429 ClassDecl->setFailedImplicitMoveConstructor();
8430 return 0;
8431 }
8432
8433 // Note that we have declared this constructor.
8434 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8435
8436 if (Scope *S = getScopeForContext(ClassDecl))
8437 PushOnScopeChains(MoveConstructor, S, false);
8438 ClassDecl->addDecl(MoveConstructor);
8439
8440 return MoveConstructor;
8441}
8442
8443void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8444 CXXConstructorDecl *MoveConstructor) {
8445 assert((MoveConstructor->isDefaulted() &&
8446 MoveConstructor->isMoveConstructor() &&
8447 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8448 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8449
8450 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8451 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8452
8453 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8454 DiagnosticErrorTrap Trap(Diags);
8455
8456 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8457 Trap.hasErrorOccurred()) {
8458 Diag(CurrentLocation, diag::note_member_synthesized_at)
8459 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8460 MoveConstructor->setInvalidDecl();
8461 } else {
8462 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8463 MoveConstructor->getLocation(),
8464 MultiStmtArg(*this, 0, 0),
8465 /*isStmtExpr=*/false)
8466 .takeAs<Stmt>());
8467 }
8468
8469 MoveConstructor->setUsed();
8470
8471 if (ASTMutationListener *L = getASTMutationListener()) {
8472 L->CompletedImplicitDefinition(MoveConstructor);
8473 }
8474}
8475
John McCall60d7b3a2010-08-24 06:29:42 +00008476ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008477Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008478 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008479 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008480 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008481 unsigned ConstructKind,
8482 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008483 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008484
Douglas Gregor2f599792010-04-02 18:24:57 +00008485 // C++0x [class.copy]p34:
8486 // When certain criteria are met, an implementation is allowed to
8487 // omit the copy/move construction of a class object, even if the
8488 // copy/move constructor and/or destructor for the object have
8489 // side effects. [...]
8490 // - when a temporary class object that has not been bound to a
8491 // reference (12.2) would be copied/moved to a class object
8492 // with the same cv-unqualified type, the copy/move operation
8493 // can be omitted by constructing the temporary object
8494 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008495 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00008496 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008497 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008498 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008499 }
Mike Stump1eb44332009-09-09 15:08:12 +00008500
8501 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008502 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008503 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008504}
8505
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008506/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8507/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00008508ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008509Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8510 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00008511 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008512 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008513 unsigned ConstructKind,
8514 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00008515 unsigned NumExprs = ExprArgs.size();
8516 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00008517
Nick Lewycky909a70d2011-03-25 01:44:32 +00008518 for (specific_attr_iterator<NonNullAttr>
8519 i = Constructor->specific_attr_begin<NonNullAttr>(),
8520 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8521 const NonNullAttr *NonNull = *i;
8522 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8523 }
8524
Douglas Gregor7edfb692009-11-23 12:27:39 +00008525 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00008526 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00008527 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00008528 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008529 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8530 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008531}
8532
Mike Stump1eb44332009-09-09 15:08:12 +00008533bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008534 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00008535 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00008536 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00008537 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00008538 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008539 move(Exprs), false, CXXConstructExpr::CK_Complete,
8540 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00008541 if (TempResult.isInvalid())
8542 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008543
Anders Carlssonda3f4e22009-08-25 05:12:04 +00008544 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00008545 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00008546 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00008547 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00008548 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00008549
Anders Carlssonfe2de492009-08-25 05:18:00 +00008550 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00008551}
8552
John McCall68c6c9a2010-02-02 09:10:11 +00008553void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008554 if (VD->isInvalidDecl()) return;
8555
John McCall68c6c9a2010-02-02 09:10:11 +00008556 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008557 if (ClassDecl->isInvalidDecl()) return;
8558 if (ClassDecl->hasTrivialDestructor()) return;
8559 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00008560
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008561 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8562 MarkDeclarationReferenced(VD->getLocation(), Destructor);
8563 CheckDestructorAccess(VD->getLocation(), Destructor,
8564 PDiag(diag::err_access_dtor_var)
8565 << VD->getDeclName()
8566 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00008567
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008568 if (!VD->hasGlobalStorage()) return;
8569
8570 // Emit warning for non-trivial dtor in global scope (a real global,
8571 // class-static, function-static).
8572 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8573
8574 // TODO: this should be re-enabled for static locals by !CXAAtExit
8575 if (!VD->isStaticLocal())
8576 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008577}
8578
Mike Stump1eb44332009-09-09 15:08:12 +00008579/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008580/// ActOnDeclarator, when a C++ direct initializer is present.
8581/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00008582void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00008583 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008584 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00008585 SourceLocation RParenLoc,
8586 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00008587 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008588
8589 // If there is no declaration, there was an error parsing it. Just ignore
8590 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00008591 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008592 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008593
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008594 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8595 if (!VDecl) {
8596 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8597 RealDecl->setInvalidDecl();
8598 return;
8599 }
8600
Richard Smith34b41d92011-02-20 03:19:35 +00008601 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8602 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008603 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
8604 if (Exprs.size() > 1) {
8605 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
8606 diag::err_auto_var_init_multiple_expressions)
8607 << VDecl->getDeclName() << VDecl->getType()
8608 << VDecl->getSourceRange();
8609 RealDecl->setInvalidDecl();
8610 return;
8611 }
8612
8613 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00008614 TypeSourceInfo *DeducedType = 0;
8615 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00008616 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
8617 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
8618 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00008619 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00008620 RealDecl->setInvalidDecl();
8621 return;
8622 }
Richard Smitha085da82011-03-17 16:11:59 +00008623 VDecl->setTypeSourceInfo(DeducedType);
8624 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00008625
John McCallf85e1932011-06-15 23:02:42 +00008626 // In ARC, infer lifetime.
8627 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8628 VDecl->setInvalidDecl();
8629
Richard Smith34b41d92011-02-20 03:19:35 +00008630 // If this is a redeclaration, check that the type we just deduced matches
8631 // the previously declared type.
8632 if (VarDecl *Old = VDecl->getPreviousDeclaration())
8633 MergeVarDeclTypes(VDecl, Old);
8634 }
8635
Douglas Gregor83ddad32009-08-26 21:14:46 +00008636 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00008637 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008638 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8639 //
8640 // Clients that want to distinguish between the two forms, can check for
8641 // direct initializer using VarDecl::hasCXXDirectInitializer().
8642 // A major benefit is that clients that don't particularly care about which
8643 // exactly form was it (like the CodeGen) can handle both cases without
8644 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008645
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008646 // C++ 8.5p11:
8647 // The form of initialization (using parentheses or '=') is generally
8648 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008649 // class type.
8650
Douglas Gregor4dffad62010-02-11 22:55:30 +00008651 if (!VDecl->getType()->isDependentType() &&
8652 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00008653 diag::err_typecheck_decl_incomplete_type)) {
8654 VDecl->setInvalidDecl();
8655 return;
8656 }
8657
Douglas Gregor90f93822009-12-22 22:17:25 +00008658 // The variable can not have an abstract class type.
8659 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8660 diag::err_abstract_type_in_decl,
8661 AbstractVariableType))
8662 VDecl->setInvalidDecl();
8663
Sebastian Redl31310a22010-02-01 20:16:42 +00008664 const VarDecl *Def;
8665 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00008666 Diag(VDecl->getLocation(), diag::err_redefinition)
8667 << VDecl->getDeclName();
8668 Diag(Def->getLocation(), diag::note_previous_definition);
8669 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008670 return;
8671 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00008672
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008673 // C++ [class.static.data]p4
8674 // If a static data member is of const integral or const
8675 // enumeration type, its declaration in the class definition can
8676 // specify a constant-initializer which shall be an integral
8677 // constant expression (5.19). In that case, the member can appear
8678 // in integral constant expressions. The member shall still be
8679 // defined in a namespace scope if it is used in the program and the
8680 // namespace scope definition shall not contain an initializer.
8681 //
8682 // We already performed a redefinition check above, but for static
8683 // data members we also need to check whether there was an in-class
8684 // declaration with an initializer.
8685 const VarDecl* PrevInit = 0;
8686 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8687 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
8688 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8689 return;
8690 }
8691
Douglas Gregora31040f2010-12-16 01:31:22 +00008692 bool IsDependent = false;
8693 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
8694 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
8695 VDecl->setInvalidDecl();
8696 return;
8697 }
8698
8699 if (Exprs.get()[I]->isTypeDependent())
8700 IsDependent = true;
8701 }
8702
Douglas Gregor4dffad62010-02-11 22:55:30 +00008703 // If either the declaration has a dependent type or if any of the
8704 // expressions is type-dependent, we represent the initialization
8705 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00008706 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00008707 // Let clients know that initialization was done with a direct initializer.
8708 VDecl->setCXXDirectInitializer(true);
8709
8710 // Store the initialization expressions as a ParenListExpr.
8711 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00008712 VDecl->setInit(new (Context) ParenListExpr(
8713 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
8714 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00008715 return;
8716 }
Douglas Gregor90f93822009-12-22 22:17:25 +00008717
8718 // Capture the variable that is being initialized and the style of
8719 // initialization.
8720 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8721
8722 // FIXME: Poor source location information.
8723 InitializationKind Kind
8724 = InitializationKind::CreateDirect(VDecl->getLocation(),
8725 LParenLoc, RParenLoc);
8726
8727 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00008728 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00008729 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00008730 if (Result.isInvalid()) {
8731 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008732 return;
8733 }
John McCallb4eb64d2010-10-08 02:01:28 +00008734
8735 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00008736
Douglas Gregor53c374f2010-12-07 00:41:46 +00008737 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00008738 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008739 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00008740
John McCall2998d6b2011-01-19 11:48:09 +00008741 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008742}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008743
Douglas Gregor39da0b82009-09-09 23:08:42 +00008744/// \brief Given a constructor and the set of arguments provided for the
8745/// constructor, convert the arguments and add any required default arguments
8746/// to form a proper call to this constructor.
8747///
8748/// \returns true if an error occurred, false otherwise.
8749bool
8750Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8751 MultiExprArg ArgsPtr,
8752 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00008753 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00008754 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8755 unsigned NumArgs = ArgsPtr.size();
8756 Expr **Args = (Expr **)ArgsPtr.get();
8757
8758 const FunctionProtoType *Proto
8759 = Constructor->getType()->getAs<FunctionProtoType>();
8760 assert(Proto && "Constructor without a prototype?");
8761 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00008762
8763 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008764 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00008765 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008766 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00008767 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008768
8769 VariadicCallType CallType =
8770 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008771 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008772 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
8773 Proto, 0, Args, NumArgs, AllArgs,
8774 CallType);
8775 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
8776 ConvertedArgs.push_back(AllArgs[i]);
8777 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008778}
8779
Anders Carlsson20d45d22009-12-12 00:32:00 +00008780static inline bool
8781CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
8782 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00008783 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00008784 if (isa<NamespaceDecl>(DC)) {
8785 return SemaRef.Diag(FnDecl->getLocation(),
8786 diag::err_operator_new_delete_declared_in_namespace)
8787 << FnDecl->getDeclName();
8788 }
8789
8790 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00008791 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00008792 return SemaRef.Diag(FnDecl->getLocation(),
8793 diag::err_operator_new_delete_declared_static)
8794 << FnDecl->getDeclName();
8795 }
8796
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00008797 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00008798}
8799
Anders Carlsson156c78e2009-12-13 17:53:43 +00008800static inline bool
8801CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
8802 CanQualType ExpectedResultType,
8803 CanQualType ExpectedFirstParamType,
8804 unsigned DependentParamTypeDiag,
8805 unsigned InvalidParamTypeDiag) {
8806 QualType ResultType =
8807 FnDecl->getType()->getAs<FunctionType>()->getResultType();
8808
8809 // Check that the result type is not dependent.
8810 if (ResultType->isDependentType())
8811 return SemaRef.Diag(FnDecl->getLocation(),
8812 diag::err_operator_new_delete_dependent_result_type)
8813 << FnDecl->getDeclName() << ExpectedResultType;
8814
8815 // Check that the result type is what we expect.
8816 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
8817 return SemaRef.Diag(FnDecl->getLocation(),
8818 diag::err_operator_new_delete_invalid_result_type)
8819 << FnDecl->getDeclName() << ExpectedResultType;
8820
8821 // A function template must have at least 2 parameters.
8822 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
8823 return SemaRef.Diag(FnDecl->getLocation(),
8824 diag::err_operator_new_delete_template_too_few_parameters)
8825 << FnDecl->getDeclName();
8826
8827 // The function decl must have at least 1 parameter.
8828 if (FnDecl->getNumParams() == 0)
8829 return SemaRef.Diag(FnDecl->getLocation(),
8830 diag::err_operator_new_delete_too_few_parameters)
8831 << FnDecl->getDeclName();
8832
8833 // Check the the first parameter type is not dependent.
8834 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
8835 if (FirstParamType->isDependentType())
8836 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
8837 << FnDecl->getDeclName() << ExpectedFirstParamType;
8838
8839 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00008840 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00008841 ExpectedFirstParamType)
8842 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
8843 << FnDecl->getDeclName() << ExpectedFirstParamType;
8844
8845 return false;
8846}
8847
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008848static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00008849CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00008850 // C++ [basic.stc.dynamic.allocation]p1:
8851 // A program is ill-formed if an allocation function is declared in a
8852 // namespace scope other than global scope or declared static in global
8853 // scope.
8854 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8855 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00008856
8857 CanQualType SizeTy =
8858 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
8859
8860 // C++ [basic.stc.dynamic.allocation]p1:
8861 // The return type shall be void*. The first parameter shall have type
8862 // std::size_t.
8863 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
8864 SizeTy,
8865 diag::err_operator_new_dependent_param_type,
8866 diag::err_operator_new_param_type))
8867 return true;
8868
8869 // C++ [basic.stc.dynamic.allocation]p1:
8870 // The first parameter shall not have an associated default argument.
8871 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00008872 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00008873 diag::err_operator_new_default_arg)
8874 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
8875
8876 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00008877}
8878
8879static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008880CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
8881 // C++ [basic.stc.dynamic.deallocation]p1:
8882 // A program is ill-formed if deallocation functions are declared in a
8883 // namespace scope other than global scope or declared static in global
8884 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00008885 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8886 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008887
8888 // C++ [basic.stc.dynamic.deallocation]p2:
8889 // Each deallocation function shall return void and its first parameter
8890 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00008891 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
8892 SemaRef.Context.VoidPtrTy,
8893 diag::err_operator_delete_dependent_param_type,
8894 diag::err_operator_delete_param_type))
8895 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008896
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008897 return false;
8898}
8899
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008900/// CheckOverloadedOperatorDeclaration - Check whether the declaration
8901/// of this overloaded operator is well-formed. If so, returns false;
8902/// otherwise, emits appropriate diagnostics and returns true.
8903bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008904 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008905 "Expected an overloaded operator declaration");
8906
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008907 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
8908
Mike Stump1eb44332009-09-09 15:08:12 +00008909 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008910 // The allocation and deallocation functions, operator new,
8911 // operator new[], operator delete and operator delete[], are
8912 // described completely in 3.7.3. The attributes and restrictions
8913 // found in the rest of this subclause do not apply to them unless
8914 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00008915 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008916 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00008917
Anders Carlssona3ccda52009-12-12 00:26:23 +00008918 if (Op == OO_New || Op == OO_Array_New)
8919 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008920
8921 // C++ [over.oper]p6:
8922 // An operator function shall either be a non-static member
8923 // function or be a non-member function and have at least one
8924 // parameter whose type is a class, a reference to a class, an
8925 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008926 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
8927 if (MethodDecl->isStatic())
8928 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008929 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008930 } else {
8931 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008932 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
8933 ParamEnd = FnDecl->param_end();
8934 Param != ParamEnd; ++Param) {
8935 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00008936 if (ParamType->isDependentType() || ParamType->isRecordType() ||
8937 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008938 ClassOrEnumParam = true;
8939 break;
8940 }
8941 }
8942
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008943 if (!ClassOrEnumParam)
8944 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00008945 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008946 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008947 }
8948
8949 // C++ [over.oper]p8:
8950 // An operator function cannot have default arguments (8.3.6),
8951 // except where explicitly stated below.
8952 //
Mike Stump1eb44332009-09-09 15:08:12 +00008953 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008954 // (C++ [over.call]p1).
8955 if (Op != OO_Call) {
8956 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
8957 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00008958 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00008959 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00008960 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00008961 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008962 }
8963 }
8964
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008965 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
8966 { false, false, false }
8967#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
8968 , { Unary, Binary, MemberOnly }
8969#include "clang/Basic/OperatorKinds.def"
8970 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008971
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008972 bool CanBeUnaryOperator = OperatorUses[Op][0];
8973 bool CanBeBinaryOperator = OperatorUses[Op][1];
8974 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008975
8976 // C++ [over.oper]p8:
8977 // [...] Operator functions cannot have more or fewer parameters
8978 // than the number required for the corresponding operator, as
8979 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00008980 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008981 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008982 if (Op != OO_Call &&
8983 ((NumParams == 1 && !CanBeUnaryOperator) ||
8984 (NumParams == 2 && !CanBeBinaryOperator) ||
8985 (NumParams < 1) || (NumParams > 2))) {
8986 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00008987 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008988 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00008989 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008990 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00008991 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008992 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00008993 assert(CanBeBinaryOperator &&
8994 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00008995 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008996 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008997
Chris Lattner416e46f2008-11-21 07:57:12 +00008998 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008999 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009000 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009001
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009002 // Overloaded operators other than operator() cannot be variadic.
9003 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009004 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009005 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009006 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009007 }
9008
9009 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009010 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9011 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009012 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009013 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009014 }
9015
9016 // C++ [over.inc]p1:
9017 // The user-defined function called operator++ implements the
9018 // prefix and postfix ++ operator. If this function is a member
9019 // function with no parameters, or a non-member function with one
9020 // parameter of class or enumeration type, it defines the prefix
9021 // increment operator ++ for objects of that type. If the function
9022 // is a member function with one parameter (which shall be of type
9023 // int) or a non-member function with two parameters (the second
9024 // of which shall be of type int), it defines the postfix
9025 // increment operator ++ for objects of that type.
9026 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9027 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9028 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009029 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009030 ParamIsInt = BT->getKind() == BuiltinType::Int;
9031
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009032 if (!ParamIsInt)
9033 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009034 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009035 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009036 }
9037
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009038 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009039}
Chris Lattner5a003a42008-12-17 07:09:26 +00009040
Sean Hunta6c058d2010-01-13 09:01:02 +00009041/// CheckLiteralOperatorDeclaration - Check whether the declaration
9042/// of this literal operator function is well-formed. If so, returns
9043/// false; otherwise, emits appropriate diagnostics and returns true.
9044bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9045 DeclContext *DC = FnDecl->getDeclContext();
9046 Decl::Kind Kind = DC->getDeclKind();
9047 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9048 Kind != Decl::LinkageSpec) {
9049 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9050 << FnDecl->getDeclName();
9051 return true;
9052 }
9053
9054 bool Valid = false;
9055
Sean Hunt216c2782010-04-07 23:11:06 +00009056 // template <char...> type operator "" name() is the only valid template
9057 // signature, and the only valid signature with no parameters.
9058 if (FnDecl->param_size() == 0) {
9059 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9060 // Must have only one template parameter
9061 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9062 if (Params->size() == 1) {
9063 NonTypeTemplateParmDecl *PmDecl =
9064 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009065
Sean Hunt216c2782010-04-07 23:11:06 +00009066 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009067 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9068 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9069 Valid = true;
9070 }
9071 }
9072 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009073 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009074 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9075
Sean Hunta6c058d2010-01-13 09:01:02 +00009076 QualType T = (*Param)->getType();
9077
Sean Hunt30019c02010-04-07 22:57:35 +00009078 // unsigned long long int, long double, and any character type are allowed
9079 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009080 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9081 Context.hasSameType(T, Context.LongDoubleTy) ||
9082 Context.hasSameType(T, Context.CharTy) ||
9083 Context.hasSameType(T, Context.WCharTy) ||
9084 Context.hasSameType(T, Context.Char16Ty) ||
9085 Context.hasSameType(T, Context.Char32Ty)) {
9086 if (++Param == FnDecl->param_end())
9087 Valid = true;
9088 goto FinishedParams;
9089 }
9090
Sean Hunt30019c02010-04-07 22:57:35 +00009091 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009092 const PointerType *PT = T->getAs<PointerType>();
9093 if (!PT)
9094 goto FinishedParams;
9095 T = PT->getPointeeType();
9096 if (!T.isConstQualified())
9097 goto FinishedParams;
9098 T = T.getUnqualifiedType();
9099
9100 // Move on to the second parameter;
9101 ++Param;
9102
9103 // If there is no second parameter, the first must be a const char *
9104 if (Param == FnDecl->param_end()) {
9105 if (Context.hasSameType(T, Context.CharTy))
9106 Valid = true;
9107 goto FinishedParams;
9108 }
9109
9110 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9111 // are allowed as the first parameter to a two-parameter function
9112 if (!(Context.hasSameType(T, Context.CharTy) ||
9113 Context.hasSameType(T, Context.WCharTy) ||
9114 Context.hasSameType(T, Context.Char16Ty) ||
9115 Context.hasSameType(T, Context.Char32Ty)))
9116 goto FinishedParams;
9117
9118 // The second and final parameter must be an std::size_t
9119 T = (*Param)->getType().getUnqualifiedType();
9120 if (Context.hasSameType(T, Context.getSizeType()) &&
9121 ++Param == FnDecl->param_end())
9122 Valid = true;
9123 }
9124
9125 // FIXME: This diagnostic is absolutely terrible.
9126FinishedParams:
9127 if (!Valid) {
9128 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9129 << FnDecl->getDeclName();
9130 return true;
9131 }
9132
Douglas Gregor1155c422011-08-30 22:40:35 +00009133 StringRef LiteralName
9134 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9135 if (LiteralName[0] != '_') {
9136 // C++0x [usrlit.suffix]p1:
9137 // Literal suffix identifiers that do not start with an underscore are
9138 // reserved for future standardization.
9139 bool IsHexFloat = true;
9140 if (LiteralName.size() > 1 &&
9141 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9142 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9143 if (!isdigit(LiteralName[I])) {
9144 IsHexFloat = false;
9145 break;
9146 }
9147 }
9148 }
9149
9150 if (IsHexFloat)
9151 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9152 << LiteralName;
9153 else
9154 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9155 }
9156
Sean Hunta6c058d2010-01-13 09:01:02 +00009157 return false;
9158}
9159
Douglas Gregor074149e2009-01-05 19:45:36 +00009160/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9161/// linkage specification, including the language and (if present)
9162/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9163/// the location of the language string literal, which is provided
9164/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9165/// the '{' brace. Otherwise, this linkage specification does not
9166/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009167Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9168 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009169 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009170 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009171 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009172 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009173 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009174 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009175 Language = LinkageSpecDecl::lang_cxx;
9176 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009177 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009178 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009179 }
Mike Stump1eb44332009-09-09 15:08:12 +00009180
Chris Lattnercc98eac2008-12-17 07:13:27 +00009181 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009182
Douglas Gregor074149e2009-01-05 19:45:36 +00009183 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009184 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009185 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009186 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009187 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009188}
9189
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009190/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009191/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9192/// valid, it's the position of the closing '}' brace in a linkage
9193/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009194Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009195 Decl *LinkageSpec,
9196 SourceLocation RBraceLoc) {
9197 if (LinkageSpec) {
9198 if (RBraceLoc.isValid()) {
9199 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9200 LSDecl->setRBraceLoc(RBraceLoc);
9201 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009202 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009203 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009204 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009205}
9206
Douglas Gregord308e622009-05-18 20:51:54 +00009207/// \brief Perform semantic analysis for the variable declaration that
9208/// occurs within a C++ catch clause, returning the newly-created
9209/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009210VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009211 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009212 SourceLocation StartLoc,
9213 SourceLocation Loc,
9214 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009215 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009216 QualType ExDeclType = TInfo->getType();
9217
Sebastian Redl4b07b292008-12-22 19:15:10 +00009218 // Arrays and functions decay.
9219 if (ExDeclType->isArrayType())
9220 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9221 else if (ExDeclType->isFunctionType())
9222 ExDeclType = Context.getPointerType(ExDeclType);
9223
9224 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9225 // The exception-declaration shall not denote a pointer or reference to an
9226 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009227 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009228 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009229 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009230 Invalid = true;
9231 }
Douglas Gregord308e622009-05-18 20:51:54 +00009232
Douglas Gregora2762912010-03-08 01:47:36 +00009233 // GCC allows catching pointers and references to incomplete types
9234 // as an extension; so do we, but we warn by default.
9235
Sebastian Redl4b07b292008-12-22 19:15:10 +00009236 QualType BaseType = ExDeclType;
9237 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009238 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00009239 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00009240 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009241 BaseType = Ptr->getPointeeType();
9242 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00009243 DK = diag::ext_catch_incomplete_ptr;
9244 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009245 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009246 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009247 BaseType = Ref->getPointeeType();
9248 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00009249 DK = diag::ext_catch_incomplete_ref;
9250 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009251 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009252 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00009253 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9254 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00009255 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009256
Mike Stump1eb44332009-09-09 15:08:12 +00009257 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009258 RequireNonAbstractType(Loc, ExDeclType,
9259 diag::err_abstract_type_in_decl,
9260 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009261 Invalid = true;
9262
John McCall5a180392010-07-24 00:37:23 +00009263 // Only the non-fragile NeXT runtime currently supports C++ catches
9264 // of ObjC types, and no runtime supports catching ObjC types by value.
9265 if (!Invalid && getLangOptions().ObjC1) {
9266 QualType T = ExDeclType;
9267 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9268 T = RT->getPointeeType();
9269
9270 if (T->isObjCObjectType()) {
9271 Diag(Loc, diag::err_objc_object_catch);
9272 Invalid = true;
9273 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009274 if (!getLangOptions().ObjCNonFragileABI)
9275 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009276 }
9277 }
9278
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009279 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9280 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009281 ExDecl->setExceptionVariable(true);
9282
Douglas Gregorc41b8782011-07-06 18:14:43 +00009283 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009284 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009285 // C++ [except.handle]p16:
9286 // The object declared in an exception-declaration or, if the
9287 // exception-declaration does not specify a name, a temporary (12.2) is
9288 // copy-initialized (8.5) from the exception object. [...]
9289 // The object is destroyed when the handler exits, after the destruction
9290 // of any automatic objects initialized within the handler.
9291 //
9292 // We just pretend to initialize the object with itself, then make sure
9293 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009294 QualType initType = ExDeclType;
9295
9296 InitializedEntity entity =
9297 InitializedEntity::InitializeVariable(ExDecl);
9298 InitializationKind initKind =
9299 InitializationKind::CreateCopy(Loc, SourceLocation());
9300
9301 Expr *opaqueValue =
9302 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9303 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9304 ExprResult result = sequence.Perform(*this, entity, initKind,
9305 MultiExprArg(&opaqueValue, 1));
9306 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009307 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009308 else {
9309 // If the constructor used was non-trivial, set this as the
9310 // "initializer".
9311 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9312 if (!construct->getConstructor()->isTrivial()) {
9313 Expr *init = MaybeCreateExprWithCleanups(construct);
9314 ExDecl->setInit(init);
9315 }
9316
9317 // And make sure it's destructable.
9318 FinalizeVarWithDestructor(ExDecl, recordType);
9319 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009320 }
9321 }
9322
Douglas Gregord308e622009-05-18 20:51:54 +00009323 if (Invalid)
9324 ExDecl->setInvalidDecl();
9325
9326 return ExDecl;
9327}
9328
9329/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9330/// handler.
John McCalld226f652010-08-21 09:40:31 +00009331Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009332 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009333 bool Invalid = D.isInvalidType();
9334
9335 // Check for unexpanded parameter packs.
9336 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9337 UPPC_ExceptionType)) {
9338 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9339 D.getIdentifierLoc());
9340 Invalid = true;
9341 }
9342
Sebastian Redl4b07b292008-12-22 19:15:10 +00009343 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009344 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009345 LookupOrdinaryName,
9346 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009347 // The scope should be freshly made just for us. There is just no way
9348 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009349 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009350 if (PrevDecl->isTemplateParameter()) {
9351 // Maybe we will complain about the shadowed template parameter.
9352 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009353 }
9354 }
9355
Chris Lattnereaaebc72009-04-25 08:06:05 +00009356 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009357 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9358 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009359 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009360 }
9361
Douglas Gregor83cb9422010-09-09 17:09:21 +00009362 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009363 D.getSourceRange().getBegin(),
9364 D.getIdentifierLoc(),
9365 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009366 if (Invalid)
9367 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009368
Sebastian Redl4b07b292008-12-22 19:15:10 +00009369 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009370 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009371 PushOnScopeChains(ExDecl, S);
9372 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009373 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009374
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009375 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009376 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009377}
Anders Carlssonfb311762009-03-14 00:25:26 +00009378
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009379Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009380 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009381 Expr *AssertMessageExpr_,
9382 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009383 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009384
Anders Carlssonc3082412009-03-14 00:33:21 +00009385 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9386 llvm::APSInt Value(32);
9387 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009388 Diag(StaticAssertLoc,
9389 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00009390 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009391 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00009392 }
Anders Carlssonfb311762009-03-14 00:25:26 +00009393
Anders Carlssonc3082412009-03-14 00:33:21 +00009394 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009395 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009396 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009397 }
9398 }
Mike Stump1eb44332009-09-09 15:08:12 +00009399
Douglas Gregor399ad972010-12-15 23:55:21 +00009400 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9401 return 0;
9402
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009403 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9404 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009405
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009406 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009407 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009408}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009409
Douglas Gregor1d869352010-04-07 16:53:43 +00009410/// \brief Perform semantic analysis of the given friend type declaration.
9411///
9412/// \returns A friend declaration that.
9413FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9414 TypeSourceInfo *TSInfo) {
9415 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9416
9417 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009418 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009419
Douglas Gregor06245bf2010-04-07 17:57:12 +00009420 if (!getLangOptions().CPlusPlus0x) {
9421 // C++03 [class.friend]p2:
9422 // An elaborated-type-specifier shall be used in a friend declaration
9423 // for a class.*
9424 //
9425 // * The class-key of the elaborated-type-specifier is required.
9426 if (!ActiveTemplateInstantiations.empty()) {
9427 // Do not complain about the form of friend template types during
9428 // template instantiation; we will already have complained when the
9429 // template was declared.
9430 } else if (!T->isElaboratedTypeSpecifier()) {
9431 // If we evaluated the type to a record type, suggest putting
9432 // a tag in front.
9433 if (const RecordType *RT = T->getAs<RecordType>()) {
9434 RecordDecl *RD = RT->getDecl();
9435
9436 std::string InsertionText = std::string(" ") + RD->getKindName();
9437
9438 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9439 << (unsigned) RD->getTagKind()
9440 << T
9441 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9442 InsertionText);
9443 } else {
9444 Diag(FriendLoc, diag::ext_nonclass_type_friend)
9445 << T
9446 << SourceRange(FriendLoc, TypeRange.getEnd());
9447 }
9448 } else if (T->getAs<EnumType>()) {
9449 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009450 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009451 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009452 }
9453 }
9454
Douglas Gregor06245bf2010-04-07 17:57:12 +00009455 // C++0x [class.friend]p3:
9456 // If the type specifier in a friend declaration designates a (possibly
9457 // cv-qualified) class type, that class is declared as a friend; otherwise,
9458 // the friend declaration is ignored.
9459
9460 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9461 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009462
9463 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9464}
9465
John McCall9a34edb2010-10-19 01:40:49 +00009466/// Handle a friend tag declaration where the scope specifier was
9467/// templated.
9468Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9469 unsigned TagSpec, SourceLocation TagLoc,
9470 CXXScopeSpec &SS,
9471 IdentifierInfo *Name, SourceLocation NameLoc,
9472 AttributeList *Attr,
9473 MultiTemplateParamsArg TempParamLists) {
9474 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9475
9476 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009477 bool Invalid = false;
9478
9479 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009480 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009481 TempParamLists.get(),
9482 TempParamLists.size(),
9483 /*friend*/ true,
9484 isExplicitSpecialization,
9485 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009486 if (TemplateParams->size() > 0) {
9487 // This is a declaration of a class template.
9488 if (Invalid)
9489 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009490
Eric Christopher4110e132011-07-21 05:34:24 +00009491 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9492 SS, Name, NameLoc, Attr,
9493 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009494 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009495 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009496 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009497 } else {
9498 // The "template<>" header is extraneous.
9499 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9500 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9501 isExplicitSpecialization = true;
9502 }
9503 }
9504
9505 if (Invalid) return 0;
9506
9507 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9508
9509 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009510 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009511 if (TempParamLists.get()[I]->size()) {
9512 isAllExplicitSpecializations = false;
9513 break;
9514 }
9515 }
9516
9517 // FIXME: don't ignore attributes.
9518
9519 // If it's explicit specializations all the way down, just forget
9520 // about the template header and build an appropriate non-templated
9521 // friend. TODO: for source fidelity, remember the headers.
9522 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00009523 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009524 ElaboratedTypeKeyword Keyword
9525 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009526 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009527 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009528 if (T.isNull())
9529 return 0;
9530
9531 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9532 if (isa<DependentNameType>(T)) {
9533 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9534 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009535 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009536 TL.setNameLoc(NameLoc);
9537 } else {
9538 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9539 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009540 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009541 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9542 }
9543
9544 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9545 TSI, FriendLoc);
9546 Friend->setAccess(AS_public);
9547 CurContext->addDecl(Friend);
9548 return Friend;
9549 }
9550
9551 // Handle the case of a templated-scope friend class. e.g.
9552 // template <class T> class A<T>::B;
9553 // FIXME: we don't support these right now.
9554 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9555 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9556 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9557 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9558 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009559 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009560 TL.setNameLoc(NameLoc);
9561
9562 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9563 TSI, FriendLoc);
9564 Friend->setAccess(AS_public);
9565 Friend->setUnsupportedFriend(true);
9566 CurContext->addDecl(Friend);
9567 return Friend;
9568}
9569
9570
John McCalldd4a3b02009-09-16 22:47:08 +00009571/// Handle a friend type declaration. This works in tandem with
9572/// ActOnTag.
9573///
9574/// Notes on friend class templates:
9575///
9576/// We generally treat friend class declarations as if they were
9577/// declaring a class. So, for example, the elaborated type specifier
9578/// in a friend declaration is required to obey the restrictions of a
9579/// class-head (i.e. no typedefs in the scope chain), template
9580/// parameters are required to match up with simple template-ids, &c.
9581/// However, unlike when declaring a template specialization, it's
9582/// okay to refer to a template specialization without an empty
9583/// template parameter declaration, e.g.
9584/// friend class A<T>::B<unsigned>;
9585/// We permit this as a special case; if there are any template
9586/// parameters present at all, require proper matching, i.e.
9587/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00009588Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00009589 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00009590 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00009591
9592 assert(DS.isFriendSpecified());
9593 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9594
John McCalldd4a3b02009-09-16 22:47:08 +00009595 // Try to convert the decl specifier to a type. This works for
9596 // friend templates because ActOnTag never produces a ClassTemplateDecl
9597 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00009598 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00009599 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9600 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00009601 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00009602 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009603
Douglas Gregor6ccab972010-12-16 01:14:37 +00009604 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9605 return 0;
9606
John McCalldd4a3b02009-09-16 22:47:08 +00009607 // This is definitely an error in C++98. It's probably meant to
9608 // be forbidden in C++0x, too, but the specification is just
9609 // poorly written.
9610 //
9611 // The problem is with declarations like the following:
9612 // template <T> friend A<T>::foo;
9613 // where deciding whether a class C is a friend or not now hinges
9614 // on whether there exists an instantiation of A that causes
9615 // 'foo' to equal C. There are restrictions on class-heads
9616 // (which we declare (by fiat) elaborated friend declarations to
9617 // be) that makes this tractable.
9618 //
9619 // FIXME: handle "template <> friend class A<T>;", which
9620 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00009621 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00009622 Diag(Loc, diag::err_tagless_friend_type_template)
9623 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009624 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00009625 }
Douglas Gregor1d869352010-04-07 16:53:43 +00009626
John McCall02cace72009-08-28 07:59:38 +00009627 // C++98 [class.friend]p1: A friend of a class is a function
9628 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00009629 // This is fixed in DR77, which just barely didn't make the C++03
9630 // deadline. It's also a very silly restriction that seriously
9631 // affects inner classes and which nobody else seems to implement;
9632 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00009633 //
9634 // But note that we could warn about it: it's always useless to
9635 // friend one of your own members (it's not, however, worthless to
9636 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00009637
John McCalldd4a3b02009-09-16 22:47:08 +00009638 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00009639 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00009640 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009641 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00009642 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00009643 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00009644 DS.getFriendSpecLoc());
9645 else
Douglas Gregor1d869352010-04-07 16:53:43 +00009646 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
9647
9648 if (!D)
John McCalld226f652010-08-21 09:40:31 +00009649 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00009650
John McCalldd4a3b02009-09-16 22:47:08 +00009651 D->setAccess(AS_public);
9652 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00009653
John McCalld226f652010-08-21 09:40:31 +00009654 return D;
John McCall02cace72009-08-28 07:59:38 +00009655}
9656
John McCall337ec3d2010-10-12 23:13:28 +00009657Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
9658 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00009659 const DeclSpec &DS = D.getDeclSpec();
9660
9661 assert(DS.isFriendSpecified());
9662 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9663
9664 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00009665 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9666 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00009667
9668 // C++ [class.friend]p1
9669 // A friend of a class is a function or class....
9670 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00009671 // It *doesn't* see through dependent types, which is correct
9672 // according to [temp.arg.type]p3:
9673 // If a declaration acquires a function type through a
9674 // type dependent on a template-parameter and this causes
9675 // a declaration that does not use the syntactic form of a
9676 // function declarator to have a function type, the program
9677 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00009678 if (!T->isFunctionType()) {
9679 Diag(Loc, diag::err_unexpected_friend);
9680
9681 // It might be worthwhile to try to recover by creating an
9682 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00009683 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009684 }
9685
9686 // C++ [namespace.memdef]p3
9687 // - If a friend declaration in a non-local class first declares a
9688 // class or function, the friend class or function is a member
9689 // of the innermost enclosing namespace.
9690 // - The name of the friend is not found by simple name lookup
9691 // until a matching declaration is provided in that namespace
9692 // scope (either before or after the class declaration granting
9693 // friendship).
9694 // - If a friend function is called, its name may be found by the
9695 // name lookup that considers functions from namespaces and
9696 // classes associated with the types of the function arguments.
9697 // - When looking for a prior declaration of a class or a function
9698 // declared as a friend, scopes outside the innermost enclosing
9699 // namespace scope are not considered.
9700
John McCall337ec3d2010-10-12 23:13:28 +00009701 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00009702 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9703 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00009704 assert(Name);
9705
Douglas Gregor6ccab972010-12-16 01:14:37 +00009706 // Check for unexpanded parameter packs.
9707 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9708 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9709 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9710 return 0;
9711
John McCall67d1a672009-08-06 02:15:43 +00009712 // The context we found the declaration in, or in which we should
9713 // create the declaration.
9714 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00009715 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00009716 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00009717 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00009718
John McCall337ec3d2010-10-12 23:13:28 +00009719 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00009720
John McCall337ec3d2010-10-12 23:13:28 +00009721 // There are four cases here.
9722 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00009723 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00009724 // there as appropriate.
9725 // Recover from invalid scope qualifiers as if they just weren't there.
9726 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00009727 // C++0x [namespace.memdef]p3:
9728 // If the name in a friend declaration is neither qualified nor
9729 // a template-id and the declaration is a function or an
9730 // elaborated-type-specifier, the lookup to determine whether
9731 // the entity has been previously declared shall not consider
9732 // any scopes outside the innermost enclosing namespace.
9733 // C++0x [class.friend]p11:
9734 // If a friend declaration appears in a local class and the name
9735 // specified is an unqualified name, a prior declaration is
9736 // looked up without considering scopes that are outside the
9737 // innermost enclosing non-class scope. For a friend function
9738 // declaration, if there is no prior declaration, the program is
9739 // ill-formed.
9740 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00009741 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00009742
John McCall29ae6e52010-10-13 05:45:15 +00009743 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00009744 DC = CurContext;
9745 while (true) {
9746 // Skip class contexts. If someone can cite chapter and verse
9747 // for this behavior, that would be nice --- it's what GCC and
9748 // EDG do, and it seems like a reasonable intent, but the spec
9749 // really only says that checks for unqualified existing
9750 // declarations should stop at the nearest enclosing namespace,
9751 // not that they should only consider the nearest enclosing
9752 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00009753 while (DC->isRecord())
9754 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00009755
John McCall68263142009-11-18 22:49:29 +00009756 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00009757
9758 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00009759 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00009760 break;
John McCall29ae6e52010-10-13 05:45:15 +00009761
John McCall8a407372010-10-14 22:22:28 +00009762 if (isTemplateId) {
9763 if (isa<TranslationUnitDecl>(DC)) break;
9764 } else {
9765 if (DC->isFileContext()) break;
9766 }
John McCall67d1a672009-08-06 02:15:43 +00009767 DC = DC->getParent();
9768 }
9769
9770 // C++ [class.friend]p1: A friend of a class is a function or
9771 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00009772 // C++0x changes this for both friend types and functions.
9773 // Most C++ 98 compilers do seem to give an error here, so
9774 // we do, too.
John McCall68263142009-11-18 22:49:29 +00009775 if (!Previous.empty() && DC->Equals(CurContext)
9776 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00009777 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00009778
John McCall380aaa42010-10-13 06:22:15 +00009779 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00009780
John McCall337ec3d2010-10-12 23:13:28 +00009781 // - There's a non-dependent scope specifier, in which case we
9782 // compute it and do a previous lookup there for a function
9783 // or function template.
9784 } else if (!SS.getScopeRep()->isDependent()) {
9785 DC = computeDeclContext(SS);
9786 if (!DC) return 0;
9787
9788 if (RequireCompleteDeclContext(SS, DC)) return 0;
9789
9790 LookupQualifiedName(Previous, DC);
9791
9792 // Ignore things found implicitly in the wrong scope.
9793 // TODO: better diagnostics for this case. Suggesting the right
9794 // qualified scope would be nice...
9795 LookupResult::Filter F = Previous.makeFilter();
9796 while (F.hasNext()) {
9797 NamedDecl *D = F.next();
9798 if (!DC->InEnclosingNamespaceSetOf(
9799 D->getDeclContext()->getRedeclContext()))
9800 F.erase();
9801 }
9802 F.done();
9803
9804 if (Previous.empty()) {
9805 D.setInvalidType();
9806 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
9807 return 0;
9808 }
9809
9810 // C++ [class.friend]p1: A friend of a class is a function or
9811 // class that is not a member of the class . . .
9812 if (DC->Equals(CurContext))
9813 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
9814
9815 // - There's a scope specifier that does not match any template
9816 // parameter lists, in which case we use some arbitrary context,
9817 // create a method or method template, and wait for instantiation.
9818 // - There's a scope specifier that does match some template
9819 // parameter lists, which we don't handle right now.
9820 } else {
9821 DC = CurContext;
9822 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00009823 }
9824
John McCall29ae6e52010-10-13 05:45:15 +00009825 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00009826 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00009827 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
9828 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
9829 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00009830 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00009831 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
9832 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00009833 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009834 }
John McCall67d1a672009-08-06 02:15:43 +00009835 }
9836
Douglas Gregor182ddf02009-09-28 00:08:27 +00009837 bool Redeclaration = false;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00009838 bool AddToScope = true;
John McCall380aaa42010-10-13 06:22:15 +00009839 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00009840 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00009841 IsDefinition,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00009842 Redeclaration, AddToScope);
John McCalld226f652010-08-21 09:40:31 +00009843 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00009844
Douglas Gregor182ddf02009-09-28 00:08:27 +00009845 assert(ND->getDeclContext() == DC);
9846 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00009847
John McCallab88d972009-08-31 22:39:49 +00009848 // Add the function declaration to the appropriate lookup tables,
9849 // adjusting the redeclarations list as necessary. We don't
9850 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00009851 //
John McCallab88d972009-08-31 22:39:49 +00009852 // Also update the scope-based lookup if the target context's
9853 // lookup context is in lexical scope.
9854 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009855 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00009856 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00009857 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00009858 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00009859 }
John McCall02cace72009-08-28 07:59:38 +00009860
9861 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00009862 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00009863 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00009864 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00009865 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00009866
John McCall337ec3d2010-10-12 23:13:28 +00009867 if (ND->isInvalidDecl())
9868 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00009869 else {
9870 FunctionDecl *FD;
9871 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9872 FD = FTD->getTemplatedDecl();
9873 else
9874 FD = cast<FunctionDecl>(ND);
9875
9876 // Mark templated-scope function declarations as unsupported.
9877 if (FD->getNumTemplateParameterLists())
9878 FrD->setUnsupportedFriend(true);
9879 }
John McCall337ec3d2010-10-12 23:13:28 +00009880
John McCalld226f652010-08-21 09:40:31 +00009881 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00009882}
9883
John McCalld226f652010-08-21 09:40:31 +00009884void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
9885 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00009886
Sebastian Redl50de12f2009-03-24 22:27:57 +00009887 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
9888 if (!Fn) {
9889 Diag(DelLoc, diag::err_deleted_non_function);
9890 return;
9891 }
9892 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
9893 Diag(DelLoc, diag::err_deleted_decl_not_first);
9894 Diag(Prev->getLocation(), diag::note_previous_declaration);
9895 // If the declaration wasn't the first, we delete the function anyway for
9896 // recovery.
9897 }
Sean Hunt10620eb2011-05-06 20:44:56 +00009898 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +00009899}
Sebastian Redl13e88542009-04-27 21:33:24 +00009900
Sean Hunte4246a62011-05-12 06:15:49 +00009901void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
9902 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
9903
9904 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +00009905 if (MD->getParent()->isDependentType()) {
9906 MD->setDefaulted();
9907 MD->setExplicitlyDefaulted();
9908 return;
9909 }
9910
Sean Hunte4246a62011-05-12 06:15:49 +00009911 CXXSpecialMember Member = getSpecialMember(MD);
9912 if (Member == CXXInvalid) {
9913 Diag(DefaultLoc, diag::err_default_special_members);
9914 return;
9915 }
9916
9917 MD->setDefaulted();
9918 MD->setExplicitlyDefaulted();
9919
Sean Huntcd10dec2011-05-23 23:14:04 +00009920 // If this definition appears within the record, do the checking when
9921 // the record is complete.
9922 const FunctionDecl *Primary = MD;
9923 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
9924 // Find the uninstantiated declaration that actually had the '= default'
9925 // on it.
9926 MD->getTemplateInstantiationPattern()->isDefined(Primary);
9927
9928 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +00009929 return;
9930
9931 switch (Member) {
9932 case CXXDefaultConstructor: {
9933 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9934 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +00009935 if (!CD->isInvalidDecl())
9936 DefineImplicitDefaultConstructor(DefaultLoc, CD);
9937 break;
9938 }
9939
9940 case CXXCopyConstructor: {
9941 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9942 CheckExplicitlyDefaultedCopyConstructor(CD);
9943 if (!CD->isInvalidDecl())
9944 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +00009945 break;
9946 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00009947
Sean Hunt2b188082011-05-14 05:23:28 +00009948 case CXXCopyAssignment: {
9949 CheckExplicitlyDefaultedCopyAssignment(MD);
9950 if (!MD->isInvalidDecl())
9951 DefineImplicitCopyAssignment(DefaultLoc, MD);
9952 break;
9953 }
9954
Sean Huntcb45a0f2011-05-12 22:46:25 +00009955 case CXXDestructor: {
9956 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
9957 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +00009958 if (!DD->isInvalidDecl())
9959 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +00009960 break;
9961 }
9962
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009963 case CXXMoveConstructor: {
9964 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9965 CheckExplicitlyDefaultedMoveConstructor(CD);
9966 if (!CD->isInvalidDecl())
9967 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +00009968 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009969 }
Sean Hunt82713172011-05-25 23:16:36 +00009970
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009971 case CXXMoveAssignment: {
9972 CheckExplicitlyDefaultedMoveAssignment(MD);
9973 if (!MD->isInvalidDecl())
9974 DefineImplicitMoveAssignment(DefaultLoc, MD);
9975 break;
9976 }
9977
9978 case CXXInvalid:
9979 assert(false && "Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +00009980 break;
9981 }
9982 } else {
9983 Diag(DefaultLoc, diag::err_default_special_members);
9984 }
9985}
9986
Sebastian Redl13e88542009-04-27 21:33:24 +00009987static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00009988 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00009989 Stmt *SubStmt = *CI;
9990 if (!SubStmt)
9991 continue;
9992 if (isa<ReturnStmt>(SubStmt))
9993 Self.Diag(SubStmt->getSourceRange().getBegin(),
9994 diag::err_return_in_constructor_handler);
9995 if (!isa<Expr>(SubStmt))
9996 SearchForReturnInStmt(Self, SubStmt);
9997 }
9998}
9999
10000void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10001 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10002 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10003 SearchForReturnInStmt(*this, Handler);
10004 }
10005}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010006
Mike Stump1eb44332009-09-09 15:08:12 +000010007bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010008 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010009 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10010 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010011
Chandler Carruth73857792010-02-15 11:53:20 +000010012 if (Context.hasSameType(NewTy, OldTy) ||
10013 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010014 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010015
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010016 // Check if the return types are covariant
10017 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010018
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010019 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010020 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10021 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010022 NewClassTy = NewPT->getPointeeType();
10023 OldClassTy = OldPT->getPointeeType();
10024 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010025 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10026 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10027 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10028 NewClassTy = NewRT->getPointeeType();
10029 OldClassTy = OldRT->getPointeeType();
10030 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010031 }
10032 }
Mike Stump1eb44332009-09-09 15:08:12 +000010033
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010034 // The return types aren't either both pointers or references to a class type.
10035 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010036 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010037 diag::err_different_return_type_for_overriding_virtual_function)
10038 << New->getDeclName() << NewTy << OldTy;
10039 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010040
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010041 return true;
10042 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010043
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010044 // C++ [class.virtual]p6:
10045 // If the return type of D::f differs from the return type of B::f, the
10046 // class type in the return type of D::f shall be complete at the point of
10047 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010048 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10049 if (!RT->isBeingDefined() &&
10050 RequireCompleteType(New->getLocation(), NewClassTy,
10051 PDiag(diag::err_covariant_return_incomplete)
10052 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010053 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010054 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010055
Douglas Gregora4923eb2009-11-16 21:35:15 +000010056 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010057 // Check if the new class derives from the old class.
10058 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10059 Diag(New->getLocation(),
10060 diag::err_covariant_return_not_derived)
10061 << New->getDeclName() << NewTy << OldTy;
10062 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10063 return true;
10064 }
Mike Stump1eb44332009-09-09 15:08:12 +000010065
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010066 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010067 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010068 diag::err_covariant_return_inaccessible_base,
10069 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10070 // FIXME: Should this point to the return type?
10071 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010072 // FIXME: this note won't trigger for delayed access control
10073 // diagnostics, and it's impossible to get an undelayed error
10074 // here from access control during the original parse because
10075 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010076 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10077 return true;
10078 }
10079 }
Mike Stump1eb44332009-09-09 15:08:12 +000010080
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010081 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010082 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010083 Diag(New->getLocation(),
10084 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010085 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010086 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10087 return true;
10088 };
Mike Stump1eb44332009-09-09 15:08:12 +000010089
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010090
10091 // The new class type must have the same or less qualifiers as the old type.
10092 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10093 Diag(New->getLocation(),
10094 diag::err_covariant_return_type_class_type_more_qualified)
10095 << New->getDeclName() << NewTy << OldTy;
10096 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10097 return true;
10098 };
Mike Stump1eb44332009-09-09 15:08:12 +000010099
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010100 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010101}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010102
Douglas Gregor4ba31362009-12-01 17:24:26 +000010103/// \brief Mark the given method pure.
10104///
10105/// \param Method the method to be marked pure.
10106///
10107/// \param InitRange the source range that covers the "0" initializer.
10108bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010109 SourceLocation EndLoc = InitRange.getEnd();
10110 if (EndLoc.isValid())
10111 Method->setRangeEnd(EndLoc);
10112
Douglas Gregor4ba31362009-12-01 17:24:26 +000010113 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10114 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010115 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010116 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010117
10118 if (!Method->isInvalidDecl())
10119 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10120 << Method->getDeclName() << InitRange;
10121 return true;
10122}
10123
John McCall731ad842009-12-19 09:28:58 +000010124/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10125/// an initializer for the out-of-line declaration 'Dcl'. The scope
10126/// is a fresh scope pushed for just this purpose.
10127///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010128/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10129/// static data member of class X, names should be looked up in the scope of
10130/// class X.
John McCalld226f652010-08-21 09:40:31 +000010131void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010132 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010133 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010134
John McCall731ad842009-12-19 09:28:58 +000010135 // We should only get called for declarations with scope specifiers, like:
10136 // int foo::bar;
10137 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010138 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010139}
10140
10141/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010142/// initializer for the out-of-line declaration 'D'.
10143void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010144 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010145 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010146
John McCall731ad842009-12-19 09:28:58 +000010147 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010148 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010149}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010150
10151/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10152/// C++ if/switch/while/for statement.
10153/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010154DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010155 // C++ 6.4p2:
10156 // The declarator shall not specify a function or an array.
10157 // The type-specifier-seq shall not contain typedef and shall not declare a
10158 // new class or enumeration.
10159 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10160 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010161
10162 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010163 if (!Dcl)
10164 return true;
10165
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010166 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10167 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010168 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010169 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010170 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010171
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010172 return Dcl;
10173}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010174
Douglas Gregordfe65432011-07-28 19:11:31 +000010175void Sema::LoadExternalVTableUses() {
10176 if (!ExternalSource)
10177 return;
10178
10179 SmallVector<ExternalVTableUse, 4> VTables;
10180 ExternalSource->ReadUsedVTables(VTables);
10181 SmallVector<VTableUse, 4> NewUses;
10182 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10183 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10184 = VTablesUsed.find(VTables[I].Record);
10185 // Even if a definition wasn't required before, it may be required now.
10186 if (Pos != VTablesUsed.end()) {
10187 if (!Pos->second && VTables[I].DefinitionRequired)
10188 Pos->second = true;
10189 continue;
10190 }
10191
10192 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10193 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10194 }
10195
10196 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10197}
10198
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010199void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10200 bool DefinitionRequired) {
10201 // Ignore any vtable uses in unevaluated operands or for classes that do
10202 // not have a vtable.
10203 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10204 CurContext->isDependentContext() ||
10205 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010206 return;
10207
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010208 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010209 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010210 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10211 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10212 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10213 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010214 // If we already had an entry, check to see if we are promoting this vtable
10215 // to required a definition. If so, we need to reappend to the VTableUses
10216 // list, since we may have already processed the first entry.
10217 if (DefinitionRequired && !Pos.first->second) {
10218 Pos.first->second = true;
10219 } else {
10220 // Otherwise, we can early exit.
10221 return;
10222 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010223 }
10224
10225 // Local classes need to have their virtual members marked
10226 // immediately. For all other classes, we mark their virtual members
10227 // at the end of the translation unit.
10228 if (Class->isLocalClass())
10229 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010230 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010231 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010232}
10233
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010234bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010235 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010236 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010237 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010238
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010239 // Note: The VTableUses vector could grow as a result of marking
10240 // the members of a class as "used", so we check the size each
10241 // time through the loop and prefer indices (with are stable) to
10242 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010243 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010244 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010245 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010246 if (!Class)
10247 continue;
10248
10249 SourceLocation Loc = VTableUses[I].second;
10250
10251 // If this class has a key function, but that key function is
10252 // defined in another translation unit, we don't need to emit the
10253 // vtable even though we're using it.
10254 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010255 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010256 switch (KeyFunction->getTemplateSpecializationKind()) {
10257 case TSK_Undeclared:
10258 case TSK_ExplicitSpecialization:
10259 case TSK_ExplicitInstantiationDeclaration:
10260 // The key function is in another translation unit.
10261 continue;
10262
10263 case TSK_ExplicitInstantiationDefinition:
10264 case TSK_ImplicitInstantiation:
10265 // We will be instantiating the key function.
10266 break;
10267 }
10268 } else if (!KeyFunction) {
10269 // If we have a class with no key function that is the subject
10270 // of an explicit instantiation declaration, suppress the
10271 // vtable; it will live with the explicit instantiation
10272 // definition.
10273 bool IsExplicitInstantiationDeclaration
10274 = Class->getTemplateSpecializationKind()
10275 == TSK_ExplicitInstantiationDeclaration;
10276 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10277 REnd = Class->redecls_end();
10278 R != REnd; ++R) {
10279 TemplateSpecializationKind TSK
10280 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10281 if (TSK == TSK_ExplicitInstantiationDeclaration)
10282 IsExplicitInstantiationDeclaration = true;
10283 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10284 IsExplicitInstantiationDeclaration = false;
10285 break;
10286 }
10287 }
10288
10289 if (IsExplicitInstantiationDeclaration)
10290 continue;
10291 }
10292
10293 // Mark all of the virtual members of this class as referenced, so
10294 // that we can build a vtable. Then, tell the AST consumer that a
10295 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010296 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010297 MarkVirtualMembersReferenced(Loc, Class);
10298 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10299 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10300
10301 // Optionally warn if we're emitting a weak vtable.
10302 if (Class->getLinkage() == ExternalLinkage &&
10303 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010304 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010305 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10306 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010307 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010308 VTableUses.clear();
10309
Douglas Gregor78844032011-04-22 22:25:37 +000010310 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010311}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010312
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010313void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10314 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010315 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10316 e = RD->method_end(); i != e; ++i) {
10317 CXXMethodDecl *MD = *i;
10318
10319 // C++ [basic.def.odr]p2:
10320 // [...] A virtual member function is used if it is not pure. [...]
10321 if (MD->isVirtual() && !MD->isPure())
10322 MarkDeclarationReferenced(Loc, MD);
10323 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010324
10325 // Only classes that have virtual bases need a VTT.
10326 if (RD->getNumVBases() == 0)
10327 return;
10328
10329 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10330 e = RD->bases_end(); i != e; ++i) {
10331 const CXXRecordDecl *Base =
10332 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010333 if (Base->getNumVBases() == 0)
10334 continue;
10335 MarkVirtualMembersReferenced(Loc, Base);
10336 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010337}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010338
10339/// SetIvarInitializers - This routine builds initialization ASTs for the
10340/// Objective-C implementation whose ivars need be initialized.
10341void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10342 if (!getLangOptions().CPlusPlus)
10343 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010344 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010345 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010346 CollectIvarsToConstructOrDestruct(OID, ivars);
10347 if (ivars.empty())
10348 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010349 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010350 for (unsigned i = 0; i < ivars.size(); i++) {
10351 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010352 if (Field->isInvalidDecl())
10353 continue;
10354
Sean Huntcbb67482011-01-08 20:30:50 +000010355 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010356 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10357 InitializationKind InitKind =
10358 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10359
10360 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010361 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010362 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010363 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010364 // Note, MemberInit could actually come back empty if no initialization
10365 // is required (e.g., because it would call a trivial default constructor)
10366 if (!MemberInit.get() || MemberInit.isInvalid())
10367 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010368
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010369 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010370 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10371 SourceLocation(),
10372 MemberInit.takeAs<Expr>(),
10373 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010374 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010375
10376 // Be sure that the destructor is accessible and is marked as referenced.
10377 if (const RecordType *RecordTy
10378 = Context.getBaseElementType(Field->getType())
10379 ->getAs<RecordType>()) {
10380 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010381 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010382 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10383 CheckDestructorAccess(Field->getLocation(), Destructor,
10384 PDiag(diag::err_access_dtor_ivar)
10385 << Context.getBaseElementType(Field->getType()));
10386 }
10387 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010388 }
10389 ObjCImplementation->setIvarInitializers(Context,
10390 AllToInit.data(), AllToInit.size());
10391 }
10392}
Sean Huntfe57eef2011-05-04 05:57:24 +000010393
Sean Huntebcbe1d2011-05-04 23:29:54 +000010394static
10395void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10396 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10397 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10398 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10399 Sema &S) {
10400 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10401 CE = Current.end();
10402 if (Ctor->isInvalidDecl())
10403 return;
10404
10405 const FunctionDecl *FNTarget = 0;
10406 CXXConstructorDecl *Target;
10407
10408 // We ignore the result here since if we don't have a body, Target will be
10409 // null below.
10410 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10411 Target
10412= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10413
10414 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10415 // Avoid dereferencing a null pointer here.
10416 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10417
10418 if (!Current.insert(Canonical))
10419 return;
10420
10421 // We know that beyond here, we aren't chaining into a cycle.
10422 if (!Target || !Target->isDelegatingConstructor() ||
10423 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10424 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10425 Valid.insert(*CI);
10426 Current.clear();
10427 // We've hit a cycle.
10428 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10429 Current.count(TCanonical)) {
10430 // If we haven't diagnosed this cycle yet, do so now.
10431 if (!Invalid.count(TCanonical)) {
10432 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010433 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010434 << Ctor;
10435
10436 // Don't add a note for a function delegating directo to itself.
10437 if (TCanonical != Canonical)
10438 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10439
10440 CXXConstructorDecl *C = Target;
10441 while (C->getCanonicalDecl() != Canonical) {
10442 (void)C->getTargetConstructor()->hasBody(FNTarget);
10443 assert(FNTarget && "Ctor cycle through bodiless function");
10444
10445 C
10446 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10447 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10448 }
10449 }
10450
10451 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10452 Invalid.insert(*CI);
10453 Current.clear();
10454 } else {
10455 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10456 }
10457}
10458
10459
Sean Huntfe57eef2011-05-04 05:57:24 +000010460void Sema::CheckDelegatingCtorCycles() {
10461 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10462
Sean Huntebcbe1d2011-05-04 23:29:54 +000010463 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10464 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010465
Douglas Gregor0129b562011-07-27 21:57:17 +000010466 for (DelegatingCtorDeclsType::iterator
10467 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010468 E = DelegatingCtorDecls.end();
10469 I != E; ++I) {
10470 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010471 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010472
10473 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10474 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010475}