blob: 14890cf920e38fac99965c44525b1123c8fa6c82 [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;
395 if (getLangOptions().Microsoft) {
396 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.
John McCalld226f652010-08-21 09:40:31 +0000800void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **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,
Anders Carlsson69a87352011-01-20 03:57:25 +00001063 ExprTy *BW, const VirtSpecifiers &VS,
Richard Smith7a614d82011-06-11 17:19:42 +00001064 ExprTy *InitExpr, bool HasDeferredInit,
1065 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 Gregor922fff22010-10-13 22:19:53 +00001124 if (SS.isSet() && !SS.isInvalid()) {
1125 // The user provided a superfluous scope specifier inside a class
1126 // definition:
1127 //
1128 // class X {
1129 // int X::member;
1130 // };
1131 DeclContext *DC = 0;
1132 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1133 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1134 << Name << FixItHint::CreateRemoval(SS.getRange());
1135 else
1136 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1137 << Name << SS.getRange();
1138
1139 SS.clear();
1140 }
1141
Douglas Gregor37b372b2009-08-20 22:52:58 +00001142 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001143 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001144 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001145 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001146 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001147 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001148 assert(!HasDeferredInit);
1149
Sean Hunte4246a62011-05-12 06:15:49 +00001150 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001151 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001152 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001153 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001154
1155 // Non-instance-fields can't have a bitfield.
1156 if (BitWidth) {
1157 if (Member->isInvalidDecl()) {
1158 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001159 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001160 // C++ 9.6p3: A bit-field shall not be a static member.
1161 // "static member 'A' cannot be a bit-field"
1162 Diag(Loc, diag::err_static_not_bitfield)
1163 << Name << BitWidth->getSourceRange();
1164 } else if (isa<TypedefDecl>(Member)) {
1165 // "typedef member 'x' cannot be a bit-field"
1166 Diag(Loc, diag::err_typedef_not_bitfield)
1167 << Name << BitWidth->getSourceRange();
1168 } else {
1169 // A function typedef ("typedef int f(); f a;").
1170 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1171 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001172 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001173 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001174 }
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Chris Lattner8b963ef2009-03-05 23:01:03 +00001176 BitWidth = 0;
1177 Member->setInvalidDecl();
1178 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001179
1180 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Douglas Gregor37b372b2009-08-20 22:52:58 +00001182 // If we have declared a member function template, set the access of the
1183 // templated declaration as well.
1184 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1185 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001186 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001187
Anders Carlssonaae5af22011-01-20 04:34:22 +00001188 if (VS.isOverrideSpecified()) {
1189 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1190 if (!MD || !MD->isVirtual()) {
1191 Diag(Member->getLocStart(),
1192 diag::override_keyword_only_allowed_on_virtual_member_functions)
1193 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001194 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001195 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001196 }
1197 if (VS.isFinalSpecified()) {
1198 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1199 if (!MD || !MD->isVirtual()) {
1200 Diag(Member->getLocStart(),
1201 diag::override_keyword_only_allowed_on_virtual_member_functions)
1202 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001203 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001204 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001205 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001206
Douglas Gregorf5251602011-03-08 17:10:18 +00001207 if (VS.getLastLocation().isValid()) {
1208 // Update the end location of a method that has a virt-specifiers.
1209 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1210 MD->setRangeEnd(VS.getLastLocation());
1211 }
1212
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001213 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001214
Douglas Gregor10bd3682008-11-17 22:58:34 +00001215 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001216
Douglas Gregor021c3b32009-03-11 23:00:04 +00001217 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001218 AddInitializerToDecl(Member, Init, false,
1219 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smith7a614d82011-06-11 17:19:42 +00001220 else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1221 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1222 // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1223 // data member if a brace-or-equal-initializer is provided.
1224 Diag(Loc, diag::err_auto_var_requires_init)
1225 << Name << cast<ValueDecl>(Member)->getType();
1226 Member->setInvalidDecl();
1227 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001228
Richard Smith483b9f32011-02-21 20:05:19 +00001229 FinalizeDeclaration(Member);
1230
John McCallb25b2952011-02-15 07:12:36 +00001231 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001232 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001233 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001234}
1235
Richard Smith7a614d82011-06-11 17:19:42 +00001236/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001237/// in-class initializer for a non-static C++ class member, and after
1238/// instantiating an in-class initializer in a class template. Such actions
1239/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001240void
1241Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1242 Expr *InitExpr) {
1243 FieldDecl *FD = cast<FieldDecl>(D);
1244
1245 if (!InitExpr) {
1246 FD->setInvalidDecl();
1247 FD->removeInClassInitializer();
1248 return;
1249 }
1250
1251 ExprResult Init = InitExpr;
1252 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1253 // FIXME: if there is no EqualLoc, this is list-initialization.
1254 Init = PerformCopyInitialization(
1255 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1256 if (Init.isInvalid()) {
1257 FD->setInvalidDecl();
1258 return;
1259 }
1260
1261 CheckImplicitConversions(Init.get(), EqualLoc);
1262 }
1263
1264 // C++0x [class.base.init]p7:
1265 // The initialization of each base and member constitutes a
1266 // full-expression.
1267 Init = MaybeCreateExprWithCleanups(Init);
1268 if (Init.isInvalid()) {
1269 FD->setInvalidDecl();
1270 return;
1271 }
1272
1273 InitExpr = Init.release();
1274
1275 FD->setInClassInitializer(InitExpr);
1276}
1277
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001278/// \brief Find the direct and/or virtual base specifiers that
1279/// correspond to the given base type, for use in base initialization
1280/// within a constructor.
1281static bool FindBaseInitializer(Sema &SemaRef,
1282 CXXRecordDecl *ClassDecl,
1283 QualType BaseType,
1284 const CXXBaseSpecifier *&DirectBaseSpec,
1285 const CXXBaseSpecifier *&VirtualBaseSpec) {
1286 // First, check for a direct base class.
1287 DirectBaseSpec = 0;
1288 for (CXXRecordDecl::base_class_const_iterator Base
1289 = ClassDecl->bases_begin();
1290 Base != ClassDecl->bases_end(); ++Base) {
1291 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1292 // We found a direct base of this type. That's what we're
1293 // initializing.
1294 DirectBaseSpec = &*Base;
1295 break;
1296 }
1297 }
1298
1299 // Check for a virtual base class.
1300 // FIXME: We might be able to short-circuit this if we know in advance that
1301 // there are no virtual bases.
1302 VirtualBaseSpec = 0;
1303 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1304 // We haven't found a base yet; search the class hierarchy for a
1305 // virtual base class.
1306 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1307 /*DetectVirtual=*/false);
1308 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1309 BaseType, Paths)) {
1310 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1311 Path != Paths.end(); ++Path) {
1312 if (Path->back().Base->isVirtual()) {
1313 VirtualBaseSpec = Path->back().Base;
1314 break;
1315 }
1316 }
1317 }
1318 }
1319
1320 return DirectBaseSpec || VirtualBaseSpec;
1321}
1322
Douglas Gregor7ad83902008-11-05 04:29:56 +00001323/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001324MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001325Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001326 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001327 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001328 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001329 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001330 SourceLocation IdLoc,
1331 SourceLocation LParenLoc,
1332 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001333 SourceLocation RParenLoc,
1334 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001335 if (!ConstructorD)
1336 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001338 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001339
1340 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001341 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001342 if (!Constructor) {
1343 // The user wrote a constructor initializer on a function that is
1344 // not a C++ constructor. Ignore the error for now, because we may
1345 // have more member initializers coming; we'll diagnose it just
1346 // once in ActOnMemInitializers.
1347 return true;
1348 }
1349
1350 CXXRecordDecl *ClassDecl = Constructor->getParent();
1351
1352 // C++ [class.base.init]p2:
1353 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001354 // constructor's class and, if not found in that scope, are looked
1355 // up in the scope containing the constructor's definition.
1356 // [Note: if the constructor's class contains a member with the
1357 // same name as a direct or virtual base class of the class, a
1358 // mem-initializer-id naming the member or base class and composed
1359 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001360 // mem-initializer-id for the hidden base class may be specified
1361 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001362 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001363 // Look for a member, first.
1364 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001365 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001366 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001367 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001368 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001369
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001370 if (Member) {
1371 if (EllipsisLoc.isValid())
1372 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1373 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1374
Francois Pichet00eb3f92010-12-04 09:14:42 +00001375 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001376 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001377 }
1378
Francois Pichet00eb3f92010-12-04 09:14:42 +00001379 // Handle anonymous union case.
1380 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001381 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1382 if (EllipsisLoc.isValid())
1383 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1384 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1385
Francois Pichet00eb3f92010-12-04 09:14:42 +00001386 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1387 NumArgs, IdLoc,
1388 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001389 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001390 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001391 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001392 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001393 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001394 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001395
1396 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001397 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001398 } else {
1399 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1400 LookupParsedName(R, S, &SS);
1401
1402 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1403 if (!TyD) {
1404 if (R.isAmbiguous()) return true;
1405
John McCallfd225442010-04-09 19:01:14 +00001406 // We don't want access-control diagnostics here.
1407 R.suppressDiagnostics();
1408
Douglas Gregor7a886e12010-01-19 06:46:48 +00001409 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1410 bool NotUnknownSpecialization = false;
1411 DeclContext *DC = computeDeclContext(SS, false);
1412 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1413 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1414
1415 if (!NotUnknownSpecialization) {
1416 // When the scope specifier can refer to a member of an unknown
1417 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001418 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1419 SS.getWithLocInContext(Context),
1420 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001421 if (BaseType.isNull())
1422 return true;
1423
Douglas Gregor7a886e12010-01-19 06:46:48 +00001424 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001425 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001426 }
1427 }
1428
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001429 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001430 TypoCorrection Corr;
Douglas Gregor7a886e12010-01-19 06:46:48 +00001431 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001432 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1433 ClassDecl, false, CTC_NoKeywords))) {
1434 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1435 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1436 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001437 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001438 // We have found a non-static data member with a similar
1439 // name to what was typed; complain and initialize that
1440 // member.
1441 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001442 << MemberOrBase << true << CorrectedQuotedStr
1443 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001444 Diag(Member->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001445 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001446
1447 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1448 LParenLoc, RParenLoc);
1449 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001450 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001451 const CXXBaseSpecifier *DirectBaseSpec;
1452 const CXXBaseSpecifier *VirtualBaseSpec;
1453 if (FindBaseInitializer(*this, ClassDecl,
1454 Context.getTypeDeclType(Type),
1455 DirectBaseSpec, VirtualBaseSpec)) {
1456 // We have found a direct or virtual base class with a
1457 // similar name to what was typed; complain and initialize
1458 // that base class.
1459 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001460 << MemberOrBase << false << CorrectedQuotedStr
1461 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001462
1463 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1464 : VirtualBaseSpec;
1465 Diag(BaseSpec->getSourceRange().getBegin(),
1466 diag::note_base_class_specified_here)
1467 << BaseSpec->getType()
1468 << BaseSpec->getSourceRange();
1469
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001470 TyD = Type;
1471 }
1472 }
1473 }
1474
Douglas Gregor7a886e12010-01-19 06:46:48 +00001475 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001476 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1477 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1478 return true;
1479 }
John McCall2b194412009-12-21 10:41:20 +00001480 }
1481
Douglas Gregor7a886e12010-01-19 06:46:48 +00001482 if (BaseType.isNull()) {
1483 BaseType = Context.getTypeDeclType(TyD);
1484 if (SS.isSet()) {
1485 NestedNameSpecifier *Qualifier =
1486 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001487
Douglas Gregor7a886e12010-01-19 06:46:48 +00001488 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001489 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001490 }
John McCall2b194412009-12-21 10:41:20 +00001491 }
1492 }
Mike Stump1eb44332009-09-09 15:08:12 +00001493
John McCalla93c9342009-12-07 02:54:59 +00001494 if (!TInfo)
1495 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001496
John McCalla93c9342009-12-07 02:54:59 +00001497 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001498 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001499}
1500
Chandler Carruth81c64772011-09-03 01:14:15 +00001501/// Checks a member initializer expression for cases where reference (or
1502/// pointer) members are bound to by-value parameters (or their addresses).
1503/// FIXME: We should also flag temporaries here.
1504static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1505 Expr *Init,
1506 SourceLocation IdLoc) {
1507 QualType MemberTy = Member->getType();
1508
1509 // We only handle pointers and references currently.
1510 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1511 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1512 return;
1513
1514 const bool IsPointer = MemberTy->isPointerType();
1515 if (IsPointer) {
1516 if (const UnaryOperator *Op
1517 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1518 // The only case we're worried about with pointers requires taking the
1519 // address.
1520 if (Op->getOpcode() != UO_AddrOf)
1521 return;
1522
1523 Init = Op->getSubExpr();
1524 } else {
1525 // We only handle address-of expression initializers for pointers.
1526 return;
1527 }
1528 }
1529
1530 // We only warn when referring to a non-reference declaration.
1531 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParenCasts());
1532 if (!DRE)
1533 return;
1534
1535 if (const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1536 if (Parameter->getType()->isReferenceType())
1537 return;
1538
1539 S.Diag(Init->getExprLoc(),
1540 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1541 : diag::warn_bind_ref_member_to_parameter)
1542 << Member << Parameter << Init->getSourceRange();
1543 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1544 << (unsigned)IsPointer;
1545 }
1546}
1547
John McCallb4190042009-11-04 23:02:40 +00001548/// Checks an initializer expression for use of uninitialized fields, such as
1549/// containing the field that is being initialized. Returns true if there is an
1550/// uninitialized field was used an updates the SourceLocation parameter; false
1551/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001552static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001553 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001554 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001555 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1556
Nick Lewycky43ad1822010-06-15 07:32:55 +00001557 if (isa<CallExpr>(S)) {
1558 // Do not descend into function calls or constructors, as the use
1559 // of an uninitialized field may be valid. One would have to inspect
1560 // the contents of the function/ctor to determine if it is safe or not.
1561 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1562 // may be safe, depending on what the function/ctor does.
1563 return false;
1564 }
1565 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1566 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001567
1568 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1569 // The member expression points to a static data member.
1570 assert(VD->isStaticDataMember() &&
1571 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001572 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001573 return false;
1574 }
1575
1576 if (isa<EnumConstantDecl>(RhsField)) {
1577 // The member expression points to an enum.
1578 return false;
1579 }
1580
John McCallb4190042009-11-04 23:02:40 +00001581 if (RhsField == LhsField) {
1582 // Initializing a field with itself. Throw a warning.
1583 // But wait; there are exceptions!
1584 // Exception #1: The field may not belong to this record.
1585 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001586 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001587 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1588 // Even though the field matches, it does not belong to this record.
1589 return false;
1590 }
1591 // None of the exceptions triggered; return true to indicate an
1592 // uninitialized field was used.
1593 *L = ME->getMemberLoc();
1594 return true;
1595 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001596 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001597 // sizeof/alignof doesn't reference contents, do not warn.
1598 return false;
1599 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1600 // address-of doesn't reference contents (the pointer may be dereferenced
1601 // in the same expression but it would be rare; and weird).
1602 if (UOE->getOpcode() == UO_AddrOf)
1603 return false;
John McCallb4190042009-11-04 23:02:40 +00001604 }
John McCall7502c1d2011-02-13 04:07:26 +00001605 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001606 if (!*it) {
1607 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001608 continue;
1609 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001610 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1611 return true;
John McCallb4190042009-11-04 23:02:40 +00001612 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001613 return false;
John McCallb4190042009-11-04 23:02:40 +00001614}
1615
John McCallf312b1e2010-08-26 23:41:50 +00001616MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001617Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001618 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001619 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001620 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001621 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1622 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1623 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001624 "Member must be a FieldDecl or IndirectFieldDecl");
1625
Douglas Gregor464b2f02010-11-05 22:21:31 +00001626 if (Member->isInvalidDecl())
1627 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001628
John McCallb4190042009-11-04 23:02:40 +00001629 // Diagnose value-uses of fields to initialize themselves, e.g.
1630 // foo(foo)
1631 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001632 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001633 for (unsigned i = 0; i < NumArgs; ++i) {
1634 SourceLocation L;
1635 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1636 // FIXME: Return true in the case when other fields are used before being
1637 // uninitialized. For example, let this field be the i'th field. When
1638 // initializing the i'th field, throw a warning if any of the >= i'th
1639 // fields are used, as they are not yet initialized.
1640 // Right now we are only handling the case where the i'th field uses
1641 // itself in its initializer.
1642 Diag(L, diag::warn_field_is_uninit);
1643 }
1644 }
1645
Eli Friedman59c04372009-07-29 19:44:27 +00001646 bool HasDependentArg = false;
1647 for (unsigned i = 0; i < NumArgs; i++)
1648 HasDependentArg |= Args[i]->isTypeDependent();
1649
Chandler Carruth894aed92010-12-06 09:23:57 +00001650 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001651 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001652 // Can't check initialization for a member of dependent type or when
1653 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001654 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001655 RParenLoc,
1656 Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001657
John McCallf85e1932011-06-15 23:02:42 +00001658 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00001659 } else {
1660 // Initialize the member.
1661 InitializedEntity MemberEntity =
1662 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1663 : InitializedEntity::InitializeMember(IndirectMember, 0);
1664 InitializationKind Kind =
1665 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001666
Chandler Carruth894aed92010-12-06 09:23:57 +00001667 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1668
1669 ExprResult MemberInit =
1670 InitSeq.Perform(*this, MemberEntity, Kind,
1671 MultiExprArg(*this, Args, NumArgs), 0);
1672 if (MemberInit.isInvalid())
1673 return true;
1674
1675 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1676
1677 // C++0x [class.base.init]p7:
1678 // The initialization of each base and member constitutes a
1679 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001680 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001681 if (MemberInit.isInvalid())
1682 return true;
1683
1684 // If we are in a dependent context, template instantiation will
1685 // perform this type-checking again. Just save the arguments that we
1686 // received in a ParenListExpr.
1687 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1688 // of the information that we have about the member
1689 // initializer. However, deconstructing the ASTs is a dicey process,
1690 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00001691 if (CurContext->isDependentContext()) {
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001692 Init = new (Context) ParenListExpr(
1693 Context, LParenLoc, Args, NumArgs, RParenLoc,
1694 Member->getType().getNonReferenceType());
Chandler Carruth81c64772011-09-03 01:14:15 +00001695 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00001696 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00001697 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
1698 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001699 }
1700
Chandler Carruth894aed92010-12-06 09:23:57 +00001701 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001702 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001703 IdLoc, LParenLoc, Init,
1704 RParenLoc);
1705 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001706 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001707 IdLoc, LParenLoc, Init,
1708 RParenLoc);
1709 }
Eli Friedman59c04372009-07-29 19:44:27 +00001710}
1711
John McCallf312b1e2010-08-26 23:41:50 +00001712MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001713Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1714 Expr **Args, unsigned NumArgs,
Sean Hunt41717662011-02-26 19:13:13 +00001715 SourceLocation NameLoc,
Sean Hunt97fcc492011-01-08 19:20:43 +00001716 SourceLocation LParenLoc,
1717 SourceLocation RParenLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001718 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001719 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1720 if (!LangOpts.CPlusPlus0x)
1721 return Diag(Loc, diag::err_delegation_0x_only)
1722 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001723
Sean Hunt41717662011-02-26 19:13:13 +00001724 // Initialize the object.
1725 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1726 QualType(ClassDecl->getTypeForDecl(), 0));
1727 InitializationKind Kind =
1728 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1729
1730 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1731
1732 ExprResult DelegationInit =
1733 InitSeq.Perform(*this, DelegationEntity, Kind,
1734 MultiExprArg(*this, Args, NumArgs), 0);
1735 if (DelegationInit.isInvalid())
1736 return true;
1737
1738 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Sean Huntfe57eef2011-05-04 05:57:24 +00001739 CXXConstructorDecl *Constructor
1740 = ConExpr->getConstructor();
Sean Hunt41717662011-02-26 19:13:13 +00001741 assert(Constructor && "Delegating constructor with no target?");
1742
1743 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1744
1745 // C++0x [class.base.init]p7:
1746 // The initialization of each base and member constitutes a
1747 // full-expression.
1748 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1749 if (DelegationInit.isInvalid())
1750 return true;
1751
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001752 assert(!CurContext->isDependentContext());
Sean Hunt41717662011-02-26 19:13:13 +00001753 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1754 DelegationInit.takeAs<Expr>(),
1755 RParenLoc);
Sean Hunt97fcc492011-01-08 19:20:43 +00001756}
1757
1758MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001759Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001760 Expr **Args, unsigned NumArgs,
1761 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001762 CXXRecordDecl *ClassDecl,
1763 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001764 bool HasDependentArg = false;
1765 for (unsigned i = 0; i < NumArgs; i++)
1766 HasDependentArg |= Args[i]->isTypeDependent();
1767
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001768 SourceLocation BaseLoc
1769 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1770
1771 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1772 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1773 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1774
1775 // C++ [class.base.init]p2:
1776 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001777 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001778 // of that class, the mem-initializer is ill-formed. A
1779 // mem-initializer-list can initialize a base class using any
1780 // name that denotes that base class type.
1781 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1782
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001783 if (EllipsisLoc.isValid()) {
1784 // This is a pack expansion.
1785 if (!BaseType->containsUnexpandedParameterPack()) {
1786 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1787 << SourceRange(BaseLoc, RParenLoc);
1788
1789 EllipsisLoc = SourceLocation();
1790 }
1791 } else {
1792 // Check for any unexpanded parameter packs.
1793 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1794 return true;
1795
1796 for (unsigned I = 0; I != NumArgs; ++I)
1797 if (DiagnoseUnexpandedParameterPack(Args[I]))
1798 return true;
1799 }
1800
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001801 // Check for direct and virtual base classes.
1802 const CXXBaseSpecifier *DirectBaseSpec = 0;
1803 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1804 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001805 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1806 BaseType))
Sean Hunt41717662011-02-26 19:13:13 +00001807 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1808 LParenLoc, RParenLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001809
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001810 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1811 VirtualBaseSpec);
1812
1813 // C++ [base.class.init]p2:
1814 // Unless the mem-initializer-id names a nonstatic data member of the
1815 // constructor's class or a direct or virtual base of that class, the
1816 // mem-initializer is ill-formed.
1817 if (!DirectBaseSpec && !VirtualBaseSpec) {
1818 // If the class has any dependent bases, then it's possible that
1819 // one of those types will resolve to the same type as
1820 // BaseType. Therefore, just treat this as a dependent base
1821 // class initialization. FIXME: Should we try to check the
1822 // initialization anyway? It seems odd.
1823 if (ClassDecl->hasAnyDependentBases())
1824 Dependent = true;
1825 else
1826 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1827 << BaseType << Context.getTypeDeclType(ClassDecl)
1828 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1829 }
1830 }
1831
1832 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001833 // Can't check initialization for a base of dependent type or when
1834 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001835 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001836 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001837 RParenLoc, BaseType));
Eli Friedman59c04372009-07-29 19:44:27 +00001838
John McCallf85e1932011-06-15 23:02:42 +00001839 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Sean Huntcbb67482011-01-08 20:30:50 +00001841 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001842 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001843 LParenLoc,
1844 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001845 RParenLoc,
1846 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001847 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001848
1849 // C++ [base.class.init]p2:
1850 // If a mem-initializer-id is ambiguous because it designates both
1851 // a direct non-virtual base class and an inherited virtual base
1852 // class, the mem-initializer is ill-formed.
1853 if (DirectBaseSpec && VirtualBaseSpec)
1854 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001855 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001856
1857 CXXBaseSpecifier *BaseSpec
1858 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1859 if (!BaseSpec)
1860 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1861
1862 // Initialize the base.
1863 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001864 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001865 InitializationKind Kind =
1866 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1867
1868 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1869
John McCall60d7b3a2010-08-24 06:29:42 +00001870 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001871 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001872 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001873 if (BaseInit.isInvalid())
1874 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001875
1876 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001877
1878 // C++0x [class.base.init]p7:
1879 // The initialization of each base and member constitutes a
1880 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001881 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001882 if (BaseInit.isInvalid())
1883 return true;
1884
1885 // If we are in a dependent context, template instantiation will
1886 // perform this type-checking again. Just save the arguments that we
1887 // received in a ParenListExpr.
1888 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1889 // of the information that we have about the base
1890 // initializer. However, deconstructing the ASTs is a dicey process,
1891 // and this approach is far more likely to get the corner cases right.
1892 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001893 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001894 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001895 RParenLoc, BaseType));
Sean Huntcbb67482011-01-08 20:30:50 +00001896 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001897 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001898 LParenLoc,
1899 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001900 RParenLoc,
1901 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001902 }
1903
Sean Huntcbb67482011-01-08 20:30:50 +00001904 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001905 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001906 LParenLoc,
1907 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001908 RParenLoc,
1909 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001910}
1911
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001912// Create a static_cast\<T&&>(expr).
1913static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
1914 QualType ExprType = E->getType();
1915 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
1916 SourceLocation ExprLoc = E->getLocStart();
1917 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
1918 TargetType, ExprLoc);
1919
1920 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1921 SourceRange(ExprLoc, ExprLoc),
1922 E->getSourceRange()).take();
1923}
1924
Anders Carlssone5ef7402010-04-23 03:10:23 +00001925/// ImplicitInitializerKind - How an implicit base or member initializer should
1926/// initialize its base or member.
1927enum ImplicitInitializerKind {
1928 IIK_Default,
1929 IIK_Copy,
1930 IIK_Move
1931};
1932
Anders Carlssondefefd22010-04-23 02:00:02 +00001933static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001934BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001935 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001936 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001937 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001938 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001939 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001940 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1941 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001942
John McCall60d7b3a2010-08-24 06:29:42 +00001943 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001944
1945 switch (ImplicitInitKind) {
1946 case IIK_Default: {
1947 InitializationKind InitKind
1948 = InitializationKind::CreateDefault(Constructor->getLocation());
1949 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1950 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001951 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001952 break;
1953 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001954
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001955 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00001956 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001957 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001958 ParmVarDecl *Param = Constructor->getParamDecl(0);
1959 QualType ParamType = Param->getType().getNonReferenceType();
1960
1961 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001962 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001963 Constructor->getLocation(), ParamType,
1964 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001965
Anders Carlssonc7957502010-04-24 22:02:54 +00001966 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001967 QualType ArgTy =
1968 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1969 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001970
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001971 if (Moving) {
1972 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
1973 }
1974
John McCallf871d0c2010-08-07 06:22:56 +00001975 CXXCastPath BasePath;
1976 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00001977 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1978 CK_UncheckedDerivedToBase,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001979 Moving ? VK_RValue : VK_LValue,
1980 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00001981
Anders Carlssone5ef7402010-04-23 03:10:23 +00001982 InitializationKind InitKind
1983 = InitializationKind::CreateDirect(Constructor->getLocation(),
1984 SourceLocation(), SourceLocation());
1985 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1986 &CopyCtorArg, 1);
1987 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001988 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001989 break;
1990 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00001991 }
John McCall9ae2f072010-08-23 23:25:46 +00001992
Douglas Gregor53c374f2010-12-07 00:41:46 +00001993 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001994 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001995 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001996
Anders Carlssondefefd22010-04-23 02:00:02 +00001997 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001998 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001999 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2000 SourceLocation()),
2001 BaseSpec->isVirtual(),
2002 SourceLocation(),
2003 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002004 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002005 SourceLocation());
2006
Anders Carlssondefefd22010-04-23 02:00:02 +00002007 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002008}
2009
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002010static bool RefersToRValueRef(Expr *MemRef) {
2011 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2012 return Referenced->getType()->isRValueReferenceType();
2013}
2014
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002015static bool
2016BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002017 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002018 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002019 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002020 if (Field->isInvalidDecl())
2021 return true;
2022
Chandler Carruthf186b542010-06-29 23:50:44 +00002023 SourceLocation Loc = Constructor->getLocation();
2024
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002025 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2026 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002027 ParmVarDecl *Param = Constructor->getParamDecl(0);
2028 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002029
2030 // Suppress copying zero-width bitfields.
2031 if (const Expr *Width = Field->getBitWidth())
2032 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
2033 return false;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002034
2035 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00002036 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002037 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002038
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002039 if (Moving) {
2040 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2041 }
2042
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002043 // Build a reference to this field within the parameter.
2044 CXXScopeSpec SS;
2045 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2046 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002047 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2048 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002049 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00002050 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002051 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002052 ParamType, Loc,
2053 /*IsArrow=*/false,
2054 SS,
2055 /*FirstQualifierInScope=*/0,
2056 MemberLookup,
2057 /*TemplateArgs=*/0);
2058 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002059 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002060
2061 // C++11 [class.copy]p15:
2062 // - if a member m has rvalue reference type T&&, it is direct-initialized
2063 // with static_cast<T&&>(x.m);
2064 if (RefersToRValueRef(CopyCtorArg.get())) {
2065 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg.take());
2066 }
2067
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002068 // When the field we are copying is an array, create index variables for
2069 // each dimension of the array. We use these index variables to subscript
2070 // the source array, and other clients (e.g., CodeGen) will perform the
2071 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002072 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002073 QualType BaseType = Field->getType();
2074 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002075 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002076 while (const ConstantArrayType *Array
2077 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002078 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002079 // Create the iteration variable for this array index.
2080 IdentifierInfo *IterationVarName = 0;
2081 {
2082 llvm::SmallString<8> Str;
2083 llvm::raw_svector_ostream OS(Str);
2084 OS << "__i" << IndexVariables.size();
2085 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2086 }
2087 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002088 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002089 IterationVarName, SizeType,
2090 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002091 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002092 IndexVariables.push_back(IterationVar);
2093
2094 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002095 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00002096 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002097 assert(!IterationVarRef.isInvalid() &&
2098 "Reference to invented variable cannot fail!");
2099
2100 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00002101 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002102 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002103 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002104 Loc);
2105 if (CopyCtorArg.isInvalid())
2106 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002107
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002108 BaseType = Array->getElementType();
2109 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002110
2111 // The array subscript expression is an lvalue, which is wrong for moving.
2112 if (Moving && InitializingArray)
2113 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg.take());
2114
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002115 // Construct the entity that we will be initializing. For an array, this
2116 // will be first element in the array, which may require several levels
2117 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002118 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002119 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002120 if (Indirect)
2121 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2122 else
2123 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002124 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2125 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2126 0,
2127 Entities.back()));
2128
2129 // Direct-initialize to use the copy constructor.
2130 InitializationKind InitKind =
2131 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2132
2133 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2134 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2135 &CopyCtorArgE, 1);
2136
John McCall60d7b3a2010-08-24 06:29:42 +00002137 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002138 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002139 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002140 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002141 if (MemberInit.isInvalid())
2142 return true;
2143
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002144 if (Indirect) {
2145 assert(IndexVariables.size() == 0 &&
2146 "Indirect field improperly initialized");
2147 CXXMemberInit
2148 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2149 Loc, Loc,
2150 MemberInit.takeAs<Expr>(),
2151 Loc);
2152 } else
2153 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2154 Loc, MemberInit.takeAs<Expr>(),
2155 Loc,
2156 IndexVariables.data(),
2157 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002158 return false;
2159 }
2160
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002161 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2162
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002163 QualType FieldBaseElementType =
2164 SemaRef.Context.getBaseElementType(Field->getType());
2165
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002166 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002167 InitializedEntity InitEntity
2168 = Indirect? InitializedEntity::InitializeMember(Indirect)
2169 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002170 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002171 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002172
2173 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002174 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002175 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002176
Douglas Gregor53c374f2010-12-07 00:41:46 +00002177 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002178 if (MemberInit.isInvalid())
2179 return true;
2180
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002181 if (Indirect)
2182 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2183 Indirect, Loc,
2184 Loc,
2185 MemberInit.get(),
2186 Loc);
2187 else
2188 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2189 Field, Loc, Loc,
2190 MemberInit.get(),
2191 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002192 return false;
2193 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002194
Sean Hunt1f2f3842011-05-17 00:19:05 +00002195 if (!Field->getParent()->isUnion()) {
2196 if (FieldBaseElementType->isReferenceType()) {
2197 SemaRef.Diag(Constructor->getLocation(),
2198 diag::err_uninitialized_member_in_ctor)
2199 << (int)Constructor->isImplicit()
2200 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2201 << 0 << Field->getDeclName();
2202 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2203 return true;
2204 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002205
Sean Hunt1f2f3842011-05-17 00:19:05 +00002206 if (FieldBaseElementType.isConstQualified()) {
2207 SemaRef.Diag(Constructor->getLocation(),
2208 diag::err_uninitialized_member_in_ctor)
2209 << (int)Constructor->isImplicit()
2210 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2211 << 1 << Field->getDeclName();
2212 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2213 return true;
2214 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002215 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002216
John McCallf85e1932011-06-15 23:02:42 +00002217 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2218 FieldBaseElementType->isObjCRetainableType() &&
2219 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2220 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2221 // Instant objects:
2222 // Default-initialize Objective-C pointers to NULL.
2223 CXXMemberInit
2224 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2225 Loc, Loc,
2226 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2227 Loc);
2228 return false;
2229 }
2230
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002231 // Nothing to initialize.
2232 CXXMemberInit = 0;
2233 return false;
2234}
John McCallf1860e52010-05-20 23:23:51 +00002235
2236namespace {
2237struct BaseAndFieldInfo {
2238 Sema &S;
2239 CXXConstructorDecl *Ctor;
2240 bool AnyErrorsInInits;
2241 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002242 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002243 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002244
2245 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2246 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002247 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2248 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002249 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002250 else if (Generated && Ctor->isMoveConstructor())
2251 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002252 else
2253 IIK = IIK_Default;
2254 }
2255};
2256}
2257
Richard Smith7a614d82011-06-11 17:19:42 +00002258static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002259 FieldDecl *Field,
2260 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002261
Chandler Carruthe861c602010-06-30 02:59:29 +00002262 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002263 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002264 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002265 return false;
2266 }
2267
Richard Smith7a614d82011-06-11 17:19:42 +00002268 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2269 // has a brace-or-equal-initializer, the entity is initialized as specified
2270 // in [dcl.init].
2271 if (Field->hasInClassInitializer()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002272 CXXCtorInitializer *Init;
2273 if (Indirect)
2274 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2275 SourceLocation(),
2276 SourceLocation(), 0,
2277 SourceLocation());
2278 else
2279 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2280 SourceLocation(),
2281 SourceLocation(), 0,
2282 SourceLocation());
2283 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002284 return false;
2285 }
2286
John McCallf1860e52010-05-20 23:23:51 +00002287 // Don't try to build an implicit initializer if there were semantic
2288 // errors in any of the initializers (and therefore we might be
2289 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002290 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002291 return false;
2292
Sean Huntcbb67482011-01-08 20:30:50 +00002293 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002294 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2295 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002296 return true;
John McCallf1860e52010-05-20 23:23:51 +00002297
Francois Pichet00eb3f92010-12-04 09:14:42 +00002298 if (Init)
2299 Info.AllToInit.push_back(Init);
2300
John McCallf1860e52010-05-20 23:23:51 +00002301 return false;
2302}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002303
2304bool
2305Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2306 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002307 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002308 Constructor->setNumCtorInitializers(1);
2309 CXXCtorInitializer **initializer =
2310 new (Context) CXXCtorInitializer*[1];
2311 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2312 Constructor->setCtorInitializers(initializer);
2313
Sean Huntb76af9c2011-05-03 23:05:34 +00002314 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2315 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2316 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2317 }
2318
Sean Huntc1598702011-05-05 00:05:47 +00002319 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002320
Sean Hunt059ce0d2011-05-01 07:04:31 +00002321 return false;
2322}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002323
2324/// \brief Determine whether the given indirect field declaration is somewhere
2325/// within an anonymous union.
2326static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2327 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2328 CEnd = F->chain_end();
2329 C != CEnd; ++C)
2330 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2331 if (Record->isUnion())
2332 return true;
2333
2334 return false;
2335}
2336
John McCallb77115d2011-06-17 00:18:42 +00002337bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2338 CXXCtorInitializer **Initializers,
2339 unsigned NumInitializers,
2340 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002341 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002342 // Just store the initializers as written, they will be checked during
2343 // instantiation.
2344 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002345 Constructor->setNumCtorInitializers(NumInitializers);
2346 CXXCtorInitializer **baseOrMemberInitializers =
2347 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002348 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002349 NumInitializers * sizeof(CXXCtorInitializer*));
2350 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002351 }
2352
2353 return false;
2354 }
2355
John McCallf1860e52010-05-20 23:23:51 +00002356 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002357
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002358 // We need to build the initializer AST according to order of construction
2359 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002360 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002361 if (!ClassDecl)
2362 return true;
2363
Eli Friedman80c30da2009-11-09 19:20:36 +00002364 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002366 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002367 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002368
2369 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002370 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002371 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002372 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002373 }
2374
Anders Carlsson711f34a2010-04-21 19:52:01 +00002375 // Keep track of the direct virtual bases.
2376 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2377 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2378 E = ClassDecl->bases_end(); I != E; ++I) {
2379 if (I->isVirtual())
2380 DirectVBases.insert(I);
2381 }
2382
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002383 // Push virtual bases before others.
2384 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2385 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2386
Sean Huntcbb67482011-01-08 20:30:50 +00002387 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002388 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2389 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002390 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002391 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002392 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002393 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002394 VBase, IsInheritedVirtualBase,
2395 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002396 HadError = true;
2397 continue;
2398 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002399
John McCallf1860e52010-05-20 23:23:51 +00002400 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002401 }
2402 }
Mike Stump1eb44332009-09-09 15:08:12 +00002403
John McCallf1860e52010-05-20 23:23:51 +00002404 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002405 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2406 E = ClassDecl->bases_end(); Base != E; ++Base) {
2407 // Virtuals are in the virtual base list and already constructed.
2408 if (Base->isVirtual())
2409 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002410
Sean Huntcbb67482011-01-08 20:30:50 +00002411 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002412 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2413 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002414 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002415 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002416 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002417 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002418 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002419 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002420 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002421 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002422
John McCallf1860e52010-05-20 23:23:51 +00002423 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002424 }
2425 }
Mike Stump1eb44332009-09-09 15:08:12 +00002426
John McCallf1860e52010-05-20 23:23:51 +00002427 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002428 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2429 MemEnd = ClassDecl->decls_end();
2430 Mem != MemEnd; ++Mem) {
2431 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2432 if (F->getType()->isIncompleteArrayType()) {
2433 assert(ClassDecl->hasFlexibleArrayMember() &&
2434 "Incomplete array type is not valid");
2435 continue;
2436 }
2437
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002438 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002439 // handle anonymous struct/union fields based on their individual
2440 // indirect fields.
2441 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2442 continue;
2443
2444 if (CollectFieldInitializer(*this, Info, F))
2445 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002446 continue;
2447 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002448
2449 // Beyond this point, we only consider default initialization.
2450 if (Info.IIK != IIK_Default)
2451 continue;
2452
2453 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2454 if (F->getType()->isIncompleteArrayType()) {
2455 assert(ClassDecl->hasFlexibleArrayMember() &&
2456 "Incomplete array type is not valid");
2457 continue;
2458 }
2459
2460 // If this field is somewhere within an anonymous union, we only
2461 // initialize it if there's an explicit initializer.
2462 if (isWithinAnonymousUnion(F)) {
2463 if (CXXCtorInitializer *Init
2464 = Info.AllBaseFields.lookup(F->getAnonField())) {
2465 Info.AllToInit.push_back(Init);
2466 }
2467
2468 continue;
2469 }
2470
2471 // Initialize each field of an anonymous struct individually.
2472 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2473 HadError = true;
2474
2475 continue;
2476 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002477 }
Mike Stump1eb44332009-09-09 15:08:12 +00002478
John McCallf1860e52010-05-20 23:23:51 +00002479 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002480 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002481 Constructor->setNumCtorInitializers(NumInitializers);
2482 CXXCtorInitializer **baseOrMemberInitializers =
2483 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002484 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002485 NumInitializers * sizeof(CXXCtorInitializer*));
2486 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002487
John McCallef027fe2010-03-16 21:39:52 +00002488 // Constructors implicitly reference the base and member
2489 // destructors.
2490 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2491 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002492 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002493
2494 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002495}
2496
Eli Friedman6347f422009-07-21 19:28:10 +00002497static void *GetKeyForTopLevelField(FieldDecl *Field) {
2498 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002499 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002500 if (RT->getDecl()->isAnonymousStructOrUnion())
2501 return static_cast<void *>(RT->getDecl());
2502 }
2503 return static_cast<void *>(Field);
2504}
2505
Anders Carlssonea356fb2010-04-02 05:42:15 +00002506static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002507 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002508}
2509
Anders Carlssonea356fb2010-04-02 05:42:15 +00002510static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002511 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002512 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002513 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002514
Eli Friedman6347f422009-07-21 19:28:10 +00002515 // For fields injected into the class via declaration of an anonymous union,
2516 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002517 FieldDecl *Field = Member->getAnyMember();
2518
John McCall3c3ccdb2010-04-10 09:28:51 +00002519 // If the field is a member of an anonymous struct or union, our key
2520 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002521 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002522 if (RD->isAnonymousStructOrUnion()) {
2523 while (true) {
2524 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2525 if (Parent->isAnonymousStructOrUnion())
2526 RD = Parent;
2527 else
2528 break;
2529 }
2530
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002531 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002532 }
Mike Stump1eb44332009-09-09 15:08:12 +00002533
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002534 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002535}
2536
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002537static void
2538DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002539 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002540 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002541 unsigned NumInits) {
2542 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002543 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002544
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002545 // Don't check initializers order unless the warning is enabled at the
2546 // location of at least one initializer.
2547 bool ShouldCheckOrder = false;
2548 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002549 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002550 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2551 Init->getSourceLocation())
2552 != Diagnostic::Ignored) {
2553 ShouldCheckOrder = true;
2554 break;
2555 }
2556 }
2557 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002558 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002559
John McCalld6ca8da2010-04-10 07:37:23 +00002560 // Build the list of bases and members in the order that they'll
2561 // actually be initialized. The explicit initializers should be in
2562 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002563 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002564
Anders Carlsson071d6102010-04-02 03:38:04 +00002565 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2566
John McCalld6ca8da2010-04-10 07:37:23 +00002567 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002568 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002569 ClassDecl->vbases_begin(),
2570 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002571 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002572
John McCalld6ca8da2010-04-10 07:37:23 +00002573 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002574 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002575 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002576 if (Base->isVirtual())
2577 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002578 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002579 }
Mike Stump1eb44332009-09-09 15:08:12 +00002580
John McCalld6ca8da2010-04-10 07:37:23 +00002581 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002582 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2583 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002584 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002585
John McCalld6ca8da2010-04-10 07:37:23 +00002586 unsigned NumIdealInits = IdealInitKeys.size();
2587 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002588
Sean Huntcbb67482011-01-08 20:30:50 +00002589 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002590 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002591 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002592 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002593
2594 // Scan forward to try to find this initializer in the idealized
2595 // initializers list.
2596 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2597 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002598 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002599
2600 // If we didn't find this initializer, it must be because we
2601 // scanned past it on a previous iteration. That can only
2602 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002603 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002604 Sema::SemaDiagnosticBuilder D =
2605 SemaRef.Diag(PrevInit->getSourceLocation(),
2606 diag::warn_initializer_out_of_order);
2607
Francois Pichet00eb3f92010-12-04 09:14:42 +00002608 if (PrevInit->isAnyMemberInitializer())
2609 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002610 else
2611 D << 1 << PrevInit->getBaseClassInfo()->getType();
2612
Francois Pichet00eb3f92010-12-04 09:14:42 +00002613 if (Init->isAnyMemberInitializer())
2614 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002615 else
2616 D << 1 << Init->getBaseClassInfo()->getType();
2617
2618 // Move back to the initializer's location in the ideal list.
2619 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2620 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002621 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002622
2623 assert(IdealIndex != NumIdealInits &&
2624 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002625 }
John McCalld6ca8da2010-04-10 07:37:23 +00002626
2627 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002628 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002629}
2630
John McCall3c3ccdb2010-04-10 09:28:51 +00002631namespace {
2632bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002633 CXXCtorInitializer *Init,
2634 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002635 if (!PrevInit) {
2636 PrevInit = Init;
2637 return false;
2638 }
2639
2640 if (FieldDecl *Field = Init->getMember())
2641 S.Diag(Init->getSourceLocation(),
2642 diag::err_multiple_mem_initialization)
2643 << Field->getDeclName()
2644 << Init->getSourceRange();
2645 else {
John McCallf4c73712011-01-19 06:33:43 +00002646 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002647 assert(BaseClass && "neither field nor base");
2648 S.Diag(Init->getSourceLocation(),
2649 diag::err_multiple_base_initialization)
2650 << QualType(BaseClass, 0)
2651 << Init->getSourceRange();
2652 }
2653 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2654 << 0 << PrevInit->getSourceRange();
2655
2656 return true;
2657}
2658
Sean Huntcbb67482011-01-08 20:30:50 +00002659typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002660typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2661
2662bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002663 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002664 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002665 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002666 RecordDecl *Parent = Field->getParent();
2667 if (!Parent->isAnonymousStructOrUnion())
2668 return false;
2669
2670 NamedDecl *Child = Field;
2671 do {
2672 if (Parent->isUnion()) {
2673 UnionEntry &En = Unions[Parent];
2674 if (En.first && En.first != Child) {
2675 S.Diag(Init->getSourceLocation(),
2676 diag::err_multiple_mem_union_initialization)
2677 << Field->getDeclName()
2678 << Init->getSourceRange();
2679 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2680 << 0 << En.second->getSourceRange();
2681 return true;
2682 } else if (!En.first) {
2683 En.first = Child;
2684 En.second = Init;
2685 }
2686 }
2687
2688 Child = Parent;
2689 Parent = cast<RecordDecl>(Parent->getDeclContext());
2690 } while (Parent->isAnonymousStructOrUnion());
2691
2692 return false;
2693}
2694}
2695
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002696/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002697void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002698 SourceLocation ColonLoc,
2699 MemInitTy **meminits, unsigned NumMemInits,
2700 bool AnyErrors) {
2701 if (!ConstructorDecl)
2702 return;
2703
2704 AdjustDeclIfTemplate(ConstructorDecl);
2705
2706 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002707 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002708
2709 if (!Constructor) {
2710 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2711 return;
2712 }
2713
Sean Huntcbb67482011-01-08 20:30:50 +00002714 CXXCtorInitializer **MemInits =
2715 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002716
2717 // Mapping for the duplicate initializers check.
2718 // For member initializers, this is keyed with a FieldDecl*.
2719 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002720 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002721
2722 // Mapping for the inconsistent anonymous-union initializers check.
2723 RedundantUnionMap MemberUnions;
2724
Anders Carlssonea356fb2010-04-02 05:42:15 +00002725 bool HadError = false;
2726 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002727 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002728
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002729 // Set the source order index.
2730 Init->setSourceOrder(i);
2731
Francois Pichet00eb3f92010-12-04 09:14:42 +00002732 if (Init->isAnyMemberInitializer()) {
2733 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002734 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2735 CheckRedundantUnionInit(*this, Init, MemberUnions))
2736 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002737 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002738 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2739 if (CheckRedundantInit(*this, Init, Members[Key]))
2740 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002741 } else {
2742 assert(Init->isDelegatingInitializer());
2743 // This must be the only initializer
2744 if (i != 0 || NumMemInits > 1) {
2745 Diag(MemInits[0]->getSourceLocation(),
2746 diag::err_delegating_initializer_alone)
2747 << MemInits[0]->getSourceRange();
2748 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002749 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002750 }
Sean Huntfe57eef2011-05-04 05:57:24 +00002751 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00002752 // Return immediately as the initializer is set.
2753 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002754 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002755 }
2756
Anders Carlssonea356fb2010-04-02 05:42:15 +00002757 if (HadError)
2758 return;
2759
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002760 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002761
Sean Huntcbb67482011-01-08 20:30:50 +00002762 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002763}
2764
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002765void
John McCallef027fe2010-03-16 21:39:52 +00002766Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2767 CXXRecordDecl *ClassDecl) {
2768 // Ignore dependent contexts.
2769 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002770 return;
John McCall58e6f342010-03-16 05:22:47 +00002771
2772 // FIXME: all the access-control diagnostics are positioned on the
2773 // field/base declaration. That's probably good; that said, the
2774 // user might reasonably want to know why the destructor is being
2775 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002776
Anders Carlsson9f853df2009-11-17 04:44:12 +00002777 // Non-static data members.
2778 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2779 E = ClassDecl->field_end(); I != E; ++I) {
2780 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002781 if (Field->isInvalidDecl())
2782 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002783 QualType FieldType = Context.getBaseElementType(Field->getType());
2784
2785 const RecordType* RT = FieldType->getAs<RecordType>();
2786 if (!RT)
2787 continue;
2788
2789 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002790 if (FieldClassDecl->isInvalidDecl())
2791 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002792 if (FieldClassDecl->hasTrivialDestructor())
2793 continue;
2794
Douglas Gregordb89f282010-07-01 22:47:18 +00002795 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002796 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002797 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002798 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002799 << Field->getDeclName()
2800 << FieldType);
2801
John McCallef027fe2010-03-16 21:39:52 +00002802 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002803 }
2804
John McCall58e6f342010-03-16 05:22:47 +00002805 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2806
Anders Carlsson9f853df2009-11-17 04:44:12 +00002807 // Bases.
2808 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2809 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002810 // Bases are always records in a well-formed non-dependent class.
2811 const RecordType *RT = Base->getType()->getAs<RecordType>();
2812
2813 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002814 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002815 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002816
John McCall58e6f342010-03-16 05:22:47 +00002817 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002818 // If our base class is invalid, we probably can't get its dtor anyway.
2819 if (BaseClassDecl->isInvalidDecl())
2820 continue;
2821 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002822 if (BaseClassDecl->hasTrivialDestructor())
2823 continue;
John McCall58e6f342010-03-16 05:22:47 +00002824
Douglas Gregordb89f282010-07-01 22:47:18 +00002825 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002826 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002827
2828 // FIXME: caret should be on the start of the class name
2829 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002830 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002831 << Base->getType()
2832 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002833
John McCallef027fe2010-03-16 21:39:52 +00002834 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002835 }
2836
2837 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002838 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2839 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002840
2841 // Bases are always records in a well-formed non-dependent class.
2842 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2843
2844 // Ignore direct virtual bases.
2845 if (DirectVirtualBases.count(RT))
2846 continue;
2847
John McCall58e6f342010-03-16 05:22:47 +00002848 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002849 // If our base class is invalid, we probably can't get its dtor anyway.
2850 if (BaseClassDecl->isInvalidDecl())
2851 continue;
2852 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002853 if (BaseClassDecl->hasTrivialDestructor())
2854 continue;
John McCall58e6f342010-03-16 05:22:47 +00002855
Douglas Gregordb89f282010-07-01 22:47:18 +00002856 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002857 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002858 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002859 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002860 << VBase->getType());
2861
John McCallef027fe2010-03-16 21:39:52 +00002862 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002863 }
2864}
2865
John McCalld226f652010-08-21 09:40:31 +00002866void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002867 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002868 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002869
Mike Stump1eb44332009-09-09 15:08:12 +00002870 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002871 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002872 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002873}
2874
Mike Stump1eb44332009-09-09 15:08:12 +00002875bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002876 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002877 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002878 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002879 else
John McCall94c3b562010-08-18 09:41:07 +00002880 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002881}
2882
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002883bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002884 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002885 if (!getLangOptions().CPlusPlus)
2886 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002887
Anders Carlsson11f21a02009-03-23 19:10:31 +00002888 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002889 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002890
Ted Kremenek6217b802009-07-29 21:53:49 +00002891 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002892 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002893 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002894 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002895
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002896 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002897 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002898 }
Mike Stump1eb44332009-09-09 15:08:12 +00002899
Ted Kremenek6217b802009-07-29 21:53:49 +00002900 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002901 if (!RT)
2902 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002903
John McCall86ff3082010-02-04 22:26:26 +00002904 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002905
John McCall94c3b562010-08-18 09:41:07 +00002906 // We can't answer whether something is abstract until it has a
2907 // definition. If it's currently being defined, we'll walk back
2908 // over all the declarations when we have a full definition.
2909 const CXXRecordDecl *Def = RD->getDefinition();
2910 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002911 return false;
2912
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002913 if (!RD->isAbstract())
2914 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002915
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002916 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002917 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002918
John McCall94c3b562010-08-18 09:41:07 +00002919 return true;
2920}
2921
2922void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2923 // Check if we've already emitted the list of pure virtual functions
2924 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002925 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002926 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002927
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002928 CXXFinalOverriderMap FinalOverriders;
2929 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002930
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002931 // Keep a set of seen pure methods so we won't diagnose the same method
2932 // more than once.
2933 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2934
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002935 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2936 MEnd = FinalOverriders.end();
2937 M != MEnd;
2938 ++M) {
2939 for (OverridingMethods::iterator SO = M->second.begin(),
2940 SOEnd = M->second.end();
2941 SO != SOEnd; ++SO) {
2942 // C++ [class.abstract]p4:
2943 // A class is abstract if it contains or inherits at least one
2944 // pure virtual function for which the final overrider is pure
2945 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002946
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002947 //
2948 if (SO->second.size() != 1)
2949 continue;
2950
2951 if (!SO->second.front().Method->isPure())
2952 continue;
2953
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002954 if (!SeenPureMethods.insert(SO->second.front().Method))
2955 continue;
2956
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002957 Diag(SO->second.front().Method->getLocation(),
2958 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002959 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002960 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002961 }
2962
2963 if (!PureVirtualClassDiagSet)
2964 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2965 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002966}
2967
Anders Carlsson8211eff2009-03-24 01:19:16 +00002968namespace {
John McCall94c3b562010-08-18 09:41:07 +00002969struct AbstractUsageInfo {
2970 Sema &S;
2971 CXXRecordDecl *Record;
2972 CanQualType AbstractType;
2973 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002974
John McCall94c3b562010-08-18 09:41:07 +00002975 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2976 : S(S), Record(Record),
2977 AbstractType(S.Context.getCanonicalType(
2978 S.Context.getTypeDeclType(Record))),
2979 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002980
John McCall94c3b562010-08-18 09:41:07 +00002981 void DiagnoseAbstractType() {
2982 if (Invalid) return;
2983 S.DiagnoseAbstractType(Record);
2984 Invalid = true;
2985 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002986
John McCall94c3b562010-08-18 09:41:07 +00002987 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2988};
2989
2990struct CheckAbstractUsage {
2991 AbstractUsageInfo &Info;
2992 const NamedDecl *Ctx;
2993
2994 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2995 : Info(Info), Ctx(Ctx) {}
2996
2997 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2998 switch (TL.getTypeLocClass()) {
2999#define ABSTRACT_TYPELOC(CLASS, PARENT)
3000#define TYPELOC(CLASS, PARENT) \
3001 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3002#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003003 }
John McCall94c3b562010-08-18 09:41:07 +00003004 }
Mike Stump1eb44332009-09-09 15:08:12 +00003005
John McCall94c3b562010-08-18 09:41:07 +00003006 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3007 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3008 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003009 if (!TL.getArg(I))
3010 continue;
3011
John McCall94c3b562010-08-18 09:41:07 +00003012 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3013 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003014 }
John McCall94c3b562010-08-18 09:41:07 +00003015 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003016
John McCall94c3b562010-08-18 09:41:07 +00003017 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3018 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3019 }
Mike Stump1eb44332009-09-09 15:08:12 +00003020
John McCall94c3b562010-08-18 09:41:07 +00003021 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3022 // Visit the type parameters from a permissive context.
3023 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3024 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3025 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3026 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3027 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3028 // TODO: other template argument types?
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 // Visit pointee types from a permissive context.
3033#define CheckPolymorphic(Type) \
3034 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3035 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3036 }
3037 CheckPolymorphic(PointerTypeLoc)
3038 CheckPolymorphic(ReferenceTypeLoc)
3039 CheckPolymorphic(MemberPointerTypeLoc)
3040 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003041
John McCall94c3b562010-08-18 09:41:07 +00003042 /// Handle all the types we haven't given a more specific
3043 /// implementation for above.
3044 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3045 // Every other kind of type that we haven't called out already
3046 // that has an inner type is either (1) sugar or (2) contains that
3047 // inner type in some way as a subobject.
3048 if (TypeLoc Next = TL.getNextTypeLoc())
3049 return Visit(Next, Sel);
3050
3051 // If there's no inner type and we're in a permissive context,
3052 // don't diagnose.
3053 if (Sel == Sema::AbstractNone) return;
3054
3055 // Check whether the type matches the abstract type.
3056 QualType T = TL.getType();
3057 if (T->isArrayType()) {
3058 Sel = Sema::AbstractArrayType;
3059 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003060 }
John McCall94c3b562010-08-18 09:41:07 +00003061 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3062 if (CT != Info.AbstractType) return;
3063
3064 // It matched; do some magic.
3065 if (Sel == Sema::AbstractArrayType) {
3066 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3067 << T << TL.getSourceRange();
3068 } else {
3069 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3070 << Sel << T << TL.getSourceRange();
3071 }
3072 Info.DiagnoseAbstractType();
3073 }
3074};
3075
3076void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3077 Sema::AbstractDiagSelID Sel) {
3078 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3079}
3080
3081}
3082
3083/// Check for invalid uses of an abstract type in a method declaration.
3084static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3085 CXXMethodDecl *MD) {
3086 // No need to do the check on definitions, which require that
3087 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003088 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003089 return;
3090
3091 // For safety's sake, just ignore it if we don't have type source
3092 // information. This should never happen for non-implicit methods,
3093 // but...
3094 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3095 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3096}
3097
3098/// Check for invalid uses of an abstract type within a class definition.
3099static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3100 CXXRecordDecl *RD) {
3101 for (CXXRecordDecl::decl_iterator
3102 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3103 Decl *D = *I;
3104 if (D->isImplicit()) continue;
3105
3106 // Methods and method templates.
3107 if (isa<CXXMethodDecl>(D)) {
3108 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3109 } else if (isa<FunctionTemplateDecl>(D)) {
3110 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3111 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3112
3113 // Fields and static variables.
3114 } else if (isa<FieldDecl>(D)) {
3115 FieldDecl *FD = cast<FieldDecl>(D);
3116 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3117 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3118 } else if (isa<VarDecl>(D)) {
3119 VarDecl *VD = cast<VarDecl>(D);
3120 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3121 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3122
3123 // Nested classes and class templates.
3124 } else if (isa<CXXRecordDecl>(D)) {
3125 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3126 } else if (isa<ClassTemplateDecl>(D)) {
3127 CheckAbstractClassUsage(Info,
3128 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3129 }
3130 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003131}
3132
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003133/// \brief Perform semantic checks on a class definition that has been
3134/// completing, introducing implicitly-declared members, checking for
3135/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003136void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003137 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003138 return;
3139
John McCall94c3b562010-08-18 09:41:07 +00003140 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3141 AbstractUsageInfo Info(*this, Record);
3142 CheckAbstractClassUsage(Info, Record);
3143 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003144
3145 // If this is not an aggregate type and has no user-declared constructor,
3146 // complain about any non-static data members of reference or const scalar
3147 // type, since they will never get initializers.
3148 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3149 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3150 bool Complained = false;
3151 for (RecordDecl::field_iterator F = Record->field_begin(),
3152 FEnd = Record->field_end();
3153 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00003154 if (F->hasInClassInitializer())
3155 continue;
3156
Douglas Gregor325e5932010-04-15 00:00:53 +00003157 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003158 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003159 if (!Complained) {
3160 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3161 << Record->getTagKind() << Record;
3162 Complained = true;
3163 }
3164
3165 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3166 << F->getType()->isReferenceType()
3167 << F->getDeclName();
3168 }
3169 }
3170 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003171
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003172 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003173 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003174
3175 if (Record->getIdentifier()) {
3176 // C++ [class.mem]p13:
3177 // If T is the name of a class, then each of the following shall have a
3178 // name different from T:
3179 // - every member of every anonymous union that is a member of class T.
3180 //
3181 // C++ [class.mem]p14:
3182 // In addition, if class T has a user-declared constructor (12.1), every
3183 // non-static data member of class T shall have a name different from T.
3184 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003185 R.first != R.second; ++R.first) {
3186 NamedDecl *D = *R.first;
3187 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3188 isa<IndirectFieldDecl>(D)) {
3189 Diag(D->getLocation(), diag::err_member_name_of_class)
3190 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003191 break;
3192 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003193 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003194 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003195
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003196 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003197 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003198 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003199 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003200 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3201 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3202 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003203
3204 // See if a method overloads virtual methods in a base
3205 /// class without overriding any.
3206 if (!Record->isDependentType()) {
3207 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3208 MEnd = Record->method_end();
3209 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003210 if (!(*M)->isStatic())
3211 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003212 }
3213 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003214
3215 // Declare inherited constructors. We do this eagerly here because:
3216 // - The standard requires an eager diagnostic for conflicting inherited
3217 // constructors from different classes.
3218 // - The lazy declaration of the other implicit constructors is so as to not
3219 // waste space and performance on classes that are not meant to be
3220 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3221 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003222 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003223
Sean Hunteb88ae52011-05-23 21:07:59 +00003224 if (!Record->isDependentType())
3225 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003226}
3227
3228void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003229 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3230 ME = Record->method_end();
3231 MI != ME; ++MI) {
3232 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3233 switch (getSpecialMember(*MI)) {
3234 case CXXDefaultConstructor:
3235 CheckExplicitlyDefaultedDefaultConstructor(
3236 cast<CXXConstructorDecl>(*MI));
3237 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003238
Sean Huntcb45a0f2011-05-12 22:46:25 +00003239 case CXXDestructor:
3240 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3241 break;
3242
3243 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003244 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3245 break;
3246
Sean Huntcb45a0f2011-05-12 22:46:25 +00003247 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003248 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003249 break;
3250
Sean Hunt82713172011-05-25 23:16:36 +00003251 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003252 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003253 break;
3254
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003255 case CXXMoveAssignment:
3256 CheckExplicitlyDefaultedMoveAssignment(*MI);
3257 break;
3258
3259 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003260 llvm_unreachable("non-special member explicitly defaulted!");
3261 }
Sean Hunt001cad92011-05-10 00:49:42 +00003262 }
3263 }
3264
Sean Hunt001cad92011-05-10 00:49:42 +00003265}
3266
3267void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3268 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3269
3270 // Whether this was the first-declared instance of the constructor.
3271 // This affects whether we implicitly add an exception spec (and, eventually,
3272 // constexpr). It is also ill-formed to explicitly default a constructor such
3273 // that it would be deleted. (C++0x [decl.fct.def.default])
3274 bool First = CD == CD->getCanonicalDecl();
3275
Sean Hunt49634cf2011-05-13 06:10:58 +00003276 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003277 if (CD->getNumParams() != 0) {
3278 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3279 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003280 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003281 }
3282
3283 ImplicitExceptionSpecification Spec
3284 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3285 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003286 if (EPI.ExceptionSpecType == EST_Delayed) {
3287 // Exception specification depends on some deferred part of the class. We'll
3288 // try again when the class's definition has been fully processed.
3289 return;
3290 }
Sean Hunt001cad92011-05-10 00:49:42 +00003291 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3292 *ExceptionType = Context.getFunctionType(
3293 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3294
3295 if (CtorType->hasExceptionSpec()) {
3296 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003297 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003298 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003299 PDiag(),
3300 ExceptionType, SourceLocation(),
3301 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003302 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003303 }
3304 } else if (First) {
3305 // We set the declaration to have the computed exception spec here.
3306 // We know there are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003307 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003308 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3309 }
Sean Huntca46d132011-05-12 03:51:48 +00003310
Sean Hunt49634cf2011-05-13 06:10:58 +00003311 if (HadError) {
3312 CD->setInvalidDecl();
3313 return;
3314 }
3315
Sean Huntca46d132011-05-12 03:51:48 +00003316 if (ShouldDeleteDefaultConstructor(CD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003317 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003318 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003319 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003320 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003321 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003322 CD->setInvalidDecl();
3323 }
3324 }
3325}
3326
3327void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3328 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3329
3330 // Whether this was the first-declared instance of the constructor.
3331 bool First = CD == CD->getCanonicalDecl();
3332
3333 bool HadError = false;
3334 if (CD->getNumParams() != 1) {
3335 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3336 << CD->getSourceRange();
3337 HadError = true;
3338 }
3339
3340 ImplicitExceptionSpecification Spec(Context);
3341 bool Const;
3342 llvm::tie(Spec, Const) =
3343 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3344
3345 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3346 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3347 *ExceptionType = Context.getFunctionType(
3348 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3349
3350 // Check for parameter type matching.
3351 // This is a copy ctor so we know it's a cv-qualified reference to T.
3352 QualType ArgType = CtorType->getArgType(0);
3353 if (ArgType->getPointeeType().isVolatileQualified()) {
3354 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3355 HadError = true;
3356 }
3357 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3358 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3359 HadError = true;
3360 }
3361
3362 if (CtorType->hasExceptionSpec()) {
3363 if (CheckEquivalentExceptionSpec(
3364 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003365 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003366 PDiag(),
3367 ExceptionType, SourceLocation(),
3368 CtorType, CD->getLocation())) {
3369 HadError = true;
3370 }
3371 } else if (First) {
3372 // We set the declaration to have the computed exception spec here.
3373 // We duplicate the one parameter type.
Sean Hunt2b188082011-05-14 05:23:28 +00003374 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt49634cf2011-05-13 06:10:58 +00003375 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3376 }
3377
3378 if (HadError) {
3379 CD->setInvalidDecl();
3380 return;
3381 }
3382
3383 if (ShouldDeleteCopyConstructor(CD)) {
3384 if (First) {
3385 CD->setDeletedAsWritten();
3386 } else {
3387 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003388 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003389 CD->setInvalidDecl();
3390 }
Sean Huntca46d132011-05-12 03:51:48 +00003391 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003392}
Sean Hunt001cad92011-05-10 00:49:42 +00003393
Sean Hunt2b188082011-05-14 05:23:28 +00003394void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3395 assert(MD->isExplicitlyDefaulted());
3396
3397 // Whether this was the first-declared instance of the operator
3398 bool First = MD == MD->getCanonicalDecl();
3399
3400 bool HadError = false;
3401 if (MD->getNumParams() != 1) {
3402 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3403 << MD->getSourceRange();
3404 HadError = true;
3405 }
3406
3407 QualType ReturnType =
3408 MD->getType()->getAs<FunctionType>()->getResultType();
3409 if (!ReturnType->isLValueReferenceType() ||
3410 !Context.hasSameType(
3411 Context.getCanonicalType(ReturnType->getPointeeType()),
3412 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3413 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3414 HadError = true;
3415 }
3416
3417 ImplicitExceptionSpecification Spec(Context);
3418 bool Const;
3419 llvm::tie(Spec, Const) =
3420 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3421
3422 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3423 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3424 *ExceptionType = Context.getFunctionType(
3425 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3426
Sean Hunt2b188082011-05-14 05:23:28 +00003427 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003428 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00003429 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003430 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003431 } else {
3432 if (ArgType->getPointeeType().isVolatileQualified()) {
3433 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3434 HadError = true;
3435 }
3436 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3437 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3438 HadError = true;
3439 }
Sean Hunt2b188082011-05-14 05:23:28 +00003440 }
Sean Huntbe631222011-05-17 20:44:43 +00003441
Sean Hunt2b188082011-05-14 05:23:28 +00003442 if (OperType->getTypeQuals()) {
3443 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3444 HadError = true;
3445 }
3446
3447 if (OperType->hasExceptionSpec()) {
3448 if (CheckEquivalentExceptionSpec(
3449 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003450 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00003451 PDiag(),
3452 ExceptionType, SourceLocation(),
3453 OperType, MD->getLocation())) {
3454 HadError = true;
3455 }
3456 } else if (First) {
3457 // We set the declaration to have the computed exception spec here.
3458 // We duplicate the one parameter type.
3459 EPI.RefQualifier = OperType->getRefQualifier();
3460 EPI.ExtInfo = OperType->getExtInfo();
3461 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3462 }
3463
3464 if (HadError) {
3465 MD->setInvalidDecl();
3466 return;
3467 }
3468
3469 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3470 if (First) {
3471 MD->setDeletedAsWritten();
3472 } else {
3473 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003474 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00003475 MD->setInvalidDecl();
3476 }
3477 }
3478}
3479
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003480void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3481 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3482
3483 // Whether this was the first-declared instance of the constructor.
3484 bool First = CD == CD->getCanonicalDecl();
3485
3486 bool HadError = false;
3487 if (CD->getNumParams() != 1) {
3488 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3489 << CD->getSourceRange();
3490 HadError = true;
3491 }
3492
3493 ImplicitExceptionSpecification Spec(
3494 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3495
3496 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3497 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3498 *ExceptionType = Context.getFunctionType(
3499 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3500
3501 // Check for parameter type matching.
3502 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3503 QualType ArgType = CtorType->getArgType(0);
3504 if (ArgType->getPointeeType().isVolatileQualified()) {
3505 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3506 HadError = true;
3507 }
3508 if (ArgType->getPointeeType().isConstQualified()) {
3509 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3510 HadError = true;
3511 }
3512
3513 if (CtorType->hasExceptionSpec()) {
3514 if (CheckEquivalentExceptionSpec(
3515 PDiag(diag::err_incorrect_defaulted_exception_spec)
3516 << CXXMoveConstructor,
3517 PDiag(),
3518 ExceptionType, SourceLocation(),
3519 CtorType, CD->getLocation())) {
3520 HadError = true;
3521 }
3522 } else if (First) {
3523 // We set the declaration to have the computed exception spec here.
3524 // We duplicate the one parameter type.
3525 EPI.ExtInfo = CtorType->getExtInfo();
3526 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3527 }
3528
3529 if (HadError) {
3530 CD->setInvalidDecl();
3531 return;
3532 }
3533
3534 if (ShouldDeleteMoveConstructor(CD)) {
3535 if (First) {
3536 CD->setDeletedAsWritten();
3537 } else {
3538 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3539 << CXXMoveConstructor;
3540 CD->setInvalidDecl();
3541 }
3542 }
3543}
3544
3545void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3546 assert(MD->isExplicitlyDefaulted());
3547
3548 // Whether this was the first-declared instance of the operator
3549 bool First = MD == MD->getCanonicalDecl();
3550
3551 bool HadError = false;
3552 if (MD->getNumParams() != 1) {
3553 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3554 << MD->getSourceRange();
3555 HadError = true;
3556 }
3557
3558 QualType ReturnType =
3559 MD->getType()->getAs<FunctionType>()->getResultType();
3560 if (!ReturnType->isLValueReferenceType() ||
3561 !Context.hasSameType(
3562 Context.getCanonicalType(ReturnType->getPointeeType()),
3563 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3564 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
3565 HadError = true;
3566 }
3567
3568 ImplicitExceptionSpecification Spec(
3569 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
3570
3571 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3572 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3573 *ExceptionType = Context.getFunctionType(
3574 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3575
3576 QualType ArgType = OperType->getArgType(0);
3577 if (!ArgType->isRValueReferenceType()) {
3578 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
3579 HadError = true;
3580 } else {
3581 if (ArgType->getPointeeType().isVolatileQualified()) {
3582 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
3583 HadError = true;
3584 }
3585 if (ArgType->getPointeeType().isConstQualified()) {
3586 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
3587 HadError = true;
3588 }
3589 }
3590
3591 if (OperType->getTypeQuals()) {
3592 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
3593 HadError = true;
3594 }
3595
3596 if (OperType->hasExceptionSpec()) {
3597 if (CheckEquivalentExceptionSpec(
3598 PDiag(diag::err_incorrect_defaulted_exception_spec)
3599 << CXXMoveAssignment,
3600 PDiag(),
3601 ExceptionType, SourceLocation(),
3602 OperType, MD->getLocation())) {
3603 HadError = true;
3604 }
3605 } else if (First) {
3606 // We set the declaration to have the computed exception spec here.
3607 // We duplicate the one parameter type.
3608 EPI.RefQualifier = OperType->getRefQualifier();
3609 EPI.ExtInfo = OperType->getExtInfo();
3610 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3611 }
3612
3613 if (HadError) {
3614 MD->setInvalidDecl();
3615 return;
3616 }
3617
3618 if (ShouldDeleteMoveAssignmentOperator(MD)) {
3619 if (First) {
3620 MD->setDeletedAsWritten();
3621 } else {
3622 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3623 << CXXMoveAssignment;
3624 MD->setInvalidDecl();
3625 }
3626 }
3627}
3628
Sean Huntcb45a0f2011-05-12 22:46:25 +00003629void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3630 assert(DD->isExplicitlyDefaulted());
3631
3632 // Whether this was the first-declared instance of the destructor.
3633 bool First = DD == DD->getCanonicalDecl();
3634
3635 ImplicitExceptionSpecification Spec
3636 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3637 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3638 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3639 *ExceptionType = Context.getFunctionType(
3640 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3641
3642 if (DtorType->hasExceptionSpec()) {
3643 if (CheckEquivalentExceptionSpec(
3644 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003645 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00003646 PDiag(),
3647 ExceptionType, SourceLocation(),
3648 DtorType, DD->getLocation())) {
3649 DD->setInvalidDecl();
3650 return;
3651 }
3652 } else if (First) {
3653 // We set the declaration to have the computed exception spec here.
3654 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003655 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00003656 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3657 }
3658
3659 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003660 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003661 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003662 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003663 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003664 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003665 DD->setInvalidDecl();
3666 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003667 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003668}
3669
Sean Huntcdee3fe2011-05-11 22:34:38 +00003670bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3671 CXXRecordDecl *RD = CD->getParent();
3672 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003673 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003674 return false;
3675
Sean Hunt71a682f2011-05-18 03:41:58 +00003676 SourceLocation Loc = CD->getLocation();
3677
Sean Huntcdee3fe2011-05-11 22:34:38 +00003678 // Do access control from the constructor
3679 ContextRAII CtorContext(*this, CD);
3680
3681 bool Union = RD->isUnion();
3682 bool AllConst = true;
3683
Sean Huntcdee3fe2011-05-11 22:34:38 +00003684 // We do this because we should never actually use an anonymous
3685 // union's constructor.
3686 if (Union && RD->isAnonymousStructOrUnion())
3687 return false;
3688
3689 // FIXME: We should put some diagnostic logic right into this function.
3690
3691 // C++0x [class.ctor]/5
Sean Huntb320e0c2011-06-10 03:50:41 +00003692 // A defaulted default constructor for class X is defined as deleted if:
Sean Huntcdee3fe2011-05-11 22:34:38 +00003693
3694 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3695 BE = RD->bases_end();
3696 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003697 // We'll handle this one later
3698 if (BI->isVirtual())
3699 continue;
3700
Sean Huntcdee3fe2011-05-11 22:34:38 +00003701 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3702 assert(BaseDecl && "base isn't a CXXRecordDecl");
3703
3704 // -- any [direct base class] has a type with a destructor that is
Sean Huntb320e0c2011-06-10 03:50:41 +00003705 // deleted or inaccessible from the defaulted default constructor
Sean Huntcdee3fe2011-05-11 22:34:38 +00003706 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3707 if (BaseDtor->isDeleted())
3708 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003709 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003710 AR_accessible)
3711 return true;
3712
Sean Huntcdee3fe2011-05-11 22:34:38 +00003713 // -- any [direct base class either] has no default constructor or
3714 // overload resolution as applied to [its] default constructor
3715 // results in an ambiguity or in a function that is deleted or
3716 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003717 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3718 if (!BaseDefault || BaseDefault->isDeleted())
3719 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003720
Sean Huntb320e0c2011-06-10 03:50:41 +00003721 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3722 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003723 return true;
3724 }
3725
3726 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3727 BE = RD->vbases_end();
3728 BI != BE; ++BI) {
3729 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3730 assert(BaseDecl && "base isn't a CXXRecordDecl");
3731
3732 // -- any [virtual base class] has a type with a destructor that is
3733 // delete or inaccessible from the defaulted default constructor
3734 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3735 if (BaseDtor->isDeleted())
3736 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003737 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003738 AR_accessible)
3739 return true;
3740
3741 // -- any [virtual base class either] has no default constructor or
3742 // overload resolution as applied to [its] default constructor
3743 // results in an ambiguity or in a function that is deleted or
3744 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003745 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3746 if (!BaseDefault || BaseDefault->isDeleted())
3747 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003748
Sean Huntb320e0c2011-06-10 03:50:41 +00003749 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3750 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003751 return true;
3752 }
3753
3754 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3755 FE = RD->field_end();
3756 FI != FE; ++FI) {
Richard Smith7a614d82011-06-11 17:19:42 +00003757 if (FI->isInvalidDecl())
3758 continue;
3759
Sean Huntcdee3fe2011-05-11 22:34:38 +00003760 QualType FieldType = Context.getBaseElementType(FI->getType());
3761 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00003762
Sean Huntcdee3fe2011-05-11 22:34:38 +00003763 // -- any non-static data member with no brace-or-equal-initializer is of
3764 // reference type
Richard Smith7a614d82011-06-11 17:19:42 +00003765 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003766 return true;
3767
3768 // -- X is a union and all its variant members are of const-qualified type
3769 // (or array thereof)
3770 if (Union && !FieldType.isConstQualified())
3771 AllConst = false;
3772
3773 if (FieldRecord) {
3774 // -- X is a union-like class that has a variant member with a non-trivial
3775 // default constructor
3776 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3777 return true;
3778
3779 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3780 if (FieldDtor->isDeleted())
3781 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003782 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003783 AR_accessible)
3784 return true;
3785
3786 // -- any non-variant non-static data member of const-qualified type (or
3787 // array thereof) with no brace-or-equal-initializer does not have a
3788 // user-provided default constructor
3789 if (FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00003790 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00003791 !FieldRecord->hasUserProvidedDefaultConstructor())
3792 return true;
3793
3794 if (!Union && FieldRecord->isUnion() &&
3795 FieldRecord->isAnonymousStructOrUnion()) {
3796 // We're okay to reuse AllConst here since we only care about the
3797 // value otherwise if we're in a union.
3798 AllConst = true;
3799
3800 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3801 UE = FieldRecord->field_end();
3802 UI != UE; ++UI) {
3803 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3804 CXXRecordDecl *UnionFieldRecord =
3805 UnionFieldType->getAsCXXRecordDecl();
3806
3807 if (!UnionFieldType.isConstQualified())
3808 AllConst = false;
3809
3810 if (UnionFieldRecord &&
3811 !UnionFieldRecord->hasTrivialDefaultConstructor())
3812 return true;
3813 }
Sean Hunt2be7e902011-05-12 22:46:29 +00003814
Sean Huntcdee3fe2011-05-11 22:34:38 +00003815 if (AllConst)
3816 return true;
3817
3818 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00003819 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00003820 continue;
3821 }
Sean Huntb320e0c2011-06-10 03:50:41 +00003822
Richard Smith7a614d82011-06-11 17:19:42 +00003823 // -- any non-static data member with no brace-or-equal-initializer has
3824 // class type M (or array thereof) and either M has no default
3825 // constructor or overload resolution as applied to M's default
3826 // constructor results in an ambiguity or in a function that is deleted
3827 // or inaccessible from the defaulted default constructor.
3828 if (!FI->hasInClassInitializer()) {
3829 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3830 if (!FieldDefault || FieldDefault->isDeleted())
3831 return true;
3832 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3833 PDiag()) != AR_accessible)
3834 return true;
3835 }
3836 } else if (!Union && FieldType.isConstQualified() &&
3837 !FI->hasInClassInitializer()) {
Sean Hunte3406822011-05-20 21:43:47 +00003838 // -- any non-variant non-static data member of const-qualified type (or
3839 // array thereof) with no brace-or-equal-initializer does not have a
3840 // user-provided default constructor
3841 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003842 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003843 }
3844
3845 if (Union && AllConst)
3846 return true;
3847
3848 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003849}
3850
Sean Hunt49634cf2011-05-13 06:10:58 +00003851bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Sean Hunt493ff722011-05-18 20:57:13 +00003852 CXXRecordDecl *RD = CD->getParent();
Sean Hunt49634cf2011-05-13 06:10:58 +00003853 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003854 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt49634cf2011-05-13 06:10:58 +00003855 return false;
3856
Sean Hunt71a682f2011-05-18 03:41:58 +00003857 SourceLocation Loc = CD->getLocation();
3858
Sean Hunt49634cf2011-05-13 06:10:58 +00003859 // Do access control from the constructor
3860 ContextRAII CtorContext(*this, CD);
3861
Sean Huntc530d172011-06-10 04:44:37 +00003862 bool Union = RD->isUnion();
Sean Hunt49634cf2011-05-13 06:10:58 +00003863
Sean Hunt2b188082011-05-14 05:23:28 +00003864 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3865 "copy assignment arg has no pointee type");
Sean Huntc530d172011-06-10 04:44:37 +00003866 unsigned ArgQuals =
3867 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3868 Qualifiers::Const : 0;
Sean Hunt49634cf2011-05-13 06:10:58 +00003869
3870 // We do this because we should never actually use an anonymous
3871 // union's constructor.
3872 if (Union && RD->isAnonymousStructOrUnion())
3873 return false;
3874
3875 // FIXME: We should put some diagnostic logic right into this function.
3876
3877 // C++0x [class.copy]/11
3878 // A defaulted [copy] constructor for class X is defined as delete if X has:
3879
3880 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3881 BE = RD->bases_end();
3882 BI != BE; ++BI) {
3883 // We'll handle this one later
3884 if (BI->isVirtual())
3885 continue;
3886
3887 QualType BaseType = BI->getType();
3888 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3889 assert(BaseDecl && "base isn't a CXXRecordDecl");
3890
3891 // -- any [direct base class] of a type with a destructor that is deleted or
3892 // inaccessible from the defaulted constructor
3893 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3894 if (BaseDtor->isDeleted())
3895 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003896 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003897 AR_accessible)
3898 return true;
3899
3900 // -- a [direct base class] B that cannot be [copied] because overload
3901 // resolution, as applied to B's [copy] constructor, results in an
3902 // ambiguity or a function that is deleted or inaccessible from the
3903 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003904 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003905 if (!BaseCtor || BaseCtor->isDeleted())
3906 return true;
3907 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3908 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003909 return true;
3910 }
3911
3912 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3913 BE = RD->vbases_end();
3914 BI != BE; ++BI) {
3915 QualType BaseType = BI->getType();
3916 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3917 assert(BaseDecl && "base isn't a CXXRecordDecl");
3918
Sean Huntb320e0c2011-06-10 03:50:41 +00003919 // -- any [virtual base class] of a type with a destructor that is deleted or
Sean Hunt49634cf2011-05-13 06:10:58 +00003920 // inaccessible from the defaulted constructor
3921 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3922 if (BaseDtor->isDeleted())
3923 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003924 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003925 AR_accessible)
3926 return true;
3927
3928 // -- a [virtual base class] B that cannot be [copied] because overload
3929 // resolution, as applied to B's [copy] constructor, results in an
3930 // ambiguity or a function that is deleted or inaccessible from the
3931 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003932 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003933 if (!BaseCtor || BaseCtor->isDeleted())
3934 return true;
3935 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3936 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003937 return true;
3938 }
3939
3940 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3941 FE = RD->field_end();
3942 FI != FE; ++FI) {
3943 QualType FieldType = Context.getBaseElementType(FI->getType());
3944
3945 // -- for a copy constructor, a non-static data member of rvalue reference
3946 // type
3947 if (FieldType->isRValueReferenceType())
3948 return true;
3949
3950 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3951
3952 if (FieldRecord) {
3953 // This is an anonymous union
3954 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3955 // Anonymous unions inside unions do not variant members create
3956 if (!Union) {
3957 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3958 UE = FieldRecord->field_end();
3959 UI != UE; ++UI) {
3960 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3961 CXXRecordDecl *UnionFieldRecord =
3962 UnionFieldType->getAsCXXRecordDecl();
3963
3964 // -- a variant member with a non-trivial [copy] constructor and X
3965 // is a union-like class
3966 if (UnionFieldRecord &&
3967 !UnionFieldRecord->hasTrivialCopyConstructor())
3968 return true;
3969 }
3970 }
3971
3972 // Don't try to initalize an anonymous union
3973 continue;
3974 } else {
3975 // -- a variant member with a non-trivial [copy] constructor and X is a
3976 // union-like class
3977 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3978 return true;
3979
3980 // -- any [non-static data member] of a type with a destructor that is
3981 // deleted or inaccessible from the defaulted constructor
3982 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3983 if (FieldDtor->isDeleted())
3984 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003985 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003986 AR_accessible)
3987 return true;
3988 }
Sean Huntc530d172011-06-10 04:44:37 +00003989
3990 // -- a [non-static data member of class type (or array thereof)] B that
3991 // cannot be [copied] because overload resolution, as applied to B's
3992 // [copy] constructor, results in an ambiguity or a function that is
3993 // deleted or inaccessible from the defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003994 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
3995 ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003996 if (!FieldCtor || FieldCtor->isDeleted())
3997 return true;
3998 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3999 PDiag()) != AR_accessible)
4000 return true;
Sean Hunt49634cf2011-05-13 06:10:58 +00004001 }
Sean Hunt49634cf2011-05-13 06:10:58 +00004002 }
4003
4004 return false;
4005}
4006
Sean Hunt7f410192011-05-14 05:23:24 +00004007bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4008 CXXRecordDecl *RD = MD->getParent();
4009 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004010 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004011 return false;
4012
Sean Hunt71a682f2011-05-18 03:41:58 +00004013 SourceLocation Loc = MD->getLocation();
4014
Sean Hunt7f410192011-05-14 05:23:24 +00004015 // Do access control from the constructor
4016 ContextRAII MethodContext(*this, MD);
4017
4018 bool Union = RD->isUnion();
4019
Sean Hunt661c67a2011-06-21 23:42:56 +00004020 unsigned ArgQuals =
4021 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4022 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004023
4024 // We do this because we should never actually use an anonymous
4025 // union's constructor.
4026 if (Union && RD->isAnonymousStructOrUnion())
4027 return false;
4028
Sean Hunt7f410192011-05-14 05:23:24 +00004029 // FIXME: We should put some diagnostic logic right into this function.
4030
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004031 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004032 // A defaulted [copy] assignment operator for class X is defined as deleted
4033 // if X has:
4034
4035 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4036 BE = RD->bases_end();
4037 BI != BE; ++BI) {
4038 // We'll handle this one later
4039 if (BI->isVirtual())
4040 continue;
4041
4042 QualType BaseType = BI->getType();
4043 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4044 assert(BaseDecl && "base isn't a CXXRecordDecl");
4045
4046 // -- a [direct base class] B that cannot be [copied] because overload
4047 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004048 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004049 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004050 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4051 0);
4052 if (!CopyOper || CopyOper->isDeleted())
4053 return true;
4054 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004055 return true;
4056 }
4057
4058 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4059 BE = RD->vbases_end();
4060 BI != BE; ++BI) {
4061 QualType BaseType = BI->getType();
4062 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4063 assert(BaseDecl && "base isn't a CXXRecordDecl");
4064
Sean Hunt7f410192011-05-14 05:23:24 +00004065 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004066 // resolution, as applied to B's [copy] assignment operator, results in
4067 // an ambiguity or a function that is deleted or inaccessible from the
4068 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004069 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4070 0);
4071 if (!CopyOper || CopyOper->isDeleted())
4072 return true;
4073 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004074 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004075 }
4076
4077 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4078 FE = RD->field_end();
4079 FI != FE; ++FI) {
4080 QualType FieldType = Context.getBaseElementType(FI->getType());
4081
4082 // -- a non-static data member of reference type
4083 if (FieldType->isReferenceType())
4084 return true;
4085
4086 // -- a non-static data member of const non-class type (or array thereof)
4087 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4088 return true;
4089
4090 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4091
4092 if (FieldRecord) {
4093 // This is an anonymous union
4094 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4095 // Anonymous unions inside unions do not variant members create
4096 if (!Union) {
4097 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4098 UE = FieldRecord->field_end();
4099 UI != UE; ++UI) {
4100 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4101 CXXRecordDecl *UnionFieldRecord =
4102 UnionFieldType->getAsCXXRecordDecl();
4103
4104 // -- a variant member with a non-trivial [copy] assignment operator
4105 // and X is a union-like class
4106 if (UnionFieldRecord &&
4107 !UnionFieldRecord->hasTrivialCopyAssignment())
4108 return true;
4109 }
4110 }
4111
4112 // Don't try to initalize an anonymous union
4113 continue;
4114 // -- a variant member with a non-trivial [copy] assignment operator
4115 // and X is a union-like class
4116 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4117 return true;
4118 }
Sean Hunt7f410192011-05-14 05:23:24 +00004119
Sean Hunt661c67a2011-06-21 23:42:56 +00004120 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4121 false, 0);
4122 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004123 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004124 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004125 return true;
4126 }
4127 }
4128
4129 return false;
4130}
4131
4132bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) {
4133 CXXRecordDecl *RD = CD->getParent();
4134 assert(!RD->isDependentType() && "do deletion after instantiation");
4135 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4136 return false;
4137
4138 SourceLocation Loc = CD->getLocation();
4139
4140 // Do access control from the constructor
4141 ContextRAII CtorContext(*this, CD);
4142
4143 bool Union = RD->isUnion();
4144
4145 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4146 "copy assignment arg has no pointee type");
4147
4148 // We do this because we should never actually use an anonymous
4149 // union's constructor.
4150 if (Union && RD->isAnonymousStructOrUnion())
4151 return false;
4152
4153 // C++0x [class.copy]/11
4154 // A defaulted [move] constructor for class X is defined as deleted
4155 // if X has:
4156
4157 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4158 BE = RD->bases_end();
4159 BI != BE; ++BI) {
4160 // We'll handle this one later
4161 if (BI->isVirtual())
4162 continue;
4163
4164 QualType BaseType = BI->getType();
4165 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4166 assert(BaseDecl && "base isn't a CXXRecordDecl");
4167
4168 // -- any [direct base class] of a type with a destructor that is deleted or
4169 // inaccessible from the defaulted constructor
4170 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4171 if (BaseDtor->isDeleted())
4172 return true;
4173 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4174 AR_accessible)
4175 return true;
4176
4177 // -- a [direct base class] B that cannot be [moved] because overload
4178 // resolution, as applied to B's [move] constructor, results in an
4179 // ambiguity or a function that is deleted or inaccessible from the
4180 // defaulted constructor
4181 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4182 if (!BaseCtor || BaseCtor->isDeleted())
4183 return true;
4184 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4185 AR_accessible)
4186 return true;
4187
4188 // -- for a move constructor, a [direct base class] with a type that
4189 // does not have a move constructor and is not trivially copyable.
4190 // If the field isn't a record, it's always trivially copyable.
4191 // A moving constructor could be a copy constructor instead.
4192 if (!BaseCtor->isMoveConstructor() &&
4193 !BaseDecl->isTriviallyCopyable())
4194 return true;
4195 }
4196
4197 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4198 BE = RD->vbases_end();
4199 BI != BE; ++BI) {
4200 QualType BaseType = BI->getType();
4201 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4202 assert(BaseDecl && "base isn't a CXXRecordDecl");
4203
4204 // -- any [virtual base class] of a type with a destructor that is deleted
4205 // or inaccessible from the defaulted constructor
4206 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4207 if (BaseDtor->isDeleted())
4208 return true;
4209 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4210 AR_accessible)
4211 return true;
4212
4213 // -- a [virtual base class] B that cannot be [moved] because overload
4214 // resolution, as applied to B's [move] constructor, results in an
4215 // ambiguity or a function that is deleted or inaccessible from the
4216 // defaulted constructor
4217 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4218 if (!BaseCtor || BaseCtor->isDeleted())
4219 return true;
4220 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4221 AR_accessible)
4222 return true;
4223
4224 // -- for a move constructor, a [virtual base class] with a type that
4225 // does not have a move constructor and is not trivially copyable.
4226 // If the field isn't a record, it's always trivially copyable.
4227 // A moving constructor could be a copy constructor instead.
4228 if (!BaseCtor->isMoveConstructor() &&
4229 !BaseDecl->isTriviallyCopyable())
4230 return true;
4231 }
4232
4233 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4234 FE = RD->field_end();
4235 FI != FE; ++FI) {
4236 QualType FieldType = Context.getBaseElementType(FI->getType());
4237
4238 if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) {
4239 // This is an anonymous union
4240 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4241 // Anonymous unions inside unions do not variant members create
4242 if (!Union) {
4243 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4244 UE = FieldRecord->field_end();
4245 UI != UE; ++UI) {
4246 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4247 CXXRecordDecl *UnionFieldRecord =
4248 UnionFieldType->getAsCXXRecordDecl();
4249
4250 // -- a variant member with a non-trivial [move] constructor and X
4251 // is a union-like class
4252 if (UnionFieldRecord &&
4253 !UnionFieldRecord->hasTrivialMoveConstructor())
4254 return true;
4255 }
4256 }
4257
4258 // Don't try to initalize an anonymous union
4259 continue;
4260 } else {
4261 // -- a variant member with a non-trivial [move] constructor and X is a
4262 // union-like class
4263 if (Union && !FieldRecord->hasTrivialMoveConstructor())
4264 return true;
4265
4266 // -- any [non-static data member] of a type with a destructor that is
4267 // deleted or inaccessible from the defaulted constructor
4268 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4269 if (FieldDtor->isDeleted())
4270 return true;
4271 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4272 AR_accessible)
4273 return true;
4274 }
4275
4276 // -- a [non-static data member of class type (or array thereof)] B that
4277 // cannot be [moved] because overload resolution, as applied to B's
4278 // [move] constructor, results in an ambiguity or a function that is
4279 // deleted or inaccessible from the defaulted constructor
4280 CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord);
4281 if (!FieldCtor || FieldCtor->isDeleted())
4282 return true;
4283 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4284 PDiag()) != AR_accessible)
4285 return true;
4286
4287 // -- for a move constructor, a [non-static data member] with a type that
4288 // does not have a move constructor and is not trivially copyable.
4289 // If the field isn't a record, it's always trivially copyable.
4290 // A moving constructor could be a copy constructor instead.
4291 if (!FieldCtor->isMoveConstructor() &&
4292 !FieldRecord->isTriviallyCopyable())
4293 return true;
4294 }
4295 }
4296
4297 return false;
4298}
4299
4300bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4301 CXXRecordDecl *RD = MD->getParent();
4302 assert(!RD->isDependentType() && "do deletion after instantiation");
4303 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4304 return false;
4305
4306 SourceLocation Loc = MD->getLocation();
4307
4308 // Do access control from the constructor
4309 ContextRAII MethodContext(*this, MD);
4310
4311 bool Union = RD->isUnion();
4312
4313 // We do this because we should never actually use an anonymous
4314 // union's constructor.
4315 if (Union && RD->isAnonymousStructOrUnion())
4316 return false;
4317
4318 // C++0x [class.copy]/20
4319 // A defaulted [move] assignment operator for class X is defined as deleted
4320 // if X has:
4321
4322 // -- for the move constructor, [...] any direct or indirect virtual base
4323 // class.
4324 if (RD->getNumVBases() != 0)
4325 return true;
4326
4327 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4328 BE = RD->bases_end();
4329 BI != BE; ++BI) {
4330
4331 QualType BaseType = BI->getType();
4332 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4333 assert(BaseDecl && "base isn't a CXXRecordDecl");
4334
4335 // -- a [direct base class] B that cannot be [moved] because overload
4336 // resolution, as applied to B's [move] assignment operator, results in
4337 // an ambiguity or a function that is deleted or inaccessible from the
4338 // assignment operator
4339 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4340 if (!MoveOper || MoveOper->isDeleted())
4341 return true;
4342 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4343 return true;
4344
4345 // -- for the move assignment operator, a [direct base class] with a type
4346 // that does not have a move assignment operator and is not trivially
4347 // copyable.
4348 if (!MoveOper->isMoveAssignmentOperator() &&
4349 !BaseDecl->isTriviallyCopyable())
4350 return true;
4351 }
4352
4353 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4354 FE = RD->field_end();
4355 FI != FE; ++FI) {
4356 QualType FieldType = Context.getBaseElementType(FI->getType());
4357
4358 // -- a non-static data member of reference type
4359 if (FieldType->isReferenceType())
4360 return true;
4361
4362 // -- a non-static data member of const non-class type (or array thereof)
4363 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4364 return true;
4365
4366 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4367
4368 if (FieldRecord) {
4369 // This is an anonymous union
4370 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4371 // Anonymous unions inside unions do not variant members create
4372 if (!Union) {
4373 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4374 UE = FieldRecord->field_end();
4375 UI != UE; ++UI) {
4376 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4377 CXXRecordDecl *UnionFieldRecord =
4378 UnionFieldType->getAsCXXRecordDecl();
4379
4380 // -- a variant member with a non-trivial [move] assignment operator
4381 // and X is a union-like class
4382 if (UnionFieldRecord &&
4383 !UnionFieldRecord->hasTrivialMoveAssignment())
4384 return true;
4385 }
4386 }
4387
4388 // Don't try to initalize an anonymous union
4389 continue;
4390 // -- a variant member with a non-trivial [move] assignment operator
4391 // and X is a union-like class
4392 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4393 return true;
4394 }
4395
4396 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4397 if (!MoveOper || MoveOper->isDeleted())
4398 return true;
4399 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4400 return true;
4401
4402 // -- for the move assignment operator, a [non-static data member] with a
4403 // type that does not have a move assignment operator and is not
4404 // trivially copyable.
4405 if (!MoveOper->isMoveAssignmentOperator() &&
4406 !FieldRecord->isTriviallyCopyable())
4407 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004408 }
Sean Hunt7f410192011-05-14 05:23:24 +00004409 }
4410
4411 return false;
4412}
4413
Sean Huntcb45a0f2011-05-12 22:46:25 +00004414bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4415 CXXRecordDecl *RD = DD->getParent();
4416 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004417 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004418 return false;
4419
Sean Hunt71a682f2011-05-18 03:41:58 +00004420 SourceLocation Loc = DD->getLocation();
4421
Sean Huntcb45a0f2011-05-12 22:46:25 +00004422 // Do access control from the destructor
4423 ContextRAII CtorContext(*this, DD);
4424
4425 bool Union = RD->isUnion();
4426
Sean Hunt49634cf2011-05-13 06:10:58 +00004427 // We do this because we should never actually use an anonymous
4428 // union's destructor.
4429 if (Union && RD->isAnonymousStructOrUnion())
4430 return false;
4431
Sean Huntcb45a0f2011-05-12 22:46:25 +00004432 // C++0x [class.dtor]p5
4433 // A defaulted destructor for a class X is defined as deleted if:
4434 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4435 BE = RD->bases_end();
4436 BI != BE; ++BI) {
4437 // We'll handle this one later
4438 if (BI->isVirtual())
4439 continue;
4440
4441 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4442 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4443 assert(BaseDtor && "base has no destructor");
4444
4445 // -- any direct or virtual base class has a deleted destructor or
4446 // a destructor that is inaccessible from the defaulted destructor
4447 if (BaseDtor->isDeleted())
4448 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004449 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004450 AR_accessible)
4451 return true;
4452 }
4453
4454 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4455 BE = RD->vbases_end();
4456 BI != BE; ++BI) {
4457 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4458 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4459 assert(BaseDtor && "base has no destructor");
4460
4461 // -- any direct or virtual base class has a deleted destructor or
4462 // a destructor that is inaccessible from the defaulted destructor
4463 if (BaseDtor->isDeleted())
4464 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004465 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004466 AR_accessible)
4467 return true;
4468 }
4469
4470 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4471 FE = RD->field_end();
4472 FI != FE; ++FI) {
4473 QualType FieldType = Context.getBaseElementType(FI->getType());
4474 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4475 if (FieldRecord) {
4476 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4477 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4478 UE = FieldRecord->field_end();
4479 UI != UE; ++UI) {
4480 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4481 CXXRecordDecl *UnionFieldRecord =
4482 UnionFieldType->getAsCXXRecordDecl();
4483
4484 // -- X is a union-like class that has a variant member with a non-
4485 // trivial destructor.
4486 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4487 return true;
4488 }
4489 // Technically we are supposed to do this next check unconditionally.
4490 // But that makes absolutely no sense.
4491 } else {
4492 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4493
4494 // -- any of the non-static data members has class type M (or array
4495 // thereof) and M has a deleted destructor or a destructor that is
4496 // inaccessible from the defaulted destructor
4497 if (FieldDtor->isDeleted())
4498 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004499 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004500 AR_accessible)
4501 return true;
4502
4503 // -- X is a union-like class that has a variant member with a non-
4504 // trivial destructor.
4505 if (Union && !FieldDtor->isTrivial())
4506 return true;
4507 }
4508 }
4509 }
4510
4511 if (DD->isVirtual()) {
4512 FunctionDecl *OperatorDelete = 0;
4513 DeclarationName Name =
4514 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004515 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004516 false))
4517 return true;
4518 }
4519
4520
4521 return false;
4522}
4523
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004524/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004525namespace {
4526 struct FindHiddenVirtualMethodData {
4527 Sema *S;
4528 CXXMethodDecl *Method;
4529 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004530 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004531 };
4532}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004533
4534/// \brief Member lookup function that determines whether a given C++
4535/// method overloads virtual methods in a base class without overriding any,
4536/// to be used with CXXRecordDecl::lookupInBases().
4537static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4538 CXXBasePath &Path,
4539 void *UserData) {
4540 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4541
4542 FindHiddenVirtualMethodData &Data
4543 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4544
4545 DeclarationName Name = Data.Method->getDeclName();
4546 assert(Name.getNameKind() == DeclarationName::Identifier);
4547
4548 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004549 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004550 for (Path.Decls = BaseRecord->lookup(Name);
4551 Path.Decls.first != Path.Decls.second;
4552 ++Path.Decls.first) {
4553 NamedDecl *D = *Path.Decls.first;
4554 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004555 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004556 foundSameNameMethod = true;
4557 // Interested only in hidden virtual methods.
4558 if (!MD->isVirtual())
4559 continue;
4560 // If the method we are checking overrides a method from its base
4561 // don't warn about the other overloaded methods.
4562 if (!Data.S->IsOverload(Data.Method, MD, false))
4563 return true;
4564 // Collect the overload only if its hidden.
4565 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4566 overloadedMethods.push_back(MD);
4567 }
4568 }
4569
4570 if (foundSameNameMethod)
4571 Data.OverloadedMethods.append(overloadedMethods.begin(),
4572 overloadedMethods.end());
4573 return foundSameNameMethod;
4574}
4575
4576/// \brief See if a method overloads virtual methods in a base class without
4577/// overriding any.
4578void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4579 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4580 MD->getLocation()) == Diagnostic::Ignored)
4581 return;
4582 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4583 return;
4584
4585 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4586 /*bool RecordPaths=*/false,
4587 /*bool DetectVirtual=*/false);
4588 FindHiddenVirtualMethodData Data;
4589 Data.Method = MD;
4590 Data.S = this;
4591
4592 // Keep the base methods that were overriden or introduced in the subclass
4593 // by 'using' in a set. A base method not in this set is hidden.
4594 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4595 res.first != res.second; ++res.first) {
4596 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4597 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4598 E = MD->end_overridden_methods();
4599 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004600 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004601 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4602 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004603 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004604 }
4605
4606 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4607 !Data.OverloadedMethods.empty()) {
4608 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4609 << MD << (Data.OverloadedMethods.size() > 1);
4610
4611 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4612 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4613 Diag(overloadedMD->getLocation(),
4614 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4615 }
4616 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004617}
4618
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004619void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004620 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004621 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004622 SourceLocation RBrac,
4623 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004624 if (!TagDecl)
4625 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004626
Douglas Gregor42af25f2009-05-11 19:58:34 +00004627 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004628
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004629 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00004630 // strict aliasing violation!
4631 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004632 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004633
Douglas Gregor23c94db2010-07-02 17:43:08 +00004634 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004635 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004636}
4637
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004638/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4639/// special functions, such as the default constructor, copy
4640/// constructor, or destructor, to the given C++ class (C++
4641/// [special]p1). This routine can only be executed just before the
4642/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004643void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004644 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004645 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004646
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004647 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004648 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004649
Douglas Gregora376d102010-07-02 21:50:04 +00004650 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4651 ++ASTContext::NumImplicitCopyAssignmentOperators;
4652
4653 // If we have a dynamic class, then the copy assignment operator may be
4654 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4655 // it shows up in the right place in the vtable and that we diagnose
4656 // problems with the implicit exception specification.
4657 if (ClassDecl->isDynamicClass())
4658 DeclareImplicitCopyAssignment(ClassDecl);
4659 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004660
Douglas Gregor4923aa22010-07-02 20:37:36 +00004661 if (!ClassDecl->hasUserDeclaredDestructor()) {
4662 ++ASTContext::NumImplicitDestructors;
4663
4664 // If we have a dynamic class, then the destructor may be virtual, so we
4665 // have to declare the destructor immediately. This ensures that, e.g., it
4666 // shows up in the right place in the vtable and that we diagnose problems
4667 // with the implicit exception specification.
4668 if (ClassDecl->isDynamicClass())
4669 DeclareImplicitDestructor(ClassDecl);
4670 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004671}
4672
Francois Pichet8387e2a2011-04-22 22:18:13 +00004673void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4674 if (!D)
4675 return;
4676
4677 int NumParamList = D->getNumTemplateParameterLists();
4678 for (int i = 0; i < NumParamList; i++) {
4679 TemplateParameterList* Params = D->getTemplateParameterList(i);
4680 for (TemplateParameterList::iterator Param = Params->begin(),
4681 ParamEnd = Params->end();
4682 Param != ParamEnd; ++Param) {
4683 NamedDecl *Named = cast<NamedDecl>(*Param);
4684 if (Named->getDeclName()) {
4685 S->AddDecl(Named);
4686 IdResolver.AddDecl(Named);
4687 }
4688 }
4689 }
4690}
4691
John McCalld226f652010-08-21 09:40:31 +00004692void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004693 if (!D)
4694 return;
4695
4696 TemplateParameterList *Params = 0;
4697 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4698 Params = Template->getTemplateParameters();
4699 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4700 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4701 Params = PartialSpec->getTemplateParameters();
4702 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004703 return;
4704
Douglas Gregor6569d682009-05-27 23:11:45 +00004705 for (TemplateParameterList::iterator Param = Params->begin(),
4706 ParamEnd = Params->end();
4707 Param != ParamEnd; ++Param) {
4708 NamedDecl *Named = cast<NamedDecl>(*Param);
4709 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004710 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004711 IdResolver.AddDecl(Named);
4712 }
4713 }
4714}
4715
John McCalld226f652010-08-21 09:40:31 +00004716void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004717 if (!RecordD) return;
4718 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004719 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004720 PushDeclContext(S, Record);
4721}
4722
John McCalld226f652010-08-21 09:40:31 +00004723void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004724 if (!RecordD) return;
4725 PopDeclContext();
4726}
4727
Douglas Gregor72b505b2008-12-16 21:30:33 +00004728/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4729/// parsing a top-level (non-nested) C++ class, and we are now
4730/// parsing those parts of the given Method declaration that could
4731/// not be parsed earlier (C++ [class.mem]p2), such as default
4732/// arguments. This action should enter the scope of the given
4733/// Method declaration as if we had just parsed the qualified method
4734/// name. However, it should not bring the parameters into scope;
4735/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004736void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004737}
4738
4739/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4740/// C++ method declaration. We're (re-)introducing the given
4741/// function parameter into scope for use in parsing later parts of
4742/// the method declaration. For example, we could see an
4743/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004744void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004745 if (!ParamD)
4746 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004747
John McCalld226f652010-08-21 09:40:31 +00004748 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004749
4750 // If this parameter has an unparsed default argument, clear it out
4751 // to make way for the parsed default argument.
4752 if (Param->hasUnparsedDefaultArg())
4753 Param->setDefaultArg(0);
4754
John McCalld226f652010-08-21 09:40:31 +00004755 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004756 if (Param->getDeclName())
4757 IdResolver.AddDecl(Param);
4758}
4759
4760/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4761/// processing the delayed method declaration for Method. The method
4762/// declaration is now considered finished. There may be a separate
4763/// ActOnStartOfFunctionDef action later (not necessarily
4764/// immediately!) for this method, if it was also defined inside the
4765/// class body.
John McCalld226f652010-08-21 09:40:31 +00004766void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004767 if (!MethodD)
4768 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004769
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004770 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004771
John McCalld226f652010-08-21 09:40:31 +00004772 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004773
4774 // Now that we have our default arguments, check the constructor
4775 // again. It could produce additional diagnostics or affect whether
4776 // the class has implicitly-declared destructors, among other
4777 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004778 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4779 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004780
4781 // Check the default arguments, which we may have added.
4782 if (!Method->isInvalidDecl())
4783 CheckCXXDefaultArguments(Method);
4784}
4785
Douglas Gregor42a552f2008-11-05 20:51:48 +00004786/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004787/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004788/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004789/// emit diagnostics and set the invalid bit to true. In any case, the type
4790/// will be updated to reflect a well-formed type for the constructor and
4791/// returned.
4792QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004793 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004794 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004795
4796 // C++ [class.ctor]p3:
4797 // A constructor shall not be virtual (10.3) or static (9.4). A
4798 // constructor can be invoked for a const, volatile or const
4799 // volatile object. A constructor shall not be declared const,
4800 // volatile, or const volatile (9.3.2).
4801 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004802 if (!D.isInvalidType())
4803 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4804 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4805 << SourceRange(D.getIdentifierLoc());
4806 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004807 }
John McCalld931b082010-08-26 03:08:43 +00004808 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004809 if (!D.isInvalidType())
4810 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4811 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4812 << SourceRange(D.getIdentifierLoc());
4813 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004814 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004815 }
Mike Stump1eb44332009-09-09 15:08:12 +00004816
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004817 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004818 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004819 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004820 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4821 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004822 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004823 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4824 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004825 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004826 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4827 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004828 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004829 }
Mike Stump1eb44332009-09-09 15:08:12 +00004830
Douglas Gregorc938c162011-01-26 05:01:58 +00004831 // C++0x [class.ctor]p4:
4832 // A constructor shall not be declared with a ref-qualifier.
4833 if (FTI.hasRefQualifier()) {
4834 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4835 << FTI.RefQualifierIsLValueRef
4836 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4837 D.setInvalidType();
4838 }
4839
Douglas Gregor42a552f2008-11-05 20:51:48 +00004840 // Rebuild the function type "R" without any type qualifiers (in
4841 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004842 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004843 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004844 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4845 return R;
4846
4847 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4848 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004849 EPI.RefQualifier = RQ_None;
4850
Chris Lattner65401802009-04-25 08:28:21 +00004851 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004852 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004853}
4854
Douglas Gregor72b505b2008-12-16 21:30:33 +00004855/// CheckConstructor - Checks a fully-formed constructor for
4856/// well-formedness, issuing any diagnostics required. Returns true if
4857/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004858void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004859 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004860 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4861 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004862 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004863
4864 // C++ [class.copy]p3:
4865 // A declaration of a constructor for a class X is ill-formed if
4866 // its first parameter is of type (optionally cv-qualified) X and
4867 // either there are no other parameters or else all other
4868 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004869 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004870 ((Constructor->getNumParams() == 1) ||
4871 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004872 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4873 Constructor->getTemplateSpecializationKind()
4874 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004875 QualType ParamType = Constructor->getParamDecl(0)->getType();
4876 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4877 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00004878 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004879 const char *ConstRef
4880 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4881 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00004882 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004883 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00004884
4885 // FIXME: Rather that making the constructor invalid, we should endeavor
4886 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00004887 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004888 }
4889 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00004890}
4891
John McCall15442822010-08-04 01:04:25 +00004892/// CheckDestructor - Checks a fully-formed destructor definition for
4893/// well-formedness, issuing any diagnostics required. Returns true
4894/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004895bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00004896 CXXRecordDecl *RD = Destructor->getParent();
4897
4898 if (Destructor->isVirtual()) {
4899 SourceLocation Loc;
4900
4901 if (!Destructor->isImplicit())
4902 Loc = Destructor->getLocation();
4903 else
4904 Loc = RD->getLocation();
4905
4906 // If we have a virtual destructor, look up the deallocation function
4907 FunctionDecl *OperatorDelete = 0;
4908 DeclarationName Name =
4909 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004910 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00004911 return true;
John McCall5efd91a2010-07-03 18:33:00 +00004912
4913 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00004914
4915 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00004916 }
Anders Carlsson37909802009-11-30 21:24:50 +00004917
4918 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00004919}
4920
Mike Stump1eb44332009-09-09 15:08:12 +00004921static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004922FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4923 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4924 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00004925 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004926}
4927
Douglas Gregor42a552f2008-11-05 20:51:48 +00004928/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4929/// the well-formednes of the destructor declarator @p D with type @p
4930/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004931/// emit diagnostics and set the declarator to invalid. Even if this happens,
4932/// will be updated to reflect a well-formed type for the destructor and
4933/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00004934QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004935 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004936 // C++ [class.dtor]p1:
4937 // [...] A typedef-name that names a class is a class-name
4938 // (7.1.3); however, a typedef-name that names a class shall not
4939 // be used as the identifier in the declarator for a destructor
4940 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004941 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00004942 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00004943 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00004944 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00004945 else if (const TemplateSpecializationType *TST =
4946 DeclaratorType->getAs<TemplateSpecializationType>())
4947 if (TST->isTypeAlias())
4948 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4949 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004950
4951 // C++ [class.dtor]p2:
4952 // A destructor is used to destroy objects of its class type. A
4953 // destructor takes no parameters, and no return type can be
4954 // specified for it (not even void). The address of a destructor
4955 // shall not be taken. A destructor shall not be static. A
4956 // destructor can be invoked for a const, volatile or const
4957 // volatile object. A destructor shall not be declared const,
4958 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00004959 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004960 if (!D.isInvalidType())
4961 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4962 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00004963 << SourceRange(D.getIdentifierLoc())
4964 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4965
John McCalld931b082010-08-26 03:08:43 +00004966 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004967 }
Chris Lattner65401802009-04-25 08:28:21 +00004968 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004969 // Destructors don't have return types, but the parser will
4970 // happily parse something like:
4971 //
4972 // class X {
4973 // float ~X();
4974 // };
4975 //
4976 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004977 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4978 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4979 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00004980 }
Mike Stump1eb44332009-09-09 15:08:12 +00004981
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004982 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004983 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00004984 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004985 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4986 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004987 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004988 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4989 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004990 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004991 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4992 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00004993 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004994 }
4995
Douglas Gregorc938c162011-01-26 05:01:58 +00004996 // C++0x [class.dtor]p2:
4997 // A destructor shall not be declared with a ref-qualifier.
4998 if (FTI.hasRefQualifier()) {
4999 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5000 << FTI.RefQualifierIsLValueRef
5001 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5002 D.setInvalidType();
5003 }
5004
Douglas Gregor42a552f2008-11-05 20:51:48 +00005005 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005006 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005007 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5008
5009 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005010 FTI.freeArgs();
5011 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005012 }
5013
Mike Stump1eb44332009-09-09 15:08:12 +00005014 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005015 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005016 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005017 D.setInvalidType();
5018 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005019
5020 // Rebuild the function type "R" without any type qualifiers or
5021 // parameters (in case any of the errors above fired) and with
5022 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005023 // types.
John McCalle23cf432010-12-14 08:05:40 +00005024 if (!D.isInvalidType())
5025 return R;
5026
Douglas Gregord92ec472010-07-01 05:10:53 +00005027 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005028 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5029 EPI.Variadic = false;
5030 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005031 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005032 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005033}
5034
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005035/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5036/// well-formednes of the conversion function declarator @p D with
5037/// type @p R. If there are any errors in the declarator, this routine
5038/// will emit diagnostics and return true. Otherwise, it will return
5039/// false. Either way, the type @p R will be updated to reflect a
5040/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005041void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005042 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005043 // C++ [class.conv.fct]p1:
5044 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005045 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005046 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005047 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005048 if (!D.isInvalidType())
5049 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5050 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5051 << SourceRange(D.getIdentifierLoc());
5052 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005053 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005054 }
John McCalla3f81372010-04-13 00:04:31 +00005055
5056 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5057
Chris Lattner6e475012009-04-25 08:35:12 +00005058 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005059 // Conversion functions don't have return types, but the parser will
5060 // happily parse something like:
5061 //
5062 // class X {
5063 // float operator bool();
5064 // };
5065 //
5066 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005067 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5068 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5069 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005070 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005071 }
5072
John McCalla3f81372010-04-13 00:04:31 +00005073 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5074
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005075 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005076 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005077 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5078
5079 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005080 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005081 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005082 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005083 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005084 D.setInvalidType();
5085 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005086
John McCalla3f81372010-04-13 00:04:31 +00005087 // Diagnose "&operator bool()" and other such nonsense. This
5088 // is actually a gcc extension which we don't support.
5089 if (Proto->getResultType() != ConvType) {
5090 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5091 << Proto->getResultType();
5092 D.setInvalidType();
5093 ConvType = Proto->getResultType();
5094 }
5095
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005096 // C++ [class.conv.fct]p4:
5097 // The conversion-type-id shall not represent a function type nor
5098 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005099 if (ConvType->isArrayType()) {
5100 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5101 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005102 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005103 } else if (ConvType->isFunctionType()) {
5104 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5105 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005106 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005107 }
5108
5109 // Rebuild the function type "R" without any parameters (in case any
5110 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005111 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005112 if (D.isInvalidType())
5113 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005114
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005115 // C++0x explicit conversion operators.
5116 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00005117 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005118 diag::warn_explicit_conversion_functions)
5119 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005120}
5121
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005122/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5123/// the declaration of the given C++ conversion function. This routine
5124/// is responsible for recording the conversion function in the C++
5125/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005126Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005127 assert(Conversion && "Expected to receive a conversion function declaration");
5128
Douglas Gregor9d350972008-12-12 08:25:50 +00005129 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005130
5131 // Make sure we aren't redeclaring the conversion function.
5132 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005133
5134 // C++ [class.conv.fct]p1:
5135 // [...] A conversion function is never used to convert a
5136 // (possibly cv-qualified) object to the (possibly cv-qualified)
5137 // same object type (or a reference to it), to a (possibly
5138 // cv-qualified) base class of that type (or a reference to it),
5139 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005140 // FIXME: Suppress this warning if the conversion function ends up being a
5141 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005142 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005143 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005144 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005145 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005146 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5147 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005148 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005149 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005150 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5151 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005152 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005153 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005154 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005155 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005156 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005157 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005158 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005159 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005160 }
5161
Douglas Gregore80622f2010-09-29 04:25:11 +00005162 if (FunctionTemplateDecl *ConversionTemplate
5163 = Conversion->getDescribedFunctionTemplate())
5164 return ConversionTemplate;
5165
John McCalld226f652010-08-21 09:40:31 +00005166 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005167}
5168
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005169//===----------------------------------------------------------------------===//
5170// Namespace Handling
5171//===----------------------------------------------------------------------===//
5172
John McCallea318642010-08-26 09:15:37 +00005173
5174
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005175/// ActOnStartNamespaceDef - This is called at the start of a namespace
5176/// definition.
John McCalld226f652010-08-21 09:40:31 +00005177Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005178 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005179 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005180 SourceLocation IdentLoc,
5181 IdentifierInfo *II,
5182 SourceLocation LBrace,
5183 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005184 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5185 // For anonymous namespace, take the location of the left brace.
5186 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00005187 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005188 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005189 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005190
5191 Scope *DeclRegionScope = NamespcScope->getParent();
5192
Anders Carlsson2a3503d2010-02-07 01:09:23 +00005193 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5194
John McCall90f14502010-12-10 02:59:44 +00005195 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5196 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005197
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005198 if (II) {
5199 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005200 // The identifier in an original-namespace-definition shall not
5201 // have been previously defined in the declarative region in
5202 // which the original-namespace-definition appears. The
5203 // identifier in an original-namespace-definition is the name of
5204 // the namespace. Subsequently in that declarative region, it is
5205 // treated as an original-namespace-name.
5206 //
5207 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005208 // look through using directives, just look for any ordinary names.
5209
5210 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5211 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5212 Decl::IDNS_Namespace;
5213 NamedDecl *PrevDecl = 0;
5214 for (DeclContext::lookup_result R
5215 = CurContext->getRedeclContext()->lookup(II);
5216 R.first != R.second; ++R.first) {
5217 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5218 PrevDecl = *R.first;
5219 break;
5220 }
5221 }
5222
Douglas Gregor44b43212008-12-11 16:49:14 +00005223 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5224 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005225 if (Namespc->isInline() != OrigNS->isInline()) {
5226 // inline-ness must match
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005227 if (OrigNS->isInline()) {
5228 // The user probably just forgot the 'inline', so suggest that it
5229 // be added back.
5230 Diag(Namespc->getLocation(),
5231 diag::warn_inline_namespace_reopened_noninline)
5232 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5233 } else {
5234 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5235 << Namespc->isInline();
5236 }
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005237 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005238
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005239 // Recover by ignoring the new namespace's inline status.
5240 Namespc->setInline(OrigNS->isInline());
5241 }
5242
Douglas Gregor44b43212008-12-11 16:49:14 +00005243 // Attach this namespace decl to the chain of extended namespace
5244 // definitions.
5245 OrigNS->setNextNamespace(Namespc);
5246 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005247
Mike Stump1eb44332009-09-09 15:08:12 +00005248 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00005249 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00005250 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00005251 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005252 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005253 } else if (PrevDecl) {
5254 // This is an invalid name redefinition.
5255 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5256 << Namespc->getDeclName();
5257 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5258 Namespc->setInvalidDecl();
5259 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005260 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005261 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005262 // This is the first "real" definition of the namespace "std", so update
5263 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005264 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005265 // We had already defined a dummy namespace "std". Link this new
5266 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005267 StdNS->setNextNamespace(Namespc);
5268 StdNS->setLocation(IdentLoc);
5269 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005270 }
5271
5272 // Make our StdNamespace cache point at the first real definition of the
5273 // "std" namespace.
5274 StdNamespace = Namespc;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005275
5276 // Add this instance of "std" to the set of known namespaces
5277 KnownNamespaces[Namespc] = false;
5278 } else if (!Namespc->isInline()) {
5279 // Since this is an "original" namespace, add it to the known set of
5280 // namespaces if it is not an inline namespace.
5281 KnownNamespaces[Namespc] = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005282 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005283
5284 PushOnScopeChains(Namespc, DeclRegionScope);
5285 } else {
John McCall9aeed322009-10-01 00:25:31 +00005286 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00005287 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00005288
5289 // Link the anonymous namespace into its parent.
5290 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005291 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005292 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5293 PrevDecl = TU->getAnonymousNamespace();
5294 TU->setAnonymousNamespace(Namespc);
5295 } else {
5296 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5297 PrevDecl = ND->getAnonymousNamespace();
5298 ND->setAnonymousNamespace(Namespc);
5299 }
5300
5301 // Link the anonymous namespace with its previous declaration.
5302 if (PrevDecl) {
5303 assert(PrevDecl->isAnonymousNamespace());
5304 assert(!PrevDecl->getNextNamespace());
5305 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5306 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005307
5308 if (Namespc->isInline() != PrevDecl->isInline()) {
5309 // inline-ness must match
5310 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5311 << Namespc->isInline();
5312 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5313 Namespc->setInvalidDecl();
5314 // Recover by ignoring the new namespace's inline status.
5315 Namespc->setInline(PrevDecl->isInline());
5316 }
John McCall5fdd7642009-12-16 02:06:49 +00005317 }
John McCall9aeed322009-10-01 00:25:31 +00005318
Douglas Gregora4181472010-03-24 00:46:35 +00005319 CurContext->addDecl(Namespc);
5320
John McCall9aeed322009-10-01 00:25:31 +00005321 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5322 // behaves as if it were replaced by
5323 // namespace unique { /* empty body */ }
5324 // using namespace unique;
5325 // namespace unique { namespace-body }
5326 // where all occurrences of 'unique' in a translation unit are
5327 // replaced by the same identifier and this identifier differs
5328 // from all other identifiers in the entire program.
5329
5330 // We just create the namespace with an empty name and then add an
5331 // implicit using declaration, just like the standard suggests.
5332 //
5333 // CodeGen enforces the "universally unique" aspect by giving all
5334 // declarations semantically contained within an anonymous
5335 // namespace internal linkage.
5336
John McCall5fdd7642009-12-16 02:06:49 +00005337 if (!PrevDecl) {
5338 UsingDirectiveDecl* UD
5339 = UsingDirectiveDecl::Create(Context, CurContext,
5340 /* 'using' */ LBrace,
5341 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005342 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005343 /* identifier */ SourceLocation(),
5344 Namespc,
5345 /* Ancestor */ CurContext);
5346 UD->setImplicit();
5347 CurContext->addDecl(UD);
5348 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005349 }
5350
5351 // Although we could have an invalid decl (i.e. the namespace name is a
5352 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005353 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5354 // for the namespace has the declarations that showed up in that particular
5355 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005356 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005357 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005358}
5359
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005360/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5361/// is a namespace alias, returns the namespace it points to.
5362static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5363 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5364 return AD->getNamespace();
5365 return dyn_cast_or_null<NamespaceDecl>(D);
5366}
5367
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005368/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5369/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005370void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005371 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5372 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005373 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005374 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005375 if (Namespc->hasAttr<VisibilityAttr>())
5376 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005377}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005378
John McCall384aff82010-08-25 07:42:41 +00005379CXXRecordDecl *Sema::getStdBadAlloc() const {
5380 return cast_or_null<CXXRecordDecl>(
5381 StdBadAlloc.get(Context.getExternalSource()));
5382}
5383
5384NamespaceDecl *Sema::getStdNamespace() const {
5385 return cast_or_null<NamespaceDecl>(
5386 StdNamespace.get(Context.getExternalSource()));
5387}
5388
Douglas Gregor66992202010-06-29 17:53:46 +00005389/// \brief Retrieve the special "std" namespace, which may require us to
5390/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005391NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005392 if (!StdNamespace) {
5393 // The "std" namespace has not yet been defined, so build one implicitly.
5394 StdNamespace = NamespaceDecl::Create(Context,
5395 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005396 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00005397 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005398 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005399 }
5400
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005401 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005402}
5403
Douglas Gregor9172aa62011-03-26 22:25:30 +00005404/// \brief Determine whether a using statement is in a context where it will be
5405/// apply in all contexts.
5406static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5407 switch (CurContext->getDeclKind()) {
5408 case Decl::TranslationUnit:
5409 return true;
5410 case Decl::LinkageSpec:
5411 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5412 default:
5413 return false;
5414 }
5415}
5416
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005417static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5418 CXXScopeSpec &SS,
5419 SourceLocation IdentLoc,
5420 IdentifierInfo *Ident) {
5421 R.clear();
5422 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5423 R.getLookupKind(), Sc, &SS, NULL,
5424 false, S.CTC_NoKeywords, NULL)) {
5425 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5426 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5427 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5428 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5429 if (DeclContext *DC = S.computeDeclContext(SS, false))
5430 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5431 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5432 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5433 else
5434 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5435 << Ident << CorrectedQuotedStr
5436 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5437
5438 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5439 diag::note_namespace_defined_here) << CorrectedQuotedStr;
5440
5441 Ident = Corrected.getCorrectionAsIdentifierInfo();
5442 R.addDecl(Corrected.getCorrectionDecl());
5443 return true;
5444 }
5445 R.setLookupName(Ident);
5446 }
5447 return false;
5448}
5449
John McCalld226f652010-08-21 09:40:31 +00005450Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005451 SourceLocation UsingLoc,
5452 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005453 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005454 SourceLocation IdentLoc,
5455 IdentifierInfo *NamespcName,
5456 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005457 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5458 assert(NamespcName && "Invalid NamespcName.");
5459 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005460
5461 // This can only happen along a recovery path.
5462 while (S->getFlags() & Scope::TemplateParamScope)
5463 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005464 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005465
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005466 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005467 NestedNameSpecifier *Qualifier = 0;
5468 if (SS.isSet())
5469 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5470
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005471 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005472 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5473 LookupParsedName(R, S, &SS);
5474 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005475 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005476
Douglas Gregor66992202010-06-29 17:53:46 +00005477 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005478 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005479 // Allow "using namespace std;" or "using namespace ::std;" even if
5480 // "std" hasn't been defined yet, for GCC compatibility.
5481 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5482 NamespcName->isStr("std")) {
5483 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005484 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005485 R.resolveKind();
5486 }
5487 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005488 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005489 }
5490
John McCallf36e02d2009-10-09 21:13:30 +00005491 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005492 NamedDecl *Named = R.getFoundDecl();
5493 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5494 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005495 // C++ [namespace.udir]p1:
5496 // A using-directive specifies that the names in the nominated
5497 // namespace can be used in the scope in which the
5498 // using-directive appears after the using-directive. During
5499 // unqualified name lookup (3.4.1), the names appear as if they
5500 // were declared in the nearest enclosing namespace which
5501 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005502 // namespace. [Note: in this context, "contains" means "contains
5503 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005504
5505 // Find enclosing context containing both using-directive and
5506 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005507 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005508 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5509 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5510 CommonAncestor = CommonAncestor->getParent();
5511
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005512 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005513 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005514 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005515
Douglas Gregor9172aa62011-03-26 22:25:30 +00005516 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005517 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005518 Diag(IdentLoc, diag::warn_using_directive_in_header);
5519 }
5520
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005521 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005522 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005523 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005524 }
5525
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005526 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005527 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005528}
5529
5530void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5531 // If scope has associated entity, then using directive is at namespace
5532 // or translation unit scope. We add UsingDirectiveDecls, into
5533 // it's lookup structure.
5534 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005535 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005536 else
5537 // Otherwise it is block-sope. using-directives will affect lookup
5538 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00005539 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005540}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005541
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005542
John McCalld226f652010-08-21 09:40:31 +00005543Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005544 AccessSpecifier AS,
5545 bool HasUsingKeyword,
5546 SourceLocation UsingLoc,
5547 CXXScopeSpec &SS,
5548 UnqualifiedId &Name,
5549 AttributeList *AttrList,
5550 bool IsTypeName,
5551 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005552 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005553
Douglas Gregor12c118a2009-11-04 16:30:06 +00005554 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005555 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005556 case UnqualifiedId::IK_Identifier:
5557 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005558 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005559 case UnqualifiedId::IK_ConversionFunctionId:
5560 break;
5561
5562 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005563 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005564 // C++0x inherited constructors.
5565 if (getLangOptions().CPlusPlus0x) break;
5566
Douglas Gregor12c118a2009-11-04 16:30:06 +00005567 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5568 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005569 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005570
5571 case UnqualifiedId::IK_DestructorName:
5572 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5573 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005574 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005575
5576 case UnqualifiedId::IK_TemplateId:
5577 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5578 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005579 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005580 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005581
5582 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5583 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005584 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005585 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005586
John McCall60fa3cf2009-12-11 02:10:03 +00005587 // Warn about using declarations.
5588 // TODO: store that the declaration was written without 'using' and
5589 // talk about access decls instead of using decls in the
5590 // diagnostics.
5591 if (!HasUsingKeyword) {
5592 UsingLoc = Name.getSourceRange().getBegin();
5593
5594 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005595 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005596 }
5597
Douglas Gregor56c04582010-12-16 00:46:58 +00005598 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5599 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5600 return 0;
5601
John McCall9488ea12009-11-17 05:59:44 +00005602 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005603 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005604 /* IsInstantiation */ false,
5605 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005606 if (UD)
5607 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005608
John McCalld226f652010-08-21 09:40:31 +00005609 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005610}
5611
Douglas Gregor09acc982010-07-07 23:08:52 +00005612/// \brief Determine whether a using declaration considers the given
5613/// declarations as "equivalent", e.g., if they are redeclarations of
5614/// the same entity or are both typedefs of the same type.
5615static bool
5616IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5617 bool &SuppressRedeclaration) {
5618 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5619 SuppressRedeclaration = false;
5620 return true;
5621 }
5622
Richard Smith162e1c12011-04-15 14:24:37 +00005623 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5624 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005625 SuppressRedeclaration = true;
5626 return Context.hasSameType(TD1->getUnderlyingType(),
5627 TD2->getUnderlyingType());
5628 }
5629
5630 return false;
5631}
5632
5633
John McCall9f54ad42009-12-10 09:41:52 +00005634/// Determines whether to create a using shadow decl for a particular
5635/// decl, given the set of decls existing prior to this using lookup.
5636bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5637 const LookupResult &Previous) {
5638 // Diagnose finding a decl which is not from a base class of the
5639 // current class. We do this now because there are cases where this
5640 // function will silently decide not to build a shadow decl, which
5641 // will pre-empt further diagnostics.
5642 //
5643 // We don't need to do this in C++0x because we do the check once on
5644 // the qualifier.
5645 //
5646 // FIXME: diagnose the following if we care enough:
5647 // struct A { int foo; };
5648 // struct B : A { using A::foo; };
5649 // template <class T> struct C : A {};
5650 // template <class T> struct D : C<T> { using B::foo; } // <---
5651 // This is invalid (during instantiation) in C++03 because B::foo
5652 // resolves to the using decl in B, which is not a base class of D<T>.
5653 // We can't diagnose it immediately because C<T> is an unknown
5654 // specialization. The UsingShadowDecl in D<T> then points directly
5655 // to A::foo, which will look well-formed when we instantiate.
5656 // The right solution is to not collapse the shadow-decl chain.
5657 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5658 DeclContext *OrigDC = Orig->getDeclContext();
5659
5660 // Handle enums and anonymous structs.
5661 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5662 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5663 while (OrigRec->isAnonymousStructOrUnion())
5664 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5665
5666 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5667 if (OrigDC == CurContext) {
5668 Diag(Using->getLocation(),
5669 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005670 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005671 Diag(Orig->getLocation(), diag::note_using_decl_target);
5672 return true;
5673 }
5674
Douglas Gregordc355712011-02-25 00:36:19 +00005675 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005676 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005677 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005678 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005679 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005680 Diag(Orig->getLocation(), diag::note_using_decl_target);
5681 return true;
5682 }
5683 }
5684
5685 if (Previous.empty()) return false;
5686
5687 NamedDecl *Target = Orig;
5688 if (isa<UsingShadowDecl>(Target))
5689 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5690
John McCalld7533ec2009-12-11 02:33:26 +00005691 // If the target happens to be one of the previous declarations, we
5692 // don't have a conflict.
5693 //
5694 // FIXME: but we might be increasing its access, in which case we
5695 // should redeclare it.
5696 NamedDecl *NonTag = 0, *Tag = 0;
5697 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5698 I != E; ++I) {
5699 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005700 bool Result;
5701 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5702 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005703
5704 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5705 }
5706
John McCall9f54ad42009-12-10 09:41:52 +00005707 if (Target->isFunctionOrFunctionTemplate()) {
5708 FunctionDecl *FD;
5709 if (isa<FunctionTemplateDecl>(Target))
5710 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5711 else
5712 FD = cast<FunctionDecl>(Target);
5713
5714 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005715 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005716 case Ovl_Overload:
5717 return false;
5718
5719 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005720 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005721 break;
5722
5723 // We found a decl with the exact signature.
5724 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005725 // If we're in a record, we want to hide the target, so we
5726 // return true (without a diagnostic) to tell the caller not to
5727 // build a shadow decl.
5728 if (CurContext->isRecord())
5729 return true;
5730
5731 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005732 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005733 break;
5734 }
5735
5736 Diag(Target->getLocation(), diag::note_using_decl_target);
5737 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5738 return true;
5739 }
5740
5741 // Target is not a function.
5742
John McCall9f54ad42009-12-10 09:41:52 +00005743 if (isa<TagDecl>(Target)) {
5744 // No conflict between a tag and a non-tag.
5745 if (!Tag) return false;
5746
John McCall41ce66f2009-12-10 19:51:03 +00005747 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005748 Diag(Target->getLocation(), diag::note_using_decl_target);
5749 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5750 return true;
5751 }
5752
5753 // No conflict between a tag and a non-tag.
5754 if (!NonTag) return false;
5755
John McCall41ce66f2009-12-10 19:51:03 +00005756 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005757 Diag(Target->getLocation(), diag::note_using_decl_target);
5758 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5759 return true;
5760}
5761
John McCall9488ea12009-11-17 05:59:44 +00005762/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00005763UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00005764 UsingDecl *UD,
5765 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00005766
5767 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00005768 NamedDecl *Target = Orig;
5769 if (isa<UsingShadowDecl>(Target)) {
5770 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5771 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00005772 }
5773
5774 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00005775 = UsingShadowDecl::Create(Context, CurContext,
5776 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00005777 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00005778
5779 Shadow->setAccess(UD->getAccess());
5780 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5781 Shadow->setInvalidDecl();
5782
John McCall9488ea12009-11-17 05:59:44 +00005783 if (S)
John McCall604e7f12009-12-08 07:46:18 +00005784 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00005785 else
John McCall604e7f12009-12-08 07:46:18 +00005786 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00005787
John McCall604e7f12009-12-08 07:46:18 +00005788
John McCall9f54ad42009-12-10 09:41:52 +00005789 return Shadow;
5790}
John McCall604e7f12009-12-08 07:46:18 +00005791
John McCall9f54ad42009-12-10 09:41:52 +00005792/// Hides a using shadow declaration. This is required by the current
5793/// using-decl implementation when a resolvable using declaration in a
5794/// class is followed by a declaration which would hide or override
5795/// one or more of the using decl's targets; for example:
5796///
5797/// struct Base { void foo(int); };
5798/// struct Derived : Base {
5799/// using Base::foo;
5800/// void foo(int);
5801/// };
5802///
5803/// The governing language is C++03 [namespace.udecl]p12:
5804///
5805/// When a using-declaration brings names from a base class into a
5806/// derived class scope, member functions in the derived class
5807/// override and/or hide member functions with the same name and
5808/// parameter types in a base class (rather than conflicting).
5809///
5810/// There are two ways to implement this:
5811/// (1) optimistically create shadow decls when they're not hidden
5812/// by existing declarations, or
5813/// (2) don't create any shadow decls (or at least don't make them
5814/// visible) until we've fully parsed/instantiated the class.
5815/// The problem with (1) is that we might have to retroactively remove
5816/// a shadow decl, which requires several O(n) operations because the
5817/// decl structures are (very reasonably) not designed for removal.
5818/// (2) avoids this but is very fiddly and phase-dependent.
5819void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00005820 if (Shadow->getDeclName().getNameKind() ==
5821 DeclarationName::CXXConversionFunctionName)
5822 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5823
John McCall9f54ad42009-12-10 09:41:52 +00005824 // Remove it from the DeclContext...
5825 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005826
John McCall9f54ad42009-12-10 09:41:52 +00005827 // ...and the scope, if applicable...
5828 if (S) {
John McCalld226f652010-08-21 09:40:31 +00005829 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00005830 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005831 }
5832
John McCall9f54ad42009-12-10 09:41:52 +00005833 // ...and the using decl.
5834 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5835
5836 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00005837 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00005838}
5839
John McCall7ba107a2009-11-18 02:36:19 +00005840/// Builds a using declaration.
5841///
5842/// \param IsInstantiation - Whether this call arises from an
5843/// instantiation of an unresolved using declaration. We treat
5844/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00005845NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5846 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005847 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005848 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00005849 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005850 bool IsInstantiation,
5851 bool IsTypeName,
5852 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00005853 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005854 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00005855 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00005856
Anders Carlsson550b14b2009-08-28 05:49:21 +00005857 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00005858
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005859 if (SS.isEmpty()) {
5860 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00005861 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005862 }
Mike Stump1eb44332009-09-09 15:08:12 +00005863
John McCall9f54ad42009-12-10 09:41:52 +00005864 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005865 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00005866 ForRedeclaration);
5867 Previous.setHideTags(false);
5868 if (S) {
5869 LookupName(Previous, S);
5870
5871 // It is really dumb that we have to do this.
5872 LookupResult::Filter F = Previous.makeFilter();
5873 while (F.hasNext()) {
5874 NamedDecl *D = F.next();
5875 if (!isDeclInScope(D, CurContext, S))
5876 F.erase();
5877 }
5878 F.done();
5879 } else {
5880 assert(IsInstantiation && "no scope in non-instantiation");
5881 assert(CurContext->isRecord() && "scope not record in instantiation");
5882 LookupQualifiedName(Previous, CurContext);
5883 }
5884
John McCall9f54ad42009-12-10 09:41:52 +00005885 // Check for invalid redeclarations.
5886 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5887 return 0;
5888
5889 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00005890 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5891 return 0;
5892
John McCallaf8e6ed2009-11-12 03:15:40 +00005893 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005894 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00005895 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00005896 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00005897 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00005898 // FIXME: not all declaration name kinds are legal here
5899 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5900 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00005901 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005902 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00005903 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005904 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5905 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00005906 }
John McCalled976492009-12-04 22:46:56 +00005907 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005908 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5909 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00005910 }
John McCalled976492009-12-04 22:46:56 +00005911 D->setAccess(AS);
5912 CurContext->addDecl(D);
5913
5914 if (!LookupContext) return D;
5915 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00005916
John McCall77bb1aa2010-05-01 00:40:08 +00005917 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00005918 UD->setInvalidDecl();
5919 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005920 }
5921
Sebastian Redlf677ea32011-02-05 19:23:19 +00005922 // Constructor inheriting using decls get special treatment.
5923 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00005924 if (CheckInheritedConstructorUsingDecl(UD))
5925 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005926 return UD;
5927 }
5928
5929 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00005930
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005931 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetb2ee8302011-05-23 03:43:44 +00005932 R.setUsingDeclaration(true);
John McCall7ba107a2009-11-18 02:36:19 +00005933
John McCall604e7f12009-12-08 07:46:18 +00005934 // Unlike most lookups, we don't always want to hide tag
5935 // declarations: tag names are visible through the using declaration
5936 // even if hidden by ordinary names, *except* in a dependent context
5937 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00005938 if (!IsInstantiation)
5939 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00005940
John McCalla24dc2e2009-11-17 02:14:36 +00005941 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005942
John McCallf36e02d2009-10-09 21:13:30 +00005943 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00005944 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005945 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005946 UD->setInvalidDecl();
5947 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005948 }
5949
John McCalled976492009-12-04 22:46:56 +00005950 if (R.isAmbiguous()) {
5951 UD->setInvalidDecl();
5952 return UD;
5953 }
Mike Stump1eb44332009-09-09 15:08:12 +00005954
John McCall7ba107a2009-11-18 02:36:19 +00005955 if (IsTypeName) {
5956 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00005957 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005958 Diag(IdentLoc, diag::err_using_typename_non_type);
5959 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5960 Diag((*I)->getUnderlyingDecl()->getLocation(),
5961 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005962 UD->setInvalidDecl();
5963 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005964 }
5965 } else {
5966 // If we asked for a non-typename and we got a type, error out,
5967 // but only if this is an instantiation of an unresolved using
5968 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00005969 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005970 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5971 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005972 UD->setInvalidDecl();
5973 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005974 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005975 }
5976
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005977 // C++0x N2914 [namespace.udecl]p6:
5978 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00005979 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005980 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5981 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005982 UD->setInvalidDecl();
5983 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005984 }
Mike Stump1eb44332009-09-09 15:08:12 +00005985
John McCall9f54ad42009-12-10 09:41:52 +00005986 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5987 if (!CheckUsingShadowDecl(UD, *I, Previous))
5988 BuildUsingShadowDecl(S, UD, *I);
5989 }
John McCall9488ea12009-11-17 05:59:44 +00005990
5991 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005992}
5993
Sebastian Redlf677ea32011-02-05 19:23:19 +00005994/// Additional checks for a using declaration referring to a constructor name.
5995bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5996 if (UD->isTypeName()) {
5997 // FIXME: Cannot specify typename when specifying constructor
5998 return true;
5999 }
6000
Douglas Gregordc355712011-02-25 00:36:19 +00006001 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006002 assert(SourceType &&
6003 "Using decl naming constructor doesn't have type in scope spec.");
6004 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6005
6006 // Check whether the named type is a direct base class.
6007 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6008 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6009 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6010 BaseIt != BaseE; ++BaseIt) {
6011 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6012 if (CanonicalSourceType == BaseType)
6013 break;
6014 }
6015
6016 if (BaseIt == BaseE) {
6017 // Did not find SourceType in the bases.
6018 Diag(UD->getUsingLocation(),
6019 diag::err_using_decl_constructor_not_in_direct_base)
6020 << UD->getNameInfo().getSourceRange()
6021 << QualType(SourceType, 0) << TargetClass;
6022 return true;
6023 }
6024
6025 BaseIt->setInheritConstructors();
6026
6027 return false;
6028}
6029
John McCall9f54ad42009-12-10 09:41:52 +00006030/// Checks that the given using declaration is not an invalid
6031/// redeclaration. Note that this is checking only for the using decl
6032/// itself, not for any ill-formedness among the UsingShadowDecls.
6033bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6034 bool isTypeName,
6035 const CXXScopeSpec &SS,
6036 SourceLocation NameLoc,
6037 const LookupResult &Prev) {
6038 // C++03 [namespace.udecl]p8:
6039 // C++0x [namespace.udecl]p10:
6040 // A using-declaration is a declaration and can therefore be used
6041 // repeatedly where (and only where) multiple declarations are
6042 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006043 //
John McCall8a726212010-11-29 18:01:58 +00006044 // That's in non-member contexts.
6045 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006046 return false;
6047
6048 NestedNameSpecifier *Qual
6049 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6050
6051 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6052 NamedDecl *D = *I;
6053
6054 bool DTypename;
6055 NestedNameSpecifier *DQual;
6056 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6057 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006058 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006059 } else if (UnresolvedUsingValueDecl *UD
6060 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6061 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006062 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006063 } else if (UnresolvedUsingTypenameDecl *UD
6064 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6065 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006066 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006067 } else continue;
6068
6069 // using decls differ if one says 'typename' and the other doesn't.
6070 // FIXME: non-dependent using decls?
6071 if (isTypeName != DTypename) continue;
6072
6073 // using decls differ if they name different scopes (but note that
6074 // template instantiation can cause this check to trigger when it
6075 // didn't before instantiation).
6076 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6077 Context.getCanonicalNestedNameSpecifier(DQual))
6078 continue;
6079
6080 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006081 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006082 return true;
6083 }
6084
6085 return false;
6086}
6087
John McCall604e7f12009-12-08 07:46:18 +00006088
John McCalled976492009-12-04 22:46:56 +00006089/// Checks that the given nested-name qualifier used in a using decl
6090/// in the current context is appropriately related to the current
6091/// scope. If an error is found, diagnoses it and returns true.
6092bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6093 const CXXScopeSpec &SS,
6094 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006095 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006096
John McCall604e7f12009-12-08 07:46:18 +00006097 if (!CurContext->isRecord()) {
6098 // C++03 [namespace.udecl]p3:
6099 // C++0x [namespace.udecl]p8:
6100 // A using-declaration for a class member shall be a member-declaration.
6101
6102 // If we weren't able to compute a valid scope, it must be a
6103 // dependent class scope.
6104 if (!NamedContext || NamedContext->isRecord()) {
6105 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6106 << SS.getRange();
6107 return true;
6108 }
6109
6110 // Otherwise, everything is known to be fine.
6111 return false;
6112 }
6113
6114 // The current scope is a record.
6115
6116 // If the named context is dependent, we can't decide much.
6117 if (!NamedContext) {
6118 // FIXME: in C++0x, we can diagnose if we can prove that the
6119 // nested-name-specifier does not refer to a base class, which is
6120 // still possible in some cases.
6121
6122 // Otherwise we have to conservatively report that things might be
6123 // okay.
6124 return false;
6125 }
6126
6127 if (!NamedContext->isRecord()) {
6128 // Ideally this would point at the last name in the specifier,
6129 // but we don't have that level of source info.
6130 Diag(SS.getRange().getBegin(),
6131 diag::err_using_decl_nested_name_specifier_is_not_class)
6132 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6133 return true;
6134 }
6135
Douglas Gregor6fb07292010-12-21 07:41:49 +00006136 if (!NamedContext->isDependentContext() &&
6137 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6138 return true;
6139
John McCall604e7f12009-12-08 07:46:18 +00006140 if (getLangOptions().CPlusPlus0x) {
6141 // C++0x [namespace.udecl]p3:
6142 // In a using-declaration used as a member-declaration, the
6143 // nested-name-specifier shall name a base class of the class
6144 // being defined.
6145
6146 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6147 cast<CXXRecordDecl>(NamedContext))) {
6148 if (CurContext == NamedContext) {
6149 Diag(NameLoc,
6150 diag::err_using_decl_nested_name_specifier_is_current_class)
6151 << SS.getRange();
6152 return true;
6153 }
6154
6155 Diag(SS.getRange().getBegin(),
6156 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6157 << (NestedNameSpecifier*) SS.getScopeRep()
6158 << cast<CXXRecordDecl>(CurContext)
6159 << SS.getRange();
6160 return true;
6161 }
6162
6163 return false;
6164 }
6165
6166 // C++03 [namespace.udecl]p4:
6167 // A using-declaration used as a member-declaration shall refer
6168 // to a member of a base class of the class being defined [etc.].
6169
6170 // Salient point: SS doesn't have to name a base class as long as
6171 // lookup only finds members from base classes. Therefore we can
6172 // diagnose here only if we can prove that that can't happen,
6173 // i.e. if the class hierarchies provably don't intersect.
6174
6175 // TODO: it would be nice if "definitely valid" results were cached
6176 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6177 // need to be repeated.
6178
6179 struct UserData {
6180 llvm::DenseSet<const CXXRecordDecl*> Bases;
6181
6182 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6183 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6184 Data->Bases.insert(Base);
6185 return true;
6186 }
6187
6188 bool hasDependentBases(const CXXRecordDecl *Class) {
6189 return !Class->forallBases(collect, this);
6190 }
6191
6192 /// Returns true if the base is dependent or is one of the
6193 /// accumulated base classes.
6194 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6195 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6196 return !Data->Bases.count(Base);
6197 }
6198
6199 bool mightShareBases(const CXXRecordDecl *Class) {
6200 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6201 }
6202 };
6203
6204 UserData Data;
6205
6206 // Returns false if we find a dependent base.
6207 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6208 return false;
6209
6210 // Returns false if the class has a dependent base or if it or one
6211 // of its bases is present in the base set of the current context.
6212 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6213 return false;
6214
6215 Diag(SS.getRange().getBegin(),
6216 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6217 << (NestedNameSpecifier*) SS.getScopeRep()
6218 << cast<CXXRecordDecl>(CurContext)
6219 << SS.getRange();
6220
6221 return true;
John McCalled976492009-12-04 22:46:56 +00006222}
6223
Richard Smith162e1c12011-04-15 14:24:37 +00006224Decl *Sema::ActOnAliasDeclaration(Scope *S,
6225 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006226 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006227 SourceLocation UsingLoc,
6228 UnqualifiedId &Name,
6229 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006230 // Skip up to the relevant declaration scope.
6231 while (S->getFlags() & Scope::TemplateParamScope)
6232 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006233 assert((S->getFlags() & Scope::DeclScope) &&
6234 "got alias-declaration outside of declaration scope");
6235
6236 if (Type.isInvalid())
6237 return 0;
6238
6239 bool Invalid = false;
6240 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6241 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006242 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006243
6244 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6245 return 0;
6246
6247 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006248 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006249 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006250 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6251 TInfo->getTypeLoc().getBeginLoc());
6252 }
Richard Smith162e1c12011-04-15 14:24:37 +00006253
6254 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6255 LookupName(Previous, S);
6256
6257 // Warn about shadowing the name of a template parameter.
6258 if (Previous.isSingleResult() &&
6259 Previous.getFoundDecl()->isTemplateParameter()) {
6260 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6261 Previous.getFoundDecl()))
6262 Invalid = true;
6263 Previous.clear();
6264 }
6265
6266 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6267 "name in alias declaration must be an identifier");
6268 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6269 Name.StartLocation,
6270 Name.Identifier, TInfo);
6271
6272 NewTD->setAccess(AS);
6273
6274 if (Invalid)
6275 NewTD->setInvalidDecl();
6276
Richard Smith3e4c6c42011-05-05 21:57:07 +00006277 CheckTypedefForVariablyModifiedType(S, NewTD);
6278 Invalid |= NewTD->isInvalidDecl();
6279
Richard Smith162e1c12011-04-15 14:24:37 +00006280 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006281
6282 NamedDecl *NewND;
6283 if (TemplateParamLists.size()) {
6284 TypeAliasTemplateDecl *OldDecl = 0;
6285 TemplateParameterList *OldTemplateParams = 0;
6286
6287 if (TemplateParamLists.size() != 1) {
6288 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6289 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6290 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6291 }
6292 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6293
6294 // Only consider previous declarations in the same scope.
6295 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6296 /*ExplicitInstantiationOrSpecialization*/false);
6297 if (!Previous.empty()) {
6298 Redeclaration = true;
6299
6300 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6301 if (!OldDecl && !Invalid) {
6302 Diag(UsingLoc, diag::err_redefinition_different_kind)
6303 << Name.Identifier;
6304
6305 NamedDecl *OldD = Previous.getRepresentativeDecl();
6306 if (OldD->getLocation().isValid())
6307 Diag(OldD->getLocation(), diag::note_previous_definition);
6308
6309 Invalid = true;
6310 }
6311
6312 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6313 if (TemplateParameterListsAreEqual(TemplateParams,
6314 OldDecl->getTemplateParameters(),
6315 /*Complain=*/true,
6316 TPL_TemplateMatch))
6317 OldTemplateParams = OldDecl->getTemplateParameters();
6318 else
6319 Invalid = true;
6320
6321 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6322 if (!Invalid &&
6323 !Context.hasSameType(OldTD->getUnderlyingType(),
6324 NewTD->getUnderlyingType())) {
6325 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6326 // but we can't reasonably accept it.
6327 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6328 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6329 if (OldTD->getLocation().isValid())
6330 Diag(OldTD->getLocation(), diag::note_previous_definition);
6331 Invalid = true;
6332 }
6333 }
6334 }
6335
6336 // Merge any previous default template arguments into our parameters,
6337 // and check the parameter list.
6338 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6339 TPC_TypeAliasTemplate))
6340 return 0;
6341
6342 TypeAliasTemplateDecl *NewDecl =
6343 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6344 Name.Identifier, TemplateParams,
6345 NewTD);
6346
6347 NewDecl->setAccess(AS);
6348
6349 if (Invalid)
6350 NewDecl->setInvalidDecl();
6351 else if (OldDecl)
6352 NewDecl->setPreviousDeclaration(OldDecl);
6353
6354 NewND = NewDecl;
6355 } else {
6356 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6357 NewND = NewTD;
6358 }
Richard Smith162e1c12011-04-15 14:24:37 +00006359
6360 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006361 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006362
Richard Smith3e4c6c42011-05-05 21:57:07 +00006363 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006364}
6365
John McCalld226f652010-08-21 09:40:31 +00006366Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006367 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006368 SourceLocation AliasLoc,
6369 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006370 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006371 SourceLocation IdentLoc,
6372 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006373
Anders Carlsson81c85c42009-03-28 23:53:49 +00006374 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006375 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6376 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006377
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006378 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006379 NamedDecl *PrevDecl
6380 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6381 ForRedeclaration);
6382 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6383 PrevDecl = 0;
6384
6385 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006386 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006387 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006388 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006389 // FIXME: At some point, we'll want to create the (redundant)
6390 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006391 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006392 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006393 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006394 }
Mike Stump1eb44332009-09-09 15:08:12 +00006395
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006396 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6397 diag::err_redefinition_different_kind;
6398 Diag(AliasLoc, DiagID) << Alias;
6399 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006400 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006401 }
6402
John McCalla24dc2e2009-11-17 02:14:36 +00006403 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006404 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006405
John McCallf36e02d2009-10-09 21:13:30 +00006406 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006407 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006408 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006409 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006410 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006411 }
Mike Stump1eb44332009-09-09 15:08:12 +00006412
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006413 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006414 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006415 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006416 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006417
John McCall3dbd3d52010-02-16 06:53:13 +00006418 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006419 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006420}
6421
Douglas Gregor39957dc2010-05-01 15:04:51 +00006422namespace {
6423 /// \brief Scoped object used to handle the state changes required in Sema
6424 /// to implicitly define the body of a C++ member function;
6425 class ImplicitlyDefinedFunctionScope {
6426 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006427 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006428
6429 public:
6430 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006431 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006432 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006433 S.PushFunctionScope();
6434 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6435 }
6436
6437 ~ImplicitlyDefinedFunctionScope() {
6438 S.PopExpressionEvaluationContext();
6439 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006440 }
6441 };
6442}
6443
Sean Hunt001cad92011-05-10 00:49:42 +00006444Sema::ImplicitExceptionSpecification
6445Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006446 // C++ [except.spec]p14:
6447 // An implicitly declared special member function (Clause 12) shall have an
6448 // exception-specification. [...]
6449 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006450 if (ClassDecl->isInvalidDecl())
6451 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006452
Sebastian Redl60618fa2011-03-12 11:50:43 +00006453 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006454 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6455 BEnd = ClassDecl->bases_end();
6456 B != BEnd; ++B) {
6457 if (B->isVirtual()) // Handled below.
6458 continue;
6459
Douglas Gregor18274032010-07-03 00:47:00 +00006460 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6461 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006462 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6463 // If this is a deleted function, add it anyway. This might be conformant
6464 // with the standard. This might not. I'm not sure. It might not matter.
6465 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006466 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006467 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006468 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006469
6470 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006471 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6472 BEnd = ClassDecl->vbases_end();
6473 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006474 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6475 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006476 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6477 // If this is a deleted function, add it anyway. This might be conformant
6478 // with the standard. This might not. I'm not sure. It might not matter.
6479 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006480 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006481 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006482 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006483
6484 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006485 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6486 FEnd = ClassDecl->field_end();
6487 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006488 if (F->hasInClassInitializer()) {
6489 if (Expr *E = F->getInClassInitializer())
6490 ExceptSpec.CalledExpr(E);
6491 else if (!F->isInvalidDecl())
6492 ExceptSpec.SetDelayed();
6493 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006494 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006495 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6496 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6497 // If this is a deleted function, add it anyway. This might be conformant
6498 // with the standard. This might not. I'm not sure. It might not matter.
6499 // In particular, the problem is that this function never gets called. It
6500 // might just be ill-formed because this function attempts to refer to
6501 // a deleted function here.
6502 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006503 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006504 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006505 }
John McCalle23cf432010-12-14 08:05:40 +00006506
Sean Hunt001cad92011-05-10 00:49:42 +00006507 return ExceptSpec;
6508}
6509
6510CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6511 CXXRecordDecl *ClassDecl) {
6512 // C++ [class.ctor]p5:
6513 // A default constructor for a class X is a constructor of class X
6514 // that can be called without an argument. If there is no
6515 // user-declared constructor for class X, a default constructor is
6516 // implicitly declared. An implicitly-declared default constructor
6517 // is an inline public member of its class.
6518 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6519 "Should not build implicit default constructor!");
6520
6521 ImplicitExceptionSpecification Spec =
6522 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6523 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006524
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006525 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006526 CanQualType ClassType
6527 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006528 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006529 DeclarationName Name
6530 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006531 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006532 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006533 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00006534 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00006535 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00006536 /*TInfo=*/0,
6537 /*isExplicit=*/false,
6538 /*isInline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006539 /*isImplicitlyDeclared=*/true,
6540 // FIXME: apply the rules for definitions here
6541 /*isConstexpr=*/false);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006542 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006543 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006544 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006545 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006546
6547 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006548 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6549
Douglas Gregor23c94db2010-07-02 17:43:08 +00006550 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006551 PushOnScopeChains(DefaultCon, S, false);
6552 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006553
6554 if (ShouldDeleteDefaultConstructor(DefaultCon))
6555 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006556
Douglas Gregor32df23e2010-07-01 22:02:46 +00006557 return DefaultCon;
6558}
6559
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006560void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6561 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006562 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006563 !Constructor->doesThisDeclarationHaveABody() &&
6564 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006565 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006566
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006567 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006568 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006569
Douglas Gregor39957dc2010-05-01 15:04:51 +00006570 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006571 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006572 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006573 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006574 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006575 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006576 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006577 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006578 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006579
6580 SourceLocation Loc = Constructor->getLocation();
6581 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6582
6583 Constructor->setUsed();
6584 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006585
6586 if (ASTMutationListener *L = getASTMutationListener()) {
6587 L->CompletedImplicitDefinition(Constructor);
6588 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006589}
6590
Richard Smith7a614d82011-06-11 17:19:42 +00006591/// Get any existing defaulted default constructor for the given class. Do not
6592/// implicitly define one if it does not exist.
6593static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6594 CXXRecordDecl *D) {
6595 ASTContext &Context = Self.Context;
6596 QualType ClassType = Context.getTypeDeclType(D);
6597 DeclarationName ConstructorName
6598 = Context.DeclarationNames.getCXXConstructorName(
6599 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6600
6601 DeclContext::lookup_const_iterator Con, ConEnd;
6602 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6603 Con != ConEnd; ++Con) {
6604 // A function template cannot be defaulted.
6605 if (isa<FunctionTemplateDecl>(*Con))
6606 continue;
6607
6608 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6609 if (Constructor->isDefaultConstructor())
6610 return Constructor->isDefaulted() ? Constructor : 0;
6611 }
6612 return 0;
6613}
6614
6615void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6616 if (!D) return;
6617 AdjustDeclIfTemplate(D);
6618
6619 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6620 CXXConstructorDecl *CtorDecl
6621 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6622
6623 if (!CtorDecl) return;
6624
6625 // Compute the exception specification for the default constructor.
6626 const FunctionProtoType *CtorTy =
6627 CtorDecl->getType()->castAs<FunctionProtoType>();
6628 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6629 ImplicitExceptionSpecification Spec =
6630 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6631 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6632 assert(EPI.ExceptionSpecType != EST_Delayed);
6633
6634 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6635 }
6636
6637 // If the default constructor is explicitly defaulted, checking the exception
6638 // specification is deferred until now.
6639 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6640 !ClassDecl->isDependentType())
6641 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6642}
6643
Sebastian Redlf677ea32011-02-05 19:23:19 +00006644void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6645 // We start with an initial pass over the base classes to collect those that
6646 // inherit constructors from. If there are none, we can forgo all further
6647 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006648 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006649 BasesVector BasesToInheritFrom;
6650 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6651 BaseE = ClassDecl->bases_end();
6652 BaseIt != BaseE; ++BaseIt) {
6653 if (BaseIt->getInheritConstructors()) {
6654 QualType Base = BaseIt->getType();
6655 if (Base->isDependentType()) {
6656 // If we inherit constructors from anything that is dependent, just
6657 // abort processing altogether. We'll get another chance for the
6658 // instantiations.
6659 return;
6660 }
6661 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6662 }
6663 }
6664 if (BasesToInheritFrom.empty())
6665 return;
6666
6667 // Now collect the constructors that we already have in the current class.
6668 // Those take precedence over inherited constructors.
6669 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6670 // unless there is a user-declared constructor with the same signature in
6671 // the class where the using-declaration appears.
6672 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6673 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6674 CtorE = ClassDecl->ctor_end();
6675 CtorIt != CtorE; ++CtorIt) {
6676 ExistingConstructors.insert(
6677 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6678 }
6679
6680 Scope *S = getScopeForContext(ClassDecl);
6681 DeclarationName CreatedCtorName =
6682 Context.DeclarationNames.getCXXConstructorName(
6683 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6684
6685 // Now comes the true work.
6686 // First, we keep a map from constructor types to the base that introduced
6687 // them. Needed for finding conflicting constructors. We also keep the
6688 // actually inserted declarations in there, for pretty diagnostics.
6689 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6690 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6691 ConstructorToSourceMap InheritedConstructors;
6692 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6693 BaseE = BasesToInheritFrom.end();
6694 BaseIt != BaseE; ++BaseIt) {
6695 const RecordType *Base = *BaseIt;
6696 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6697 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6698 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6699 CtorE = BaseDecl->ctor_end();
6700 CtorIt != CtorE; ++CtorIt) {
6701 // Find the using declaration for inheriting this base's constructors.
6702 DeclarationName Name =
6703 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6704 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6705 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6706 SourceLocation UsingLoc = UD ? UD->getLocation() :
6707 ClassDecl->getLocation();
6708
6709 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6710 // from the class X named in the using-declaration consists of actual
6711 // constructors and notional constructors that result from the
6712 // transformation of defaulted parameters as follows:
6713 // - all non-template default constructors of X, and
6714 // - for each non-template constructor of X that has at least one
6715 // parameter with a default argument, the set of constructors that
6716 // results from omitting any ellipsis parameter specification and
6717 // successively omitting parameters with a default argument from the
6718 // end of the parameter-type-list.
6719 CXXConstructorDecl *BaseCtor = *CtorIt;
6720 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6721 const FunctionProtoType *BaseCtorType =
6722 BaseCtor->getType()->getAs<FunctionProtoType>();
6723
6724 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6725 maxParams = BaseCtor->getNumParams();
6726 params <= maxParams; ++params) {
6727 // Skip default constructors. They're never inherited.
6728 if (params == 0)
6729 continue;
6730 // Skip copy and move constructors for the same reason.
6731 if (CanBeCopyOrMove && params == 1)
6732 continue;
6733
6734 // Build up a function type for this particular constructor.
6735 // FIXME: The working paper does not consider that the exception spec
6736 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006737 // source. This code doesn't yet, either. When it does, this code will
6738 // need to be delayed until after exception specifications and in-class
6739 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006740 const Type *NewCtorType;
6741 if (params == maxParams)
6742 NewCtorType = BaseCtorType;
6743 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006744 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006745 for (unsigned i = 0; i < params; ++i) {
6746 Args.push_back(BaseCtorType->getArgType(i));
6747 }
6748 FunctionProtoType::ExtProtoInfo ExtInfo =
6749 BaseCtorType->getExtProtoInfo();
6750 ExtInfo.Variadic = false;
6751 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6752 Args.data(), params, ExtInfo)
6753 .getTypePtr();
6754 }
6755 const Type *CanonicalNewCtorType =
6756 Context.getCanonicalType(NewCtorType);
6757
6758 // Now that we have the type, first check if the class already has a
6759 // constructor with this signature.
6760 if (ExistingConstructors.count(CanonicalNewCtorType))
6761 continue;
6762
6763 // Then we check if we have already declared an inherited constructor
6764 // with this signature.
6765 std::pair<ConstructorToSourceMap::iterator, bool> result =
6766 InheritedConstructors.insert(std::make_pair(
6767 CanonicalNewCtorType,
6768 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6769 if (!result.second) {
6770 // Already in the map. If it came from a different class, that's an
6771 // error. Not if it's from the same.
6772 CanQualType PreviousBase = result.first->second.first;
6773 if (CanonicalBase != PreviousBase) {
6774 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6775 const CXXConstructorDecl *PrevBaseCtor =
6776 PrevCtor->getInheritedConstructor();
6777 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6778
6779 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6780 Diag(BaseCtor->getLocation(),
6781 diag::note_using_decl_constructor_conflict_current_ctor);
6782 Diag(PrevBaseCtor->getLocation(),
6783 diag::note_using_decl_constructor_conflict_previous_ctor);
6784 Diag(PrevCtor->getLocation(),
6785 diag::note_using_decl_constructor_conflict_previous_using);
6786 }
6787 continue;
6788 }
6789
6790 // OK, we're there, now add the constructor.
6791 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006792 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00006793 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6794 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006795 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6796 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006797 /*ImplicitlyDeclared=*/true,
6798 // FIXME: Due to a defect in the standard, we treat inherited
6799 // constructors as constexpr even if that makes them ill-formed.
6800 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00006801 NewCtor->setAccess(BaseCtor->getAccess());
6802
6803 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006804 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006805 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006806 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6807 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006808 /*IdentifierInfo=*/0,
6809 BaseCtorType->getArgType(i),
6810 /*TInfo=*/0, SC_None,
6811 SC_None, /*DefaultArg=*/0));
6812 }
6813 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6814 NewCtor->setInheritedConstructor(BaseCtor);
6815
6816 PushOnScopeChains(NewCtor, S, false);
6817 ClassDecl->addDecl(NewCtor);
6818 result.first->second.second = NewCtor;
6819 }
6820 }
6821 }
6822}
6823
Sean Huntcb45a0f2011-05-12 22:46:25 +00006824Sema::ImplicitExceptionSpecification
6825Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006826 // C++ [except.spec]p14:
6827 // An implicitly declared special member function (Clause 12) shall have
6828 // an exception-specification.
6829 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006830 if (ClassDecl->isInvalidDecl())
6831 return ExceptSpec;
6832
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006833 // Direct base-class destructors.
6834 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6835 BEnd = ClassDecl->bases_end();
6836 B != BEnd; ++B) {
6837 if (B->isVirtual()) // Handled below.
6838 continue;
6839
6840 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6841 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006842 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006843 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006844
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006845 // Virtual base-class destructors.
6846 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6847 BEnd = ClassDecl->vbases_end();
6848 B != BEnd; ++B) {
6849 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6850 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006851 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006852 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006853
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006854 // Field destructors.
6855 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6856 FEnd = ClassDecl->field_end();
6857 F != FEnd; ++F) {
6858 if (const RecordType *RecordTy
6859 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6860 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006861 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006862 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006863
Sean Huntcb45a0f2011-05-12 22:46:25 +00006864 return ExceptSpec;
6865}
6866
6867CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6868 // C++ [class.dtor]p2:
6869 // If a class has no user-declared destructor, a destructor is
6870 // declared implicitly. An implicitly-declared destructor is an
6871 // inline public member of its class.
6872
6873 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00006874 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006875 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6876
Douglas Gregor4923aa22010-07-02 20:37:36 +00006877 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00006878 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00006879
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006880 CanQualType ClassType
6881 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006882 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006883 DeclarationName Name
6884 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006885 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006886 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00006887 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6888 /*isInline=*/true,
6889 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006890 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006891 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006892 Destructor->setImplicit();
6893 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00006894
6895 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00006896 ++ASTContext::NumImplicitDestructorsDeclared;
6897
6898 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006899 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00006900 PushOnScopeChains(Destructor, S, false);
6901 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006902
6903 // This could be uniqued if it ever proves significant.
6904 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00006905
6906 if (ShouldDeleteDestructor(Destructor))
6907 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006908
6909 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00006910
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006911 return Destructor;
6912}
6913
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006914void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00006915 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00006916 assert((Destructor->isDefaulted() &&
6917 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006918 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00006919 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006920 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006921
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006922 if (Destructor->isInvalidDecl())
6923 return;
6924
Douglas Gregor39957dc2010-05-01 15:04:51 +00006925 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006926
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006927 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00006928 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6929 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00006930
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006931 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006932 Diag(CurrentLocation, diag::note_member_synthesized_at)
6933 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6934
6935 Destructor->setInvalidDecl();
6936 return;
6937 }
6938
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006939 SourceLocation Loc = Destructor->getLocation();
6940 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6941
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006942 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006943 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006944
6945 if (ASTMutationListener *L = getASTMutationListener()) {
6946 L->CompletedImplicitDefinition(Destructor);
6947 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006948}
6949
Sebastian Redl0ee33912011-05-19 05:13:44 +00006950void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6951 CXXDestructorDecl *destructor) {
6952 // C++11 [class.dtor]p3:
6953 // A declaration of a destructor that does not have an exception-
6954 // specification is implicitly considered to have the same exception-
6955 // specification as an implicit declaration.
6956 const FunctionProtoType *dtorType = destructor->getType()->
6957 getAs<FunctionProtoType>();
6958 if (dtorType->hasExceptionSpec())
6959 return;
6960
6961 ImplicitExceptionSpecification exceptSpec =
6962 ComputeDefaultedDtorExceptionSpec(classDecl);
6963
6964 // Replace the destructor's type.
6965 FunctionProtoType::ExtProtoInfo epi;
6966 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6967 epi.NumExceptions = exceptSpec.size();
6968 epi.Exceptions = exceptSpec.data();
6969 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6970
6971 destructor->setType(ty);
6972
6973 // FIXME: If the destructor has a body that could throw, and the newly created
6974 // spec doesn't allow exceptions, we should emit a warning, because this
6975 // change in behavior can break conforming C++03 programs at runtime.
6976 // However, we don't have a body yet, so it needs to be done somewhere else.
6977}
6978
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006979/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00006980/// \c To.
6981///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006982/// This routine is used to copy/move the members of a class with an
6983/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00006984/// copied are arrays, this routine builds for loops to copy them.
6985///
6986/// \param S The Sema object used for type-checking.
6987///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006988/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00006989///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006990/// \param T The type of the expressions being copied/moved. Both expressions
6991/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00006992///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006993/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00006994///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006995/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00006996///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006997/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006998/// Otherwise, it's a non-static member subobject.
6999///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007000/// \param Copying Whether we're copying or moving.
7001///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007002/// \param Depth Internal parameter recording the depth of the recursion.
7003///
7004/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007005static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007006BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007007 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007008 bool CopyingBaseSubobject, bool Copying,
7009 unsigned Depth = 0) {
7010 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007011 // Each subobject is assigned in the manner appropriate to its type:
7012 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007013 // - if the subobject is of class type, as if by a call to operator= with
7014 // the subobject as the object expression and the corresponding
7015 // subobject of x as a single function argument (as if by explicit
7016 // qualification; that is, ignoring any possible virtual overriding
7017 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007018 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7019 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7020
7021 // Look for operator=.
7022 DeclarationName Name
7023 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7024 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7025 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7026
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007027 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007028 LookupResult::Filter F = OpLookup.makeFilter();
7029 while (F.hasNext()) {
7030 NamedDecl *D = F.next();
7031 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007032 if (Copying ? Method->isCopyAssignmentOperator() :
7033 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007034 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007035
Douglas Gregor06a9f362010-05-01 20:49:11 +00007036 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007037 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007038 F.done();
7039
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007040 // Suppress the protected check (C++ [class.protected]) for each of the
7041 // assignment operators we found. This strange dance is required when
7042 // we're assigning via a base classes's copy-assignment operator. To
7043 // ensure that we're getting the right base class subobject (without
7044 // ambiguities), we need to cast "this" to that subobject type; to
7045 // ensure that we don't go through the virtual call mechanism, we need
7046 // to qualify the operator= name with the base class (see below). However,
7047 // this means that if the base class has a protected copy assignment
7048 // operator, the protected member access check will fail. So, we
7049 // rewrite "protected" access to "public" access in this case, since we
7050 // know by construction that we're calling from a derived class.
7051 if (CopyingBaseSubobject) {
7052 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7053 L != LEnd; ++L) {
7054 if (L.getAccess() == AS_protected)
7055 L.setAccess(AS_public);
7056 }
7057 }
7058
Douglas Gregor06a9f362010-05-01 20:49:11 +00007059 // Create the nested-name-specifier that will be used to qualify the
7060 // reference to operator=; this is required to suppress the virtual
7061 // call mechanism.
7062 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00007063 SS.MakeTrivial(S.Context,
7064 NestedNameSpecifier::Create(S.Context, 0, false,
7065 T.getTypePtr()),
7066 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007067
7068 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007069 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007070 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007071 /*FirstQualifierInScope=*/0, OpLookup,
7072 /*TemplateArgs=*/0,
7073 /*SuppressQualifierCheck=*/true);
7074 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007075 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007076
7077 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007078
John McCall60d7b3a2010-08-24 06:29:42 +00007079 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007080 OpEqualRef.takeAs<Expr>(),
7081 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007082 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007083 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007084
7085 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007086 }
John McCallb0207482010-03-16 06:11:48 +00007087
Douglas Gregor06a9f362010-05-01 20:49:11 +00007088 // - if the subobject is of scalar type, the built-in assignment
7089 // operator is used.
7090 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7091 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007092 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007093 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007094 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007095
7096 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007097 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007098
7099 // - if the subobject is an array, each element is assigned, in the
7100 // manner appropriate to the element type;
7101
7102 // Construct a loop over the array bounds, e.g.,
7103 //
7104 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7105 //
7106 // that will copy each of the array elements.
7107 QualType SizeType = S.Context.getSizeType();
7108
7109 // Create the iteration variable.
7110 IdentifierInfo *IterationVarName = 0;
7111 {
7112 llvm::SmallString<8> Str;
7113 llvm::raw_svector_ostream OS(Str);
7114 OS << "__i" << Depth;
7115 IterationVarName = &S.Context.Idents.get(OS.str());
7116 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007117 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007118 IterationVarName, SizeType,
7119 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007120 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007121
7122 // Initialize the iteration variable to zero.
7123 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007124 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007125
7126 // Create a reference to the iteration variable; we'll use this several
7127 // times throughout.
7128 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00007129 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007130 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7131
7132 // Create the DeclStmt that holds the iteration variable.
7133 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7134
7135 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007136 llvm::APInt Upper
7137 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007138 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00007139 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00007140 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7141 BO_NE, S.Context.BoolTy,
7142 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007143
7144 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007145 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007146 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7147 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007148
7149 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007150 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7151 IterationVarRef, Loc));
7152 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7153 IterationVarRef, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007154 if (!Copying) // Cast to rvalue
7155 From = CastForMoving(S, From);
7156
7157 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007158 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7159 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007160 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007161 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007162 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007163
7164 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007165 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007166 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007167 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007168 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007169}
7170
Sean Hunt30de05c2011-05-14 05:23:20 +00007171std::pair<Sema::ImplicitExceptionSpecification, bool>
7172Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7173 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007174 if (ClassDecl->isInvalidDecl())
7175 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7176
Douglas Gregord3c35902010-07-01 16:36:15 +00007177 // C++ [class.copy]p10:
7178 // If the class definition does not explicitly declare a copy
7179 // assignment operator, one is declared implicitly.
7180 // The implicitly-defined copy assignment operator for a class X
7181 // will have the form
7182 //
7183 // X& X::operator=(const X&)
7184 //
7185 // if
7186 bool HasConstCopyAssignment = true;
7187
7188 // -- each direct base class B of X has a copy assignment operator
7189 // whose parameter is of type const B&, const volatile B& or B,
7190 // and
7191 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7192 BaseEnd = ClassDecl->bases_end();
7193 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007194 // We'll handle this below
7195 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7196 continue;
7197
Douglas Gregord3c35902010-07-01 16:36:15 +00007198 assert(!Base->getType()->isDependentType() &&
7199 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007200 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7201 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7202 &HasConstCopyAssignment);
7203 }
7204
7205 // In C++0x, the above citation has "or virtual added"
7206 if (LangOpts.CPlusPlus0x) {
7207 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7208 BaseEnd = ClassDecl->vbases_end();
7209 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7210 assert(!Base->getType()->isDependentType() &&
7211 "Cannot generate implicit members for class with dependent bases.");
7212 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7213 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7214 &HasConstCopyAssignment);
7215 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007216 }
7217
7218 // -- for all the nonstatic data members of X that are of a class
7219 // type M (or array thereof), each such class type has a copy
7220 // assignment operator whose parameter is of type const M&,
7221 // const volatile M& or M.
7222 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7223 FieldEnd = ClassDecl->field_end();
7224 HasConstCopyAssignment && Field != FieldEnd;
7225 ++Field) {
7226 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007227 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7228 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7229 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007230 }
7231 }
7232
7233 // Otherwise, the implicitly declared copy assignment operator will
7234 // have the form
7235 //
7236 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007237
Douglas Gregorb87786f2010-07-01 17:48:08 +00007238 // C++ [except.spec]p14:
7239 // An implicitly declared special member function (Clause 12) shall have an
7240 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007241
7242 // It is unspecified whether or not an implicit copy assignment operator
7243 // attempts to deduplicate calls to assignment operators of virtual bases are
7244 // made. As such, this exception specification is effectively unspecified.
7245 // Based on a similar decision made for constness in C++0x, we're erring on
7246 // the side of assuming such calls to be made regardless of whether they
7247 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007248 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007249 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007250 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7251 BaseEnd = ClassDecl->bases_end();
7252 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007253 if (Base->isVirtual())
7254 continue;
7255
Douglas Gregora376d102010-07-02 21:50:04 +00007256 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007257 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007258 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7259 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007260 ExceptSpec.CalledDecl(CopyAssign);
7261 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007262
7263 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7264 BaseEnd = ClassDecl->vbases_end();
7265 Base != BaseEnd; ++Base) {
7266 CXXRecordDecl *BaseClassDecl
7267 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7268 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7269 ArgQuals, false, 0))
7270 ExceptSpec.CalledDecl(CopyAssign);
7271 }
7272
Douglas Gregorb87786f2010-07-01 17:48:08 +00007273 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7274 FieldEnd = ClassDecl->field_end();
7275 Field != FieldEnd;
7276 ++Field) {
7277 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007278 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7279 if (CXXMethodDecl *CopyAssign =
7280 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7281 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007282 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007283 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007284
Sean Hunt30de05c2011-05-14 05:23:20 +00007285 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7286}
7287
7288CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7289 // Note: The following rules are largely analoguous to the copy
7290 // constructor rules. Note that virtual bases are not taken into account
7291 // for determining the argument type of the operator. Note also that
7292 // operators taking an object instead of a reference are allowed.
7293
7294 ImplicitExceptionSpecification Spec(Context);
7295 bool Const;
7296 llvm::tie(Spec, Const) =
7297 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7298
7299 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7300 QualType RetType = Context.getLValueReferenceType(ArgType);
7301 if (Const)
7302 ArgType = ArgType.withConst();
7303 ArgType = Context.getLValueReferenceType(ArgType);
7304
Douglas Gregord3c35902010-07-01 16:36:15 +00007305 // An implicitly-declared copy assignment operator is an inline public
7306 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007307 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007308 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007309 SourceLocation ClassLoc = ClassDecl->getLocation();
7310 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007311 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007312 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007313 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007314 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007315 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007316 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007317 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007318 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007319 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007320 CopyAssignment->setImplicit();
7321 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007322
7323 // Add the parameter to the operator.
7324 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007325 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007326 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007327 SC_None,
7328 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00007329 CopyAssignment->setParams(&FromParam, 1);
7330
Douglas Gregora376d102010-07-02 21:50:04 +00007331 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007332 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007333
Douglas Gregor23c94db2010-07-02 17:43:08 +00007334 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007335 PushOnScopeChains(CopyAssignment, S, false);
7336 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007337
Sean Hunt1ccbc542011-06-22 01:05:13 +00007338 // C++0x [class.copy]p18:
7339 // ... If the class definition declares a move constructor or move
7340 // assignment operator, the implicitly declared copy assignment operator is
7341 // defined as deleted; ...
7342 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7343 ClassDecl->hasUserDeclaredMoveAssignment() ||
7344 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007345 CopyAssignment->setDeletedAsWritten();
7346
Douglas Gregord3c35902010-07-01 16:36:15 +00007347 AddOverriddenMethods(ClassDecl, CopyAssignment);
7348 return CopyAssignment;
7349}
7350
Douglas Gregor06a9f362010-05-01 20:49:11 +00007351void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7352 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007353 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007354 CopyAssignOperator->isOverloadedOperator() &&
7355 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007356 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007357 "DefineImplicitCopyAssignment called for wrong function");
7358
7359 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7360
7361 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7362 CopyAssignOperator->setInvalidDecl();
7363 return;
7364 }
7365
7366 CopyAssignOperator->setUsed();
7367
7368 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007369 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007370
7371 // C++0x [class.copy]p30:
7372 // The implicitly-defined or explicitly-defaulted copy assignment operator
7373 // for a non-union class X performs memberwise copy assignment of its
7374 // subobjects. The direct base classes of X are assigned first, in the
7375 // order of their declaration in the base-specifier-list, and then the
7376 // immediate non-static data members of X are assigned, in the order in
7377 // which they were declared in the class definition.
7378
7379 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007380 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007381
7382 // The parameter for the "other" object, which we are copying from.
7383 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7384 Qualifiers OtherQuals = Other->getType().getQualifiers();
7385 QualType OtherRefType = Other->getType();
7386 if (const LValueReferenceType *OtherRef
7387 = OtherRefType->getAs<LValueReferenceType>()) {
7388 OtherRefType = OtherRef->getPointeeType();
7389 OtherQuals = OtherRefType.getQualifiers();
7390 }
7391
7392 // Our location for everything implicitly-generated.
7393 SourceLocation Loc = CopyAssignOperator->getLocation();
7394
7395 // Construct a reference to the "other" object. We'll be using this
7396 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007397 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007398 assert(OtherRef && "Reference to parameter cannot fail!");
7399
7400 // Construct the "this" pointer. We'll be using this throughout the generated
7401 // ASTs.
7402 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7403 assert(This && "Reference to this cannot fail!");
7404
7405 // Assign base classes.
7406 bool Invalid = false;
7407 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7408 E = ClassDecl->bases_end(); Base != E; ++Base) {
7409 // Form the assignment:
7410 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7411 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007412 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007413 Invalid = true;
7414 continue;
7415 }
7416
John McCallf871d0c2010-08-07 06:22:56 +00007417 CXXCastPath BasePath;
7418 BasePath.push_back(Base);
7419
Douglas Gregor06a9f362010-05-01 20:49:11 +00007420 // Construct the "from" expression, which is an implicit cast to the
7421 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007422 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007423 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7424 CK_UncheckedDerivedToBase,
7425 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007426
7427 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007428 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007429
7430 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007431 To = ImpCastExprToType(To.take(),
7432 Context.getCVRQualifiedType(BaseType,
7433 CopyAssignOperator->getTypeQualifiers()),
7434 CK_UncheckedDerivedToBase,
7435 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007436
7437 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007438 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007439 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007440 /*CopyingBaseSubobject=*/true,
7441 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007442 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007443 Diag(CurrentLocation, diag::note_member_synthesized_at)
7444 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7445 CopyAssignOperator->setInvalidDecl();
7446 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007447 }
7448
7449 // Success! Record the copy.
7450 Statements.push_back(Copy.takeAs<Expr>());
7451 }
7452
7453 // \brief Reference to the __builtin_memcpy function.
7454 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007455 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007456 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007457
7458 // Assign non-static members.
7459 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7460 FieldEnd = ClassDecl->field_end();
7461 Field != FieldEnd; ++Field) {
7462 // Check for members of reference type; we can't copy those.
7463 if (Field->getType()->isReferenceType()) {
7464 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7465 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7466 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007467 Diag(CurrentLocation, diag::note_member_synthesized_at)
7468 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007469 Invalid = true;
7470 continue;
7471 }
7472
7473 // Check for members of const-qualified, non-class type.
7474 QualType BaseType = Context.getBaseElementType(Field->getType());
7475 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7476 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7477 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7478 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007479 Diag(CurrentLocation, diag::note_member_synthesized_at)
7480 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007481 Invalid = true;
7482 continue;
7483 }
John McCallb77115d2011-06-17 00:18:42 +00007484
7485 // Suppress assigning zero-width bitfields.
7486 if (const Expr *Width = Field->getBitWidth())
7487 if (Width->EvaluateAsInt(Context) == 0)
7488 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007489
7490 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007491 if (FieldType->isIncompleteArrayType()) {
7492 assert(ClassDecl->hasFlexibleArrayMember() &&
7493 "Incomplete array type is not valid");
7494 continue;
7495 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007496
7497 // Build references to the field in the object we're copying from and to.
7498 CXXScopeSpec SS; // Intentionally empty
7499 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7500 LookupMemberName);
7501 MemberLookup.addDecl(*Field);
7502 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007503 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007504 Loc, /*IsArrow=*/false,
7505 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007506 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007507 Loc, /*IsArrow=*/true,
7508 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007509 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7510 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7511
7512 // If the field should be copied with __builtin_memcpy rather than via
7513 // explicit assignments, do so. This optimization only applies for arrays
7514 // of scalars and arrays of class type with trivial copy-assignment
7515 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007516 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007517 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007518 // Compute the size of the memory buffer to be copied.
7519 QualType SizeType = Context.getSizeType();
7520 llvm::APInt Size(Context.getTypeSize(SizeType),
7521 Context.getTypeSizeInChars(BaseType).getQuantity());
7522 for (const ConstantArrayType *Array
7523 = Context.getAsConstantArrayType(FieldType);
7524 Array;
7525 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007526 llvm::APInt ArraySize
7527 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007528 Size *= ArraySize;
7529 }
7530
7531 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007532 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7533 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007534
7535 bool NeedsCollectableMemCpy =
7536 (BaseType->isRecordType() &&
7537 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7538
7539 if (NeedsCollectableMemCpy) {
7540 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007541 // Create a reference to the __builtin_objc_memmove_collectable function.
7542 LookupResult R(*this,
7543 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007544 Loc, LookupOrdinaryName);
7545 LookupName(R, TUScope, true);
7546
7547 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7548 if (!CollectableMemCpy) {
7549 // Something went horribly wrong earlier, and we will have
7550 // complained about it.
7551 Invalid = true;
7552 continue;
7553 }
7554
7555 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7556 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007557 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007558 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7559 }
7560 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007561 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007562 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007563 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7564 LookupOrdinaryName);
7565 LookupName(R, TUScope, true);
7566
7567 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7568 if (!BuiltinMemCpy) {
7569 // Something went horribly wrong earlier, and we will have complained
7570 // about it.
7571 Invalid = true;
7572 continue;
7573 }
7574
7575 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7576 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007577 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007578 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7579 }
7580
John McCallca0408f2010-08-23 06:44:23 +00007581 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007582 CallArgs.push_back(To.takeAs<Expr>());
7583 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007584 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007585 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007586 if (NeedsCollectableMemCpy)
7587 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007588 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007589 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007590 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007591 else
7592 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007593 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007594 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007595 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007596
Douglas Gregor06a9f362010-05-01 20:49:11 +00007597 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7598 Statements.push_back(Call.takeAs<Expr>());
7599 continue;
7600 }
7601
7602 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007603 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007604 To.get(), From.get(),
7605 /*CopyingBaseSubobject=*/false,
7606 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007607 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007608 Diag(CurrentLocation, diag::note_member_synthesized_at)
7609 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7610 CopyAssignOperator->setInvalidDecl();
7611 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007612 }
7613
7614 // Success! Record the copy.
7615 Statements.push_back(Copy.takeAs<Stmt>());
7616 }
7617
7618 if (!Invalid) {
7619 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007620 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007621
John McCall60d7b3a2010-08-24 06:29:42 +00007622 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007623 if (Return.isInvalid())
7624 Invalid = true;
7625 else {
7626 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007627
7628 if (Trap.hasErrorOccurred()) {
7629 Diag(CurrentLocation, diag::note_member_synthesized_at)
7630 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7631 Invalid = true;
7632 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007633 }
7634 }
7635
7636 if (Invalid) {
7637 CopyAssignOperator->setInvalidDecl();
7638 return;
7639 }
7640
John McCall60d7b3a2010-08-24 06:29:42 +00007641 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00007642 /*isStmtExpr=*/false);
7643 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7644 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007645
7646 if (ASTMutationListener *L = getASTMutationListener()) {
7647 L->CompletedImplicitDefinition(CopyAssignOperator);
7648 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007649}
7650
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007651Sema::ImplicitExceptionSpecification
7652Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7653 ImplicitExceptionSpecification ExceptSpec(Context);
7654
7655 if (ClassDecl->isInvalidDecl())
7656 return ExceptSpec;
7657
7658 // C++0x [except.spec]p14:
7659 // An implicitly declared special member function (Clause 12) shall have an
7660 // exception-specification. [...]
7661
7662 // It is unspecified whether or not an implicit move assignment operator
7663 // attempts to deduplicate calls to assignment operators of virtual bases are
7664 // made. As such, this exception specification is effectively unspecified.
7665 // Based on a similar decision made for constness in C++0x, we're erring on
7666 // the side of assuming such calls to be made regardless of whether they
7667 // actually happen.
7668 // Note that a move constructor is not implicitly declared when there are
7669 // virtual bases, but it can still be user-declared and explicitly defaulted.
7670 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7671 BaseEnd = ClassDecl->bases_end();
7672 Base != BaseEnd; ++Base) {
7673 if (Base->isVirtual())
7674 continue;
7675
7676 CXXRecordDecl *BaseClassDecl
7677 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7678 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7679 false, 0))
7680 ExceptSpec.CalledDecl(MoveAssign);
7681 }
7682
7683 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7684 BaseEnd = ClassDecl->vbases_end();
7685 Base != BaseEnd; ++Base) {
7686 CXXRecordDecl *BaseClassDecl
7687 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7688 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7689 false, 0))
7690 ExceptSpec.CalledDecl(MoveAssign);
7691 }
7692
7693 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7694 FieldEnd = ClassDecl->field_end();
7695 Field != FieldEnd;
7696 ++Field) {
7697 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7698 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7699 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7700 false, 0))
7701 ExceptSpec.CalledDecl(MoveAssign);
7702 }
7703 }
7704
7705 return ExceptSpec;
7706}
7707
7708CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
7709 // Note: The following rules are largely analoguous to the move
7710 // constructor rules.
7711
7712 ImplicitExceptionSpecification Spec(
7713 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7714
7715 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7716 QualType RetType = Context.getLValueReferenceType(ArgType);
7717 ArgType = Context.getRValueReferenceType(ArgType);
7718
7719 // An implicitly-declared move assignment operator is an inline public
7720 // member of its class.
7721 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7722 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7723 SourceLocation ClassLoc = ClassDecl->getLocation();
7724 DeclarationNameInfo NameInfo(Name, ClassLoc);
7725 CXXMethodDecl *MoveAssignment
7726 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7727 Context.getFunctionType(RetType, &ArgType, 1, EPI),
7728 /*TInfo=*/0, /*isStatic=*/false,
7729 /*StorageClassAsWritten=*/SC_None,
7730 /*isInline=*/true,
7731 /*isConstexpr=*/false,
7732 SourceLocation());
7733 MoveAssignment->setAccess(AS_public);
7734 MoveAssignment->setDefaulted();
7735 MoveAssignment->setImplicit();
7736 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
7737
7738 // Add the parameter to the operator.
7739 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
7740 ClassLoc, ClassLoc, /*Id=*/0,
7741 ArgType, /*TInfo=*/0,
7742 SC_None,
7743 SC_None, 0);
7744 MoveAssignment->setParams(&FromParam, 1);
7745
7746 // Note that we have added this copy-assignment operator.
7747 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
7748
7749 // C++0x [class.copy]p9:
7750 // If the definition of a class X does not explicitly declare a move
7751 // assignment operator, one will be implicitly declared as defaulted if and
7752 // only if:
7753 // [...]
7754 // - the move assignment operator would not be implicitly defined as
7755 // deleted.
7756 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
7757 // Cache this result so that we don't try to generate this over and over
7758 // on every lookup, leaking memory and wasting time.
7759 ClassDecl->setFailedImplicitMoveAssignment();
7760 return 0;
7761 }
7762
7763 if (Scope *S = getScopeForContext(ClassDecl))
7764 PushOnScopeChains(MoveAssignment, S, false);
7765 ClassDecl->addDecl(MoveAssignment);
7766
7767 AddOverriddenMethods(ClassDecl, MoveAssignment);
7768 return MoveAssignment;
7769}
7770
7771void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
7772 CXXMethodDecl *MoveAssignOperator) {
7773 assert((MoveAssignOperator->isDefaulted() &&
7774 MoveAssignOperator->isOverloadedOperator() &&
7775 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
7776 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
7777 "DefineImplicitMoveAssignment called for wrong function");
7778
7779 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
7780
7781 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
7782 MoveAssignOperator->setInvalidDecl();
7783 return;
7784 }
7785
7786 MoveAssignOperator->setUsed();
7787
7788 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
7789 DiagnosticErrorTrap Trap(Diags);
7790
7791 // C++0x [class.copy]p28:
7792 // The implicitly-defined or move assignment operator for a non-union class
7793 // X performs memberwise move assignment of its subobjects. The direct base
7794 // classes of X are assigned first, in the order of their declaration in the
7795 // base-specifier-list, and then the immediate non-static data members of X
7796 // are assigned, in the order in which they were declared in the class
7797 // definition.
7798
7799 // The statements that form the synthesized function body.
7800 ASTOwningVector<Stmt*> Statements(*this);
7801
7802 // The parameter for the "other" object, which we are move from.
7803 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
7804 QualType OtherRefType = Other->getType()->
7805 getAs<RValueReferenceType>()->getPointeeType();
7806 assert(OtherRefType.getQualifiers() == 0 &&
7807 "Bad argument type of defaulted move assignment");
7808
7809 // Our location for everything implicitly-generated.
7810 SourceLocation Loc = MoveAssignOperator->getLocation();
7811
7812 // Construct a reference to the "other" object. We'll be using this
7813 // throughout the generated ASTs.
7814 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7815 assert(OtherRef && "Reference to parameter cannot fail!");
7816 // Cast to rvalue.
7817 OtherRef = CastForMoving(*this, OtherRef);
7818
7819 // Construct the "this" pointer. We'll be using this throughout the generated
7820 // ASTs.
7821 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7822 assert(This && "Reference to this cannot fail!");
7823
7824 // Assign base classes.
7825 bool Invalid = false;
7826 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7827 E = ClassDecl->bases_end(); Base != E; ++Base) {
7828 // Form the assignment:
7829 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
7830 QualType BaseType = Base->getType().getUnqualifiedType();
7831 if (!BaseType->isRecordType()) {
7832 Invalid = true;
7833 continue;
7834 }
7835
7836 CXXCastPath BasePath;
7837 BasePath.push_back(Base);
7838
7839 // Construct the "from" expression, which is an implicit cast to the
7840 // appropriately-qualified base type.
7841 Expr *From = OtherRef;
7842 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
7843 VK_RValue, &BasePath).take();
7844
7845 // Dereference "this".
7846 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7847
7848 // Implicitly cast "this" to the appropriately-qualified base type.
7849 To = ImpCastExprToType(To.take(),
7850 Context.getCVRQualifiedType(BaseType,
7851 MoveAssignOperator->getTypeQualifiers()),
7852 CK_UncheckedDerivedToBase,
7853 VK_LValue, &BasePath);
7854
7855 // Build the move.
7856 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
7857 To.get(), From,
7858 /*CopyingBaseSubobject=*/true,
7859 /*Copying=*/false);
7860 if (Move.isInvalid()) {
7861 Diag(CurrentLocation, diag::note_member_synthesized_at)
7862 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7863 MoveAssignOperator->setInvalidDecl();
7864 return;
7865 }
7866
7867 // Success! Record the move.
7868 Statements.push_back(Move.takeAs<Expr>());
7869 }
7870
7871 // \brief Reference to the __builtin_memcpy function.
7872 Expr *BuiltinMemCpyRef = 0;
7873 // \brief Reference to the __builtin_objc_memmove_collectable function.
7874 Expr *CollectableMemCpyRef = 0;
7875
7876 // Assign non-static members.
7877 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7878 FieldEnd = ClassDecl->field_end();
7879 Field != FieldEnd; ++Field) {
7880 // Check for members of reference type; we can't move those.
7881 if (Field->getType()->isReferenceType()) {
7882 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7883 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7884 Diag(Field->getLocation(), diag::note_declared_at);
7885 Diag(CurrentLocation, diag::note_member_synthesized_at)
7886 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7887 Invalid = true;
7888 continue;
7889 }
7890
7891 // Check for members of const-qualified, non-class type.
7892 QualType BaseType = Context.getBaseElementType(Field->getType());
7893 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7894 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7895 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7896 Diag(Field->getLocation(), diag::note_declared_at);
7897 Diag(CurrentLocation, diag::note_member_synthesized_at)
7898 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7899 Invalid = true;
7900 continue;
7901 }
7902
7903 // Suppress assigning zero-width bitfields.
7904 if (const Expr *Width = Field->getBitWidth())
7905 if (Width->EvaluateAsInt(Context) == 0)
7906 continue;
7907
7908 QualType FieldType = Field->getType().getNonReferenceType();
7909 if (FieldType->isIncompleteArrayType()) {
7910 assert(ClassDecl->hasFlexibleArrayMember() &&
7911 "Incomplete array type is not valid");
7912 continue;
7913 }
7914
7915 // Build references to the field in the object we're copying from and to.
7916 CXXScopeSpec SS; // Intentionally empty
7917 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7918 LookupMemberName);
7919 MemberLookup.addDecl(*Field);
7920 MemberLookup.resolveKind();
7921 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7922 Loc, /*IsArrow=*/false,
7923 SS, 0, MemberLookup, 0);
7924 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7925 Loc, /*IsArrow=*/true,
7926 SS, 0, MemberLookup, 0);
7927 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7928 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7929
7930 assert(!From.get()->isLValue() && // could be xvalue or prvalue
7931 "Member reference with rvalue base must be rvalue except for reference "
7932 "members, which aren't allowed for move assignment.");
7933
7934 // If the field should be copied with __builtin_memcpy rather than via
7935 // explicit assignments, do so. This optimization only applies for arrays
7936 // of scalars and arrays of class type with trivial move-assignment
7937 // operators.
7938 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7939 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
7940 // Compute the size of the memory buffer to be copied.
7941 QualType SizeType = Context.getSizeType();
7942 llvm::APInt Size(Context.getTypeSize(SizeType),
7943 Context.getTypeSizeInChars(BaseType).getQuantity());
7944 for (const ConstantArrayType *Array
7945 = Context.getAsConstantArrayType(FieldType);
7946 Array;
7947 Array = Context.getAsConstantArrayType(Array->getElementType())) {
7948 llvm::APInt ArraySize
7949 = Array->getSize().zextOrTrunc(Size.getBitWidth());
7950 Size *= ArraySize;
7951 }
7952
Douglas Gregor45d3d712011-09-01 02:09:07 +00007953 // Take the address of the field references for "from" and "to". We
7954 // directly construct UnaryOperators here because semantic analysis
7955 // does not permit us to take the address of an xvalue.
7956 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
7957 Context.getPointerType(From.get()->getType()),
7958 VK_RValue, OK_Ordinary, Loc);
7959 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
7960 Context.getPointerType(To.get()->getType()),
7961 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007962
7963 bool NeedsCollectableMemCpy =
7964 (BaseType->isRecordType() &&
7965 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7966
7967 if (NeedsCollectableMemCpy) {
7968 if (!CollectableMemCpyRef) {
7969 // Create a reference to the __builtin_objc_memmove_collectable function.
7970 LookupResult R(*this,
7971 &Context.Idents.get("__builtin_objc_memmove_collectable"),
7972 Loc, LookupOrdinaryName);
7973 LookupName(R, TUScope, true);
7974
7975 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7976 if (!CollectableMemCpy) {
7977 // Something went horribly wrong earlier, and we will have
7978 // complained about it.
7979 Invalid = true;
7980 continue;
7981 }
7982
7983 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7984 CollectableMemCpy->getType(),
7985 VK_LValue, Loc, 0).take();
7986 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7987 }
7988 }
7989 // Create a reference to the __builtin_memcpy builtin function.
7990 else if (!BuiltinMemCpyRef) {
7991 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7992 LookupOrdinaryName);
7993 LookupName(R, TUScope, true);
7994
7995 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7996 if (!BuiltinMemCpy) {
7997 // Something went horribly wrong earlier, and we will have complained
7998 // about it.
7999 Invalid = true;
8000 continue;
8001 }
8002
8003 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8004 BuiltinMemCpy->getType(),
8005 VK_LValue, Loc, 0).take();
8006 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8007 }
8008
8009 ASTOwningVector<Expr*> CallArgs(*this);
8010 CallArgs.push_back(To.takeAs<Expr>());
8011 CallArgs.push_back(From.takeAs<Expr>());
8012 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8013 ExprResult Call = ExprError();
8014 if (NeedsCollectableMemCpy)
8015 Call = ActOnCallExpr(/*Scope=*/0,
8016 CollectableMemCpyRef,
8017 Loc, move_arg(CallArgs),
8018 Loc);
8019 else
8020 Call = ActOnCallExpr(/*Scope=*/0,
8021 BuiltinMemCpyRef,
8022 Loc, move_arg(CallArgs),
8023 Loc);
8024
8025 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8026 Statements.push_back(Call.takeAs<Expr>());
8027 continue;
8028 }
8029
8030 // Build the move of this field.
8031 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8032 To.get(), From.get(),
8033 /*CopyingBaseSubobject=*/false,
8034 /*Copying=*/false);
8035 if (Move.isInvalid()) {
8036 Diag(CurrentLocation, diag::note_member_synthesized_at)
8037 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8038 MoveAssignOperator->setInvalidDecl();
8039 return;
8040 }
8041
8042 // Success! Record the copy.
8043 Statements.push_back(Move.takeAs<Stmt>());
8044 }
8045
8046 if (!Invalid) {
8047 // Add a "return *this;"
8048 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8049
8050 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8051 if (Return.isInvalid())
8052 Invalid = true;
8053 else {
8054 Statements.push_back(Return.takeAs<Stmt>());
8055
8056 if (Trap.hasErrorOccurred()) {
8057 Diag(CurrentLocation, diag::note_member_synthesized_at)
8058 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8059 Invalid = true;
8060 }
8061 }
8062 }
8063
8064 if (Invalid) {
8065 MoveAssignOperator->setInvalidDecl();
8066 return;
8067 }
8068
8069 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8070 /*isStmtExpr=*/false);
8071 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8072 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8073
8074 if (ASTMutationListener *L = getASTMutationListener()) {
8075 L->CompletedImplicitDefinition(MoveAssignOperator);
8076 }
8077}
8078
Sean Hunt49634cf2011-05-13 06:10:58 +00008079std::pair<Sema::ImplicitExceptionSpecification, bool>
8080Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008081 if (ClassDecl->isInvalidDecl())
8082 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8083
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008084 // C++ [class.copy]p5:
8085 // The implicitly-declared copy constructor for a class X will
8086 // have the form
8087 //
8088 // X::X(const X&)
8089 //
8090 // if
Sean Huntc530d172011-06-10 04:44:37 +00008091 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008092 bool HasConstCopyConstructor = true;
8093
8094 // -- each direct or virtual base class B of X has a copy
8095 // constructor whose first parameter is of type const B& or
8096 // const volatile B&, and
8097 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8098 BaseEnd = ClassDecl->bases_end();
8099 HasConstCopyConstructor && Base != BaseEnd;
8100 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008101 // Virtual bases are handled below.
8102 if (Base->isVirtual())
8103 continue;
8104
Douglas Gregor22584312010-07-02 23:41:54 +00008105 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008106 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008107 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8108 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008109 }
8110
8111 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8112 BaseEnd = ClassDecl->vbases_end();
8113 HasConstCopyConstructor && Base != BaseEnd;
8114 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008115 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008116 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008117 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8118 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008119 }
8120
8121 // -- for all the nonstatic data members of X that are of a
8122 // class type M (or array thereof), each such class type
8123 // has a copy constructor whose first parameter is of type
8124 // const M& or const volatile M&.
8125 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8126 FieldEnd = ClassDecl->field_end();
8127 HasConstCopyConstructor && Field != FieldEnd;
8128 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008129 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008130 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008131 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8132 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008133 }
8134 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008135 // Otherwise, the implicitly declared copy constructor will have
8136 // the form
8137 //
8138 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008139
Douglas Gregor0d405db2010-07-01 20:59:04 +00008140 // C++ [except.spec]p14:
8141 // An implicitly declared special member function (Clause 12) shall have an
8142 // exception-specification. [...]
8143 ImplicitExceptionSpecification ExceptSpec(Context);
8144 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8145 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8146 BaseEnd = ClassDecl->bases_end();
8147 Base != BaseEnd;
8148 ++Base) {
8149 // Virtual bases are handled below.
8150 if (Base->isVirtual())
8151 continue;
8152
Douglas Gregor22584312010-07-02 23:41:54 +00008153 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008154 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008155 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008156 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008157 ExceptSpec.CalledDecl(CopyConstructor);
8158 }
8159 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8160 BaseEnd = ClassDecl->vbases_end();
8161 Base != BaseEnd;
8162 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008163 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008164 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008165 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008166 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008167 ExceptSpec.CalledDecl(CopyConstructor);
8168 }
8169 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8170 FieldEnd = ClassDecl->field_end();
8171 Field != FieldEnd;
8172 ++Field) {
8173 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008174 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8175 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008176 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008177 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008178 }
8179 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008180
Sean Hunt49634cf2011-05-13 06:10:58 +00008181 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8182}
8183
8184CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8185 CXXRecordDecl *ClassDecl) {
8186 // C++ [class.copy]p4:
8187 // If the class definition does not explicitly declare a copy
8188 // constructor, one is declared implicitly.
8189
8190 ImplicitExceptionSpecification Spec(Context);
8191 bool Const;
8192 llvm::tie(Spec, Const) =
8193 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8194
8195 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8196 QualType ArgType = ClassType;
8197 if (Const)
8198 ArgType = ArgType.withConst();
8199 ArgType = Context.getLValueReferenceType(ArgType);
8200
8201 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8202
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008203 DeclarationName Name
8204 = Context.DeclarationNames.getCXXConstructorName(
8205 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008206 SourceLocation ClassLoc = ClassDecl->getLocation();
8207 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008208
8209 // An implicitly-declared copy constructor is an inline public
8210 // member of its class.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008211 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008212 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008213 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00008214 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008215 /*TInfo=*/0,
8216 /*isExplicit=*/false,
8217 /*isInline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008218 /*isImplicitlyDeclared=*/true,
8219 // FIXME: apply the rules for definitions here
8220 /*isConstexpr=*/false);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008221 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008222 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008223 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8224
Douglas Gregor22584312010-07-02 23:41:54 +00008225 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008226 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8227
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008228 // Add the parameter to the constructor.
8229 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008230 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008231 /*IdentifierInfo=*/0,
8232 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008233 SC_None,
8234 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008235 CopyConstructor->setParams(&FromParam, 1);
Sean Hunt49634cf2011-05-13 06:10:58 +00008236
Douglas Gregor23c94db2010-07-02 17:43:08 +00008237 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008238 PushOnScopeChains(CopyConstructor, S, false);
8239 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008240
Sean Hunt1ccbc542011-06-22 01:05:13 +00008241 // C++0x [class.copy]p7:
8242 // ... If the class definition declares a move constructor or move
8243 // assignment operator, the implicitly declared constructor is defined as
8244 // deleted; ...
8245 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8246 ClassDecl->hasUserDeclaredMoveAssignment() ||
8247 ShouldDeleteCopyConstructor(CopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008248 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008249
8250 return CopyConstructor;
8251}
8252
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008253void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008254 CXXConstructorDecl *CopyConstructor) {
8255 assert((CopyConstructor->isDefaulted() &&
8256 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008257 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008258 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008259
Anders Carlsson63010a72010-04-23 16:24:12 +00008260 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008261 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008262
Douglas Gregor39957dc2010-05-01 15:04:51 +00008263 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008264 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008265
Sean Huntcbb67482011-01-08 20:30:50 +00008266 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008267 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008268 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008269 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008270 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008271 } else {
8272 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8273 CopyConstructor->getLocation(),
8274 MultiStmtArg(*this, 0, 0),
8275 /*isStmtExpr=*/false)
8276 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008277 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008278
8279 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008280
8281 if (ASTMutationListener *L = getASTMutationListener()) {
8282 L->CompletedImplicitDefinition(CopyConstructor);
8283 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008284}
8285
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008286Sema::ImplicitExceptionSpecification
8287Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8288 // C++ [except.spec]p14:
8289 // An implicitly declared special member function (Clause 12) shall have an
8290 // exception-specification. [...]
8291 ImplicitExceptionSpecification ExceptSpec(Context);
8292 if (ClassDecl->isInvalidDecl())
8293 return ExceptSpec;
8294
8295 // Direct base-class constructors.
8296 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8297 BEnd = ClassDecl->bases_end();
8298 B != BEnd; ++B) {
8299 if (B->isVirtual()) // Handled below.
8300 continue;
8301
8302 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8303 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8304 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8305 // If this is a deleted function, add it anyway. This might be conformant
8306 // with the standard. This might not. I'm not sure. It might not matter.
8307 if (Constructor)
8308 ExceptSpec.CalledDecl(Constructor);
8309 }
8310 }
8311
8312 // Virtual base-class constructors.
8313 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8314 BEnd = ClassDecl->vbases_end();
8315 B != BEnd; ++B) {
8316 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8317 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8318 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8319 // If this is a deleted function, add it anyway. This might be conformant
8320 // with the standard. This might not. I'm not sure. It might not matter.
8321 if (Constructor)
8322 ExceptSpec.CalledDecl(Constructor);
8323 }
8324 }
8325
8326 // Field constructors.
8327 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8328 FEnd = ClassDecl->field_end();
8329 F != FEnd; ++F) {
8330 if (F->hasInClassInitializer()) {
8331 if (Expr *E = F->getInClassInitializer())
8332 ExceptSpec.CalledExpr(E);
8333 else if (!F->isInvalidDecl())
8334 ExceptSpec.SetDelayed();
8335 } else if (const RecordType *RecordTy
8336 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8337 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8338 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8339 // If this is a deleted function, add it anyway. This might be conformant
8340 // with the standard. This might not. I'm not sure. It might not matter.
8341 // In particular, the problem is that this function never gets called. It
8342 // might just be ill-formed because this function attempts to refer to
8343 // a deleted function here.
8344 if (Constructor)
8345 ExceptSpec.CalledDecl(Constructor);
8346 }
8347 }
8348
8349 return ExceptSpec;
8350}
8351
8352CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8353 CXXRecordDecl *ClassDecl) {
8354 ImplicitExceptionSpecification Spec(
8355 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8356
8357 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8358 QualType ArgType = Context.getRValueReferenceType(ClassType);
8359
8360 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8361
8362 DeclarationName Name
8363 = Context.DeclarationNames.getCXXConstructorName(
8364 Context.getCanonicalType(ClassType));
8365 SourceLocation ClassLoc = ClassDecl->getLocation();
8366 DeclarationNameInfo NameInfo(Name, ClassLoc);
8367
8368 // C++0x [class.copy]p11:
8369 // An implicitly-declared copy/move constructor is an inline public
8370 // member of its class.
8371 CXXConstructorDecl *MoveConstructor
8372 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8373 Context.getFunctionType(Context.VoidTy,
8374 &ArgType, 1, EPI),
8375 /*TInfo=*/0,
8376 /*isExplicit=*/false,
8377 /*isInline=*/true,
8378 /*isImplicitlyDeclared=*/true,
8379 // FIXME: apply the rules for definitions here
8380 /*isConstexpr=*/false);
8381 MoveConstructor->setAccess(AS_public);
8382 MoveConstructor->setDefaulted();
8383 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8384
8385 // Add the parameter to the constructor.
8386 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8387 ClassLoc, ClassLoc,
8388 /*IdentifierInfo=*/0,
8389 ArgType, /*TInfo=*/0,
8390 SC_None,
8391 SC_None, 0);
8392 MoveConstructor->setParams(&FromParam, 1);
8393
8394 // C++0x [class.copy]p9:
8395 // If the definition of a class X does not explicitly declare a move
8396 // constructor, one will be implicitly declared as defaulted if and only if:
8397 // [...]
8398 // - the move constructor would not be implicitly defined as deleted.
8399 if (ShouldDeleteMoveConstructor(MoveConstructor)) {
8400 // Cache this result so that we don't try to generate this over and over
8401 // on every lookup, leaking memory and wasting time.
8402 ClassDecl->setFailedImplicitMoveConstructor();
8403 return 0;
8404 }
8405
8406 // Note that we have declared this constructor.
8407 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8408
8409 if (Scope *S = getScopeForContext(ClassDecl))
8410 PushOnScopeChains(MoveConstructor, S, false);
8411 ClassDecl->addDecl(MoveConstructor);
8412
8413 return MoveConstructor;
8414}
8415
8416void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8417 CXXConstructorDecl *MoveConstructor) {
8418 assert((MoveConstructor->isDefaulted() &&
8419 MoveConstructor->isMoveConstructor() &&
8420 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8421 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8422
8423 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8424 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8425
8426 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8427 DiagnosticErrorTrap Trap(Diags);
8428
8429 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8430 Trap.hasErrorOccurred()) {
8431 Diag(CurrentLocation, diag::note_member_synthesized_at)
8432 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8433 MoveConstructor->setInvalidDecl();
8434 } else {
8435 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8436 MoveConstructor->getLocation(),
8437 MultiStmtArg(*this, 0, 0),
8438 /*isStmtExpr=*/false)
8439 .takeAs<Stmt>());
8440 }
8441
8442 MoveConstructor->setUsed();
8443
8444 if (ASTMutationListener *L = getASTMutationListener()) {
8445 L->CompletedImplicitDefinition(MoveConstructor);
8446 }
8447}
8448
John McCall60d7b3a2010-08-24 06:29:42 +00008449ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008450Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008451 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008452 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008453 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008454 unsigned ConstructKind,
8455 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008456 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008457
Douglas Gregor2f599792010-04-02 18:24:57 +00008458 // C++0x [class.copy]p34:
8459 // When certain criteria are met, an implementation is allowed to
8460 // omit the copy/move construction of a class object, even if the
8461 // copy/move constructor and/or destructor for the object have
8462 // side effects. [...]
8463 // - when a temporary class object that has not been bound to a
8464 // reference (12.2) would be copied/moved to a class object
8465 // with the same cv-unqualified type, the copy/move operation
8466 // can be omitted by constructing the temporary object
8467 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008468 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00008469 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008470 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008471 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008472 }
Mike Stump1eb44332009-09-09 15:08:12 +00008473
8474 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008475 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008476 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008477}
8478
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008479/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8480/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00008481ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008482Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8483 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00008484 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008485 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008486 unsigned ConstructKind,
8487 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00008488 unsigned NumExprs = ExprArgs.size();
8489 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00008490
Nick Lewycky909a70d2011-03-25 01:44:32 +00008491 for (specific_attr_iterator<NonNullAttr>
8492 i = Constructor->specific_attr_begin<NonNullAttr>(),
8493 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8494 const NonNullAttr *NonNull = *i;
8495 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8496 }
8497
Douglas Gregor7edfb692009-11-23 12:27:39 +00008498 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00008499 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00008500 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00008501 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008502 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8503 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008504}
8505
Mike Stump1eb44332009-09-09 15:08:12 +00008506bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008507 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00008508 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00008509 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00008510 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00008511 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008512 move(Exprs), false, CXXConstructExpr::CK_Complete,
8513 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00008514 if (TempResult.isInvalid())
8515 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008516
Anders Carlssonda3f4e22009-08-25 05:12:04 +00008517 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00008518 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00008519 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00008520 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00008521 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00008522
Anders Carlssonfe2de492009-08-25 05:18:00 +00008523 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00008524}
8525
John McCall68c6c9a2010-02-02 09:10:11 +00008526void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008527 if (VD->isInvalidDecl()) return;
8528
John McCall68c6c9a2010-02-02 09:10:11 +00008529 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008530 if (ClassDecl->isInvalidDecl()) return;
8531 if (ClassDecl->hasTrivialDestructor()) return;
8532 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00008533
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008534 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8535 MarkDeclarationReferenced(VD->getLocation(), Destructor);
8536 CheckDestructorAccess(VD->getLocation(), Destructor,
8537 PDiag(diag::err_access_dtor_var)
8538 << VD->getDeclName()
8539 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00008540
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008541 if (!VD->hasGlobalStorage()) return;
8542
8543 // Emit warning for non-trivial dtor in global scope (a real global,
8544 // class-static, function-static).
8545 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8546
8547 // TODO: this should be re-enabled for static locals by !CXAAtExit
8548 if (!VD->isStaticLocal())
8549 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008550}
8551
Mike Stump1eb44332009-09-09 15:08:12 +00008552/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008553/// ActOnDeclarator, when a C++ direct initializer is present.
8554/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00008555void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00008556 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008557 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00008558 SourceLocation RParenLoc,
8559 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00008560 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008561
8562 // If there is no declaration, there was an error parsing it. Just ignore
8563 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00008564 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008565 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008566
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008567 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8568 if (!VDecl) {
8569 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8570 RealDecl->setInvalidDecl();
8571 return;
8572 }
8573
Richard Smith34b41d92011-02-20 03:19:35 +00008574 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8575 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008576 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
8577 if (Exprs.size() > 1) {
8578 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
8579 diag::err_auto_var_init_multiple_expressions)
8580 << VDecl->getDeclName() << VDecl->getType()
8581 << VDecl->getSourceRange();
8582 RealDecl->setInvalidDecl();
8583 return;
8584 }
8585
8586 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00008587 TypeSourceInfo *DeducedType = 0;
8588 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00008589 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
8590 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
8591 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00008592 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00008593 RealDecl->setInvalidDecl();
8594 return;
8595 }
Richard Smitha085da82011-03-17 16:11:59 +00008596 VDecl->setTypeSourceInfo(DeducedType);
8597 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00008598
John McCallf85e1932011-06-15 23:02:42 +00008599 // In ARC, infer lifetime.
8600 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8601 VDecl->setInvalidDecl();
8602
Richard Smith34b41d92011-02-20 03:19:35 +00008603 // If this is a redeclaration, check that the type we just deduced matches
8604 // the previously declared type.
8605 if (VarDecl *Old = VDecl->getPreviousDeclaration())
8606 MergeVarDeclTypes(VDecl, Old);
8607 }
8608
Douglas Gregor83ddad32009-08-26 21:14:46 +00008609 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00008610 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008611 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8612 //
8613 // Clients that want to distinguish between the two forms, can check for
8614 // direct initializer using VarDecl::hasCXXDirectInitializer().
8615 // A major benefit is that clients that don't particularly care about which
8616 // exactly form was it (like the CodeGen) can handle both cases without
8617 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008618
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008619 // C++ 8.5p11:
8620 // The form of initialization (using parentheses or '=') is generally
8621 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008622 // class type.
8623
Douglas Gregor4dffad62010-02-11 22:55:30 +00008624 if (!VDecl->getType()->isDependentType() &&
8625 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00008626 diag::err_typecheck_decl_incomplete_type)) {
8627 VDecl->setInvalidDecl();
8628 return;
8629 }
8630
Douglas Gregor90f93822009-12-22 22:17:25 +00008631 // The variable can not have an abstract class type.
8632 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8633 diag::err_abstract_type_in_decl,
8634 AbstractVariableType))
8635 VDecl->setInvalidDecl();
8636
Sebastian Redl31310a22010-02-01 20:16:42 +00008637 const VarDecl *Def;
8638 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00008639 Diag(VDecl->getLocation(), diag::err_redefinition)
8640 << VDecl->getDeclName();
8641 Diag(Def->getLocation(), diag::note_previous_definition);
8642 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008643 return;
8644 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00008645
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008646 // C++ [class.static.data]p4
8647 // If a static data member is of const integral or const
8648 // enumeration type, its declaration in the class definition can
8649 // specify a constant-initializer which shall be an integral
8650 // constant expression (5.19). In that case, the member can appear
8651 // in integral constant expressions. The member shall still be
8652 // defined in a namespace scope if it is used in the program and the
8653 // namespace scope definition shall not contain an initializer.
8654 //
8655 // We already performed a redefinition check above, but for static
8656 // data members we also need to check whether there was an in-class
8657 // declaration with an initializer.
8658 const VarDecl* PrevInit = 0;
8659 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8660 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
8661 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8662 return;
8663 }
8664
Douglas Gregora31040f2010-12-16 01:31:22 +00008665 bool IsDependent = false;
8666 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
8667 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
8668 VDecl->setInvalidDecl();
8669 return;
8670 }
8671
8672 if (Exprs.get()[I]->isTypeDependent())
8673 IsDependent = true;
8674 }
8675
Douglas Gregor4dffad62010-02-11 22:55:30 +00008676 // If either the declaration has a dependent type or if any of the
8677 // expressions is type-dependent, we represent the initialization
8678 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00008679 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00008680 // Let clients know that initialization was done with a direct initializer.
8681 VDecl->setCXXDirectInitializer(true);
8682
8683 // Store the initialization expressions as a ParenListExpr.
8684 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00008685 VDecl->setInit(new (Context) ParenListExpr(
8686 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
8687 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00008688 return;
8689 }
Douglas Gregor90f93822009-12-22 22:17:25 +00008690
8691 // Capture the variable that is being initialized and the style of
8692 // initialization.
8693 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8694
8695 // FIXME: Poor source location information.
8696 InitializationKind Kind
8697 = InitializationKind::CreateDirect(VDecl->getLocation(),
8698 LParenLoc, RParenLoc);
8699
8700 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00008701 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00008702 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00008703 if (Result.isInvalid()) {
8704 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008705 return;
8706 }
John McCallb4eb64d2010-10-08 02:01:28 +00008707
8708 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00008709
Douglas Gregor53c374f2010-12-07 00:41:46 +00008710 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00008711 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008712 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00008713
John McCall2998d6b2011-01-19 11:48:09 +00008714 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008715}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008716
Douglas Gregor39da0b82009-09-09 23:08:42 +00008717/// \brief Given a constructor and the set of arguments provided for the
8718/// constructor, convert the arguments and add any required default arguments
8719/// to form a proper call to this constructor.
8720///
8721/// \returns true if an error occurred, false otherwise.
8722bool
8723Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8724 MultiExprArg ArgsPtr,
8725 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00008726 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00008727 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8728 unsigned NumArgs = ArgsPtr.size();
8729 Expr **Args = (Expr **)ArgsPtr.get();
8730
8731 const FunctionProtoType *Proto
8732 = Constructor->getType()->getAs<FunctionProtoType>();
8733 assert(Proto && "Constructor without a prototype?");
8734 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00008735
8736 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008737 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00008738 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008739 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00008740 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008741
8742 VariadicCallType CallType =
8743 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008744 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008745 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
8746 Proto, 0, Args, NumArgs, AllArgs,
8747 CallType);
8748 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
8749 ConvertedArgs.push_back(AllArgs[i]);
8750 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008751}
8752
Anders Carlsson20d45d22009-12-12 00:32:00 +00008753static inline bool
8754CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
8755 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00008756 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00008757 if (isa<NamespaceDecl>(DC)) {
8758 return SemaRef.Diag(FnDecl->getLocation(),
8759 diag::err_operator_new_delete_declared_in_namespace)
8760 << FnDecl->getDeclName();
8761 }
8762
8763 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00008764 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00008765 return SemaRef.Diag(FnDecl->getLocation(),
8766 diag::err_operator_new_delete_declared_static)
8767 << FnDecl->getDeclName();
8768 }
8769
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00008770 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00008771}
8772
Anders Carlsson156c78e2009-12-13 17:53:43 +00008773static inline bool
8774CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
8775 CanQualType ExpectedResultType,
8776 CanQualType ExpectedFirstParamType,
8777 unsigned DependentParamTypeDiag,
8778 unsigned InvalidParamTypeDiag) {
8779 QualType ResultType =
8780 FnDecl->getType()->getAs<FunctionType>()->getResultType();
8781
8782 // Check that the result type is not dependent.
8783 if (ResultType->isDependentType())
8784 return SemaRef.Diag(FnDecl->getLocation(),
8785 diag::err_operator_new_delete_dependent_result_type)
8786 << FnDecl->getDeclName() << ExpectedResultType;
8787
8788 // Check that the result type is what we expect.
8789 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
8790 return SemaRef.Diag(FnDecl->getLocation(),
8791 diag::err_operator_new_delete_invalid_result_type)
8792 << FnDecl->getDeclName() << ExpectedResultType;
8793
8794 // A function template must have at least 2 parameters.
8795 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
8796 return SemaRef.Diag(FnDecl->getLocation(),
8797 diag::err_operator_new_delete_template_too_few_parameters)
8798 << FnDecl->getDeclName();
8799
8800 // The function decl must have at least 1 parameter.
8801 if (FnDecl->getNumParams() == 0)
8802 return SemaRef.Diag(FnDecl->getLocation(),
8803 diag::err_operator_new_delete_too_few_parameters)
8804 << FnDecl->getDeclName();
8805
8806 // Check the the first parameter type is not dependent.
8807 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
8808 if (FirstParamType->isDependentType())
8809 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
8810 << FnDecl->getDeclName() << ExpectedFirstParamType;
8811
8812 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00008813 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00008814 ExpectedFirstParamType)
8815 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
8816 << FnDecl->getDeclName() << ExpectedFirstParamType;
8817
8818 return false;
8819}
8820
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008821static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00008822CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00008823 // C++ [basic.stc.dynamic.allocation]p1:
8824 // A program is ill-formed if an allocation function is declared in a
8825 // namespace scope other than global scope or declared static in global
8826 // scope.
8827 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8828 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00008829
8830 CanQualType SizeTy =
8831 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
8832
8833 // C++ [basic.stc.dynamic.allocation]p1:
8834 // The return type shall be void*. The first parameter shall have type
8835 // std::size_t.
8836 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
8837 SizeTy,
8838 diag::err_operator_new_dependent_param_type,
8839 diag::err_operator_new_param_type))
8840 return true;
8841
8842 // C++ [basic.stc.dynamic.allocation]p1:
8843 // The first parameter shall not have an associated default argument.
8844 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00008845 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00008846 diag::err_operator_new_default_arg)
8847 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
8848
8849 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00008850}
8851
8852static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008853CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
8854 // C++ [basic.stc.dynamic.deallocation]p1:
8855 // A program is ill-formed if deallocation functions are declared in a
8856 // namespace scope other than global scope or declared static in global
8857 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00008858 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8859 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008860
8861 // C++ [basic.stc.dynamic.deallocation]p2:
8862 // Each deallocation function shall return void and its first parameter
8863 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00008864 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
8865 SemaRef.Context.VoidPtrTy,
8866 diag::err_operator_delete_dependent_param_type,
8867 diag::err_operator_delete_param_type))
8868 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008869
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008870 return false;
8871}
8872
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008873/// CheckOverloadedOperatorDeclaration - Check whether the declaration
8874/// of this overloaded operator is well-formed. If so, returns false;
8875/// otherwise, emits appropriate diagnostics and returns true.
8876bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008877 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008878 "Expected an overloaded operator declaration");
8879
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008880 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
8881
Mike Stump1eb44332009-09-09 15:08:12 +00008882 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008883 // The allocation and deallocation functions, operator new,
8884 // operator new[], operator delete and operator delete[], are
8885 // described completely in 3.7.3. The attributes and restrictions
8886 // found in the rest of this subclause do not apply to them unless
8887 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00008888 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008889 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00008890
Anders Carlssona3ccda52009-12-12 00:26:23 +00008891 if (Op == OO_New || Op == OO_Array_New)
8892 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008893
8894 // C++ [over.oper]p6:
8895 // An operator function shall either be a non-static member
8896 // function or be a non-member function and have at least one
8897 // parameter whose type is a class, a reference to a class, an
8898 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008899 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
8900 if (MethodDecl->isStatic())
8901 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008902 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008903 } else {
8904 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008905 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
8906 ParamEnd = FnDecl->param_end();
8907 Param != ParamEnd; ++Param) {
8908 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00008909 if (ParamType->isDependentType() || ParamType->isRecordType() ||
8910 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008911 ClassOrEnumParam = true;
8912 break;
8913 }
8914 }
8915
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008916 if (!ClassOrEnumParam)
8917 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00008918 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008919 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008920 }
8921
8922 // C++ [over.oper]p8:
8923 // An operator function cannot have default arguments (8.3.6),
8924 // except where explicitly stated below.
8925 //
Mike Stump1eb44332009-09-09 15:08:12 +00008926 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008927 // (C++ [over.call]p1).
8928 if (Op != OO_Call) {
8929 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
8930 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00008931 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00008932 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00008933 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00008934 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008935 }
8936 }
8937
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008938 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
8939 { false, false, false }
8940#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
8941 , { Unary, Binary, MemberOnly }
8942#include "clang/Basic/OperatorKinds.def"
8943 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008944
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008945 bool CanBeUnaryOperator = OperatorUses[Op][0];
8946 bool CanBeBinaryOperator = OperatorUses[Op][1];
8947 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008948
8949 // C++ [over.oper]p8:
8950 // [...] Operator functions cannot have more or fewer parameters
8951 // than the number required for the corresponding operator, as
8952 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00008953 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008954 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008955 if (Op != OO_Call &&
8956 ((NumParams == 1 && !CanBeUnaryOperator) ||
8957 (NumParams == 2 && !CanBeBinaryOperator) ||
8958 (NumParams < 1) || (NumParams > 2))) {
8959 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00008960 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008961 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00008962 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008963 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00008964 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008965 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00008966 assert(CanBeBinaryOperator &&
8967 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00008968 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008969 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008970
Chris Lattner416e46f2008-11-21 07:57:12 +00008971 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008972 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008973 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00008974
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008975 // Overloaded operators other than operator() cannot be variadic.
8976 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00008977 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00008978 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008979 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008980 }
8981
8982 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008983 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
8984 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00008985 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008986 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008987 }
8988
8989 // C++ [over.inc]p1:
8990 // The user-defined function called operator++ implements the
8991 // prefix and postfix ++ operator. If this function is a member
8992 // function with no parameters, or a non-member function with one
8993 // parameter of class or enumeration type, it defines the prefix
8994 // increment operator ++ for objects of that type. If the function
8995 // is a member function with one parameter (which shall be of type
8996 // int) or a non-member function with two parameters (the second
8997 // of which shall be of type int), it defines the postfix
8998 // increment operator ++ for objects of that type.
8999 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9000 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9001 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009002 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009003 ParamIsInt = BT->getKind() == BuiltinType::Int;
9004
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009005 if (!ParamIsInt)
9006 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009007 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009008 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009009 }
9010
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009011 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009012}
Chris Lattner5a003a42008-12-17 07:09:26 +00009013
Sean Hunta6c058d2010-01-13 09:01:02 +00009014/// CheckLiteralOperatorDeclaration - Check whether the declaration
9015/// of this literal operator function is well-formed. If so, returns
9016/// false; otherwise, emits appropriate diagnostics and returns true.
9017bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9018 DeclContext *DC = FnDecl->getDeclContext();
9019 Decl::Kind Kind = DC->getDeclKind();
9020 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9021 Kind != Decl::LinkageSpec) {
9022 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9023 << FnDecl->getDeclName();
9024 return true;
9025 }
9026
9027 bool Valid = false;
9028
Sean Hunt216c2782010-04-07 23:11:06 +00009029 // template <char...> type operator "" name() is the only valid template
9030 // signature, and the only valid signature with no parameters.
9031 if (FnDecl->param_size() == 0) {
9032 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9033 // Must have only one template parameter
9034 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9035 if (Params->size() == 1) {
9036 NonTypeTemplateParmDecl *PmDecl =
9037 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009038
Sean Hunt216c2782010-04-07 23:11:06 +00009039 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009040 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9041 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9042 Valid = true;
9043 }
9044 }
9045 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009046 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009047 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9048
Sean Hunta6c058d2010-01-13 09:01:02 +00009049 QualType T = (*Param)->getType();
9050
Sean Hunt30019c02010-04-07 22:57:35 +00009051 // unsigned long long int, long double, and any character type are allowed
9052 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009053 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9054 Context.hasSameType(T, Context.LongDoubleTy) ||
9055 Context.hasSameType(T, Context.CharTy) ||
9056 Context.hasSameType(T, Context.WCharTy) ||
9057 Context.hasSameType(T, Context.Char16Ty) ||
9058 Context.hasSameType(T, Context.Char32Ty)) {
9059 if (++Param == FnDecl->param_end())
9060 Valid = true;
9061 goto FinishedParams;
9062 }
9063
Sean Hunt30019c02010-04-07 22:57:35 +00009064 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009065 const PointerType *PT = T->getAs<PointerType>();
9066 if (!PT)
9067 goto FinishedParams;
9068 T = PT->getPointeeType();
9069 if (!T.isConstQualified())
9070 goto FinishedParams;
9071 T = T.getUnqualifiedType();
9072
9073 // Move on to the second parameter;
9074 ++Param;
9075
9076 // If there is no second parameter, the first must be a const char *
9077 if (Param == FnDecl->param_end()) {
9078 if (Context.hasSameType(T, Context.CharTy))
9079 Valid = true;
9080 goto FinishedParams;
9081 }
9082
9083 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9084 // are allowed as the first parameter to a two-parameter function
9085 if (!(Context.hasSameType(T, Context.CharTy) ||
9086 Context.hasSameType(T, Context.WCharTy) ||
9087 Context.hasSameType(T, Context.Char16Ty) ||
9088 Context.hasSameType(T, Context.Char32Ty)))
9089 goto FinishedParams;
9090
9091 // The second and final parameter must be an std::size_t
9092 T = (*Param)->getType().getUnqualifiedType();
9093 if (Context.hasSameType(T, Context.getSizeType()) &&
9094 ++Param == FnDecl->param_end())
9095 Valid = true;
9096 }
9097
9098 // FIXME: This diagnostic is absolutely terrible.
9099FinishedParams:
9100 if (!Valid) {
9101 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9102 << FnDecl->getDeclName();
9103 return true;
9104 }
9105
Douglas Gregor1155c422011-08-30 22:40:35 +00009106 StringRef LiteralName
9107 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9108 if (LiteralName[0] != '_') {
9109 // C++0x [usrlit.suffix]p1:
9110 // Literal suffix identifiers that do not start with an underscore are
9111 // reserved for future standardization.
9112 bool IsHexFloat = true;
9113 if (LiteralName.size() > 1 &&
9114 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9115 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9116 if (!isdigit(LiteralName[I])) {
9117 IsHexFloat = false;
9118 break;
9119 }
9120 }
9121 }
9122
9123 if (IsHexFloat)
9124 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9125 << LiteralName;
9126 else
9127 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9128 }
9129
Sean Hunta6c058d2010-01-13 09:01:02 +00009130 return false;
9131}
9132
Douglas Gregor074149e2009-01-05 19:45:36 +00009133/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9134/// linkage specification, including the language and (if present)
9135/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9136/// the location of the language string literal, which is provided
9137/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9138/// the '{' brace. Otherwise, this linkage specification does not
9139/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009140Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9141 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009142 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009143 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009144 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009145 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009146 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009147 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009148 Language = LinkageSpecDecl::lang_cxx;
9149 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009150 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009151 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009152 }
Mike Stump1eb44332009-09-09 15:08:12 +00009153
Chris Lattnercc98eac2008-12-17 07:13:27 +00009154 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009155
Douglas Gregor074149e2009-01-05 19:45:36 +00009156 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009157 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009158 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009159 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009160 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009161}
9162
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009163/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009164/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9165/// valid, it's the position of the closing '}' brace in a linkage
9166/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009167Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009168 Decl *LinkageSpec,
9169 SourceLocation RBraceLoc) {
9170 if (LinkageSpec) {
9171 if (RBraceLoc.isValid()) {
9172 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9173 LSDecl->setRBraceLoc(RBraceLoc);
9174 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009175 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009176 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009177 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009178}
9179
Douglas Gregord308e622009-05-18 20:51:54 +00009180/// \brief Perform semantic analysis for the variable declaration that
9181/// occurs within a C++ catch clause, returning the newly-created
9182/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009183VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009184 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009185 SourceLocation StartLoc,
9186 SourceLocation Loc,
9187 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009188 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009189 QualType ExDeclType = TInfo->getType();
9190
Sebastian Redl4b07b292008-12-22 19:15:10 +00009191 // Arrays and functions decay.
9192 if (ExDeclType->isArrayType())
9193 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9194 else if (ExDeclType->isFunctionType())
9195 ExDeclType = Context.getPointerType(ExDeclType);
9196
9197 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9198 // The exception-declaration shall not denote a pointer or reference to an
9199 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009200 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009201 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009202 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009203 Invalid = true;
9204 }
Douglas Gregord308e622009-05-18 20:51:54 +00009205
Douglas Gregora2762912010-03-08 01:47:36 +00009206 // GCC allows catching pointers and references to incomplete types
9207 // as an extension; so do we, but we warn by default.
9208
Sebastian Redl4b07b292008-12-22 19:15:10 +00009209 QualType BaseType = ExDeclType;
9210 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009211 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00009212 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00009213 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009214 BaseType = Ptr->getPointeeType();
9215 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00009216 DK = diag::ext_catch_incomplete_ptr;
9217 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009218 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009219 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009220 BaseType = Ref->getPointeeType();
9221 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00009222 DK = diag::ext_catch_incomplete_ref;
9223 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009224 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009225 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00009226 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9227 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00009228 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009229
Mike Stump1eb44332009-09-09 15:08:12 +00009230 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009231 RequireNonAbstractType(Loc, ExDeclType,
9232 diag::err_abstract_type_in_decl,
9233 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009234 Invalid = true;
9235
John McCall5a180392010-07-24 00:37:23 +00009236 // Only the non-fragile NeXT runtime currently supports C++ catches
9237 // of ObjC types, and no runtime supports catching ObjC types by value.
9238 if (!Invalid && getLangOptions().ObjC1) {
9239 QualType T = ExDeclType;
9240 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9241 T = RT->getPointeeType();
9242
9243 if (T->isObjCObjectType()) {
9244 Diag(Loc, diag::err_objc_object_catch);
9245 Invalid = true;
9246 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009247 if (!getLangOptions().ObjCNonFragileABI)
9248 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009249 }
9250 }
9251
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009252 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9253 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009254 ExDecl->setExceptionVariable(true);
9255
Douglas Gregorc41b8782011-07-06 18:14:43 +00009256 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009257 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009258 // C++ [except.handle]p16:
9259 // The object declared in an exception-declaration or, if the
9260 // exception-declaration does not specify a name, a temporary (12.2) is
9261 // copy-initialized (8.5) from the exception object. [...]
9262 // The object is destroyed when the handler exits, after the destruction
9263 // of any automatic objects initialized within the handler.
9264 //
9265 // We just pretend to initialize the object with itself, then make sure
9266 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009267 QualType initType = ExDeclType;
9268
9269 InitializedEntity entity =
9270 InitializedEntity::InitializeVariable(ExDecl);
9271 InitializationKind initKind =
9272 InitializationKind::CreateCopy(Loc, SourceLocation());
9273
9274 Expr *opaqueValue =
9275 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9276 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9277 ExprResult result = sequence.Perform(*this, entity, initKind,
9278 MultiExprArg(&opaqueValue, 1));
9279 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009280 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009281 else {
9282 // If the constructor used was non-trivial, set this as the
9283 // "initializer".
9284 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9285 if (!construct->getConstructor()->isTrivial()) {
9286 Expr *init = MaybeCreateExprWithCleanups(construct);
9287 ExDecl->setInit(init);
9288 }
9289
9290 // And make sure it's destructable.
9291 FinalizeVarWithDestructor(ExDecl, recordType);
9292 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009293 }
9294 }
9295
Douglas Gregord308e622009-05-18 20:51:54 +00009296 if (Invalid)
9297 ExDecl->setInvalidDecl();
9298
9299 return ExDecl;
9300}
9301
9302/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9303/// handler.
John McCalld226f652010-08-21 09:40:31 +00009304Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009305 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009306 bool Invalid = D.isInvalidType();
9307
9308 // Check for unexpanded parameter packs.
9309 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9310 UPPC_ExceptionType)) {
9311 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9312 D.getIdentifierLoc());
9313 Invalid = true;
9314 }
9315
Sebastian Redl4b07b292008-12-22 19:15:10 +00009316 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009317 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009318 LookupOrdinaryName,
9319 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009320 // The scope should be freshly made just for us. There is just no way
9321 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009322 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009323 if (PrevDecl->isTemplateParameter()) {
9324 // Maybe we will complain about the shadowed template parameter.
9325 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009326 }
9327 }
9328
Chris Lattnereaaebc72009-04-25 08:06:05 +00009329 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009330 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9331 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009332 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009333 }
9334
Douglas Gregor83cb9422010-09-09 17:09:21 +00009335 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009336 D.getSourceRange().getBegin(),
9337 D.getIdentifierLoc(),
9338 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009339 if (Invalid)
9340 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009341
Sebastian Redl4b07b292008-12-22 19:15:10 +00009342 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009343 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009344 PushOnScopeChains(ExDecl, S);
9345 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009346 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009347
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009348 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009349 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009350}
Anders Carlssonfb311762009-03-14 00:25:26 +00009351
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009352Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009353 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009354 Expr *AssertMessageExpr_,
9355 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009356 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009357
Anders Carlssonc3082412009-03-14 00:33:21 +00009358 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9359 llvm::APSInt Value(32);
9360 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009361 Diag(StaticAssertLoc,
9362 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00009363 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009364 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00009365 }
Anders Carlssonfb311762009-03-14 00:25:26 +00009366
Anders Carlssonc3082412009-03-14 00:33:21 +00009367 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009368 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009369 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009370 }
9371 }
Mike Stump1eb44332009-09-09 15:08:12 +00009372
Douglas Gregor399ad972010-12-15 23:55:21 +00009373 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9374 return 0;
9375
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009376 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9377 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009378
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009379 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009380 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009381}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009382
Douglas Gregor1d869352010-04-07 16:53:43 +00009383/// \brief Perform semantic analysis of the given friend type declaration.
9384///
9385/// \returns A friend declaration that.
9386FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9387 TypeSourceInfo *TSInfo) {
9388 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9389
9390 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009391 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009392
Douglas Gregor06245bf2010-04-07 17:57:12 +00009393 if (!getLangOptions().CPlusPlus0x) {
9394 // C++03 [class.friend]p2:
9395 // An elaborated-type-specifier shall be used in a friend declaration
9396 // for a class.*
9397 //
9398 // * The class-key of the elaborated-type-specifier is required.
9399 if (!ActiveTemplateInstantiations.empty()) {
9400 // Do not complain about the form of friend template types during
9401 // template instantiation; we will already have complained when the
9402 // template was declared.
9403 } else if (!T->isElaboratedTypeSpecifier()) {
9404 // If we evaluated the type to a record type, suggest putting
9405 // a tag in front.
9406 if (const RecordType *RT = T->getAs<RecordType>()) {
9407 RecordDecl *RD = RT->getDecl();
9408
9409 std::string InsertionText = std::string(" ") + RD->getKindName();
9410
9411 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9412 << (unsigned) RD->getTagKind()
9413 << T
9414 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9415 InsertionText);
9416 } else {
9417 Diag(FriendLoc, diag::ext_nonclass_type_friend)
9418 << T
9419 << SourceRange(FriendLoc, TypeRange.getEnd());
9420 }
9421 } else if (T->getAs<EnumType>()) {
9422 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009423 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009424 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009425 }
9426 }
9427
Douglas Gregor06245bf2010-04-07 17:57:12 +00009428 // C++0x [class.friend]p3:
9429 // If the type specifier in a friend declaration designates a (possibly
9430 // cv-qualified) class type, that class is declared as a friend; otherwise,
9431 // the friend declaration is ignored.
9432
9433 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9434 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009435
9436 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9437}
9438
John McCall9a34edb2010-10-19 01:40:49 +00009439/// Handle a friend tag declaration where the scope specifier was
9440/// templated.
9441Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9442 unsigned TagSpec, SourceLocation TagLoc,
9443 CXXScopeSpec &SS,
9444 IdentifierInfo *Name, SourceLocation NameLoc,
9445 AttributeList *Attr,
9446 MultiTemplateParamsArg TempParamLists) {
9447 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9448
9449 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009450 bool Invalid = false;
9451
9452 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009453 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009454 TempParamLists.get(),
9455 TempParamLists.size(),
9456 /*friend*/ true,
9457 isExplicitSpecialization,
9458 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009459 if (TemplateParams->size() > 0) {
9460 // This is a declaration of a class template.
9461 if (Invalid)
9462 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009463
Eric Christopher4110e132011-07-21 05:34:24 +00009464 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9465 SS, Name, NameLoc, Attr,
9466 TemplateParams, AS_public,
9467 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009468 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009469 } else {
9470 // The "template<>" header is extraneous.
9471 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9472 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9473 isExplicitSpecialization = true;
9474 }
9475 }
9476
9477 if (Invalid) return 0;
9478
9479 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9480
9481 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009482 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009483 if (TempParamLists.get()[I]->size()) {
9484 isAllExplicitSpecializations = false;
9485 break;
9486 }
9487 }
9488
9489 // FIXME: don't ignore attributes.
9490
9491 // If it's explicit specializations all the way down, just forget
9492 // about the template header and build an appropriate non-templated
9493 // friend. TODO: for source fidelity, remember the headers.
9494 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00009495 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009496 ElaboratedTypeKeyword Keyword
9497 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009498 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009499 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009500 if (T.isNull())
9501 return 0;
9502
9503 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9504 if (isa<DependentNameType>(T)) {
9505 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9506 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009507 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009508 TL.setNameLoc(NameLoc);
9509 } else {
9510 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9511 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009512 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009513 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9514 }
9515
9516 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9517 TSI, FriendLoc);
9518 Friend->setAccess(AS_public);
9519 CurContext->addDecl(Friend);
9520 return Friend;
9521 }
9522
9523 // Handle the case of a templated-scope friend class. e.g.
9524 // template <class T> class A<T>::B;
9525 // FIXME: we don't support these right now.
9526 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9527 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9528 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9529 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9530 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009531 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009532 TL.setNameLoc(NameLoc);
9533
9534 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9535 TSI, FriendLoc);
9536 Friend->setAccess(AS_public);
9537 Friend->setUnsupportedFriend(true);
9538 CurContext->addDecl(Friend);
9539 return Friend;
9540}
9541
9542
John McCalldd4a3b02009-09-16 22:47:08 +00009543/// Handle a friend type declaration. This works in tandem with
9544/// ActOnTag.
9545///
9546/// Notes on friend class templates:
9547///
9548/// We generally treat friend class declarations as if they were
9549/// declaring a class. So, for example, the elaborated type specifier
9550/// in a friend declaration is required to obey the restrictions of a
9551/// class-head (i.e. no typedefs in the scope chain), template
9552/// parameters are required to match up with simple template-ids, &c.
9553/// However, unlike when declaring a template specialization, it's
9554/// okay to refer to a template specialization without an empty
9555/// template parameter declaration, e.g.
9556/// friend class A<T>::B<unsigned>;
9557/// We permit this as a special case; if there are any template
9558/// parameters present at all, require proper matching, i.e.
9559/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00009560Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00009561 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00009562 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00009563
9564 assert(DS.isFriendSpecified());
9565 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9566
John McCalldd4a3b02009-09-16 22:47:08 +00009567 // Try to convert the decl specifier to a type. This works for
9568 // friend templates because ActOnTag never produces a ClassTemplateDecl
9569 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00009570 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00009571 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9572 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00009573 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00009574 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009575
Douglas Gregor6ccab972010-12-16 01:14:37 +00009576 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9577 return 0;
9578
John McCalldd4a3b02009-09-16 22:47:08 +00009579 // This is definitely an error in C++98. It's probably meant to
9580 // be forbidden in C++0x, too, but the specification is just
9581 // poorly written.
9582 //
9583 // The problem is with declarations like the following:
9584 // template <T> friend A<T>::foo;
9585 // where deciding whether a class C is a friend or not now hinges
9586 // on whether there exists an instantiation of A that causes
9587 // 'foo' to equal C. There are restrictions on class-heads
9588 // (which we declare (by fiat) elaborated friend declarations to
9589 // be) that makes this tractable.
9590 //
9591 // FIXME: handle "template <> friend class A<T>;", which
9592 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00009593 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00009594 Diag(Loc, diag::err_tagless_friend_type_template)
9595 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009596 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00009597 }
Douglas Gregor1d869352010-04-07 16:53:43 +00009598
John McCall02cace72009-08-28 07:59:38 +00009599 // C++98 [class.friend]p1: A friend of a class is a function
9600 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00009601 // This is fixed in DR77, which just barely didn't make the C++03
9602 // deadline. It's also a very silly restriction that seriously
9603 // affects inner classes and which nobody else seems to implement;
9604 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00009605 //
9606 // But note that we could warn about it: it's always useless to
9607 // friend one of your own members (it's not, however, worthless to
9608 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00009609
John McCalldd4a3b02009-09-16 22:47:08 +00009610 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00009611 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00009612 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009613 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00009614 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00009615 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00009616 DS.getFriendSpecLoc());
9617 else
Douglas Gregor1d869352010-04-07 16:53:43 +00009618 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
9619
9620 if (!D)
John McCalld226f652010-08-21 09:40:31 +00009621 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00009622
John McCalldd4a3b02009-09-16 22:47:08 +00009623 D->setAccess(AS_public);
9624 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00009625
John McCalld226f652010-08-21 09:40:31 +00009626 return D;
John McCall02cace72009-08-28 07:59:38 +00009627}
9628
John McCall337ec3d2010-10-12 23:13:28 +00009629Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
9630 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00009631 const DeclSpec &DS = D.getDeclSpec();
9632
9633 assert(DS.isFriendSpecified());
9634 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9635
9636 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00009637 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9638 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00009639
9640 // C++ [class.friend]p1
9641 // A friend of a class is a function or class....
9642 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00009643 // It *doesn't* see through dependent types, which is correct
9644 // according to [temp.arg.type]p3:
9645 // If a declaration acquires a function type through a
9646 // type dependent on a template-parameter and this causes
9647 // a declaration that does not use the syntactic form of a
9648 // function declarator to have a function type, the program
9649 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00009650 if (!T->isFunctionType()) {
9651 Diag(Loc, diag::err_unexpected_friend);
9652
9653 // It might be worthwhile to try to recover by creating an
9654 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00009655 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009656 }
9657
9658 // C++ [namespace.memdef]p3
9659 // - If a friend declaration in a non-local class first declares a
9660 // class or function, the friend class or function is a member
9661 // of the innermost enclosing namespace.
9662 // - The name of the friend is not found by simple name lookup
9663 // until a matching declaration is provided in that namespace
9664 // scope (either before or after the class declaration granting
9665 // friendship).
9666 // - If a friend function is called, its name may be found by the
9667 // name lookup that considers functions from namespaces and
9668 // classes associated with the types of the function arguments.
9669 // - When looking for a prior declaration of a class or a function
9670 // declared as a friend, scopes outside the innermost enclosing
9671 // namespace scope are not considered.
9672
John McCall337ec3d2010-10-12 23:13:28 +00009673 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00009674 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9675 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00009676 assert(Name);
9677
Douglas Gregor6ccab972010-12-16 01:14:37 +00009678 // Check for unexpanded parameter packs.
9679 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9680 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9681 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9682 return 0;
9683
John McCall67d1a672009-08-06 02:15:43 +00009684 // The context we found the declaration in, or in which we should
9685 // create the declaration.
9686 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00009687 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00009688 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00009689 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00009690
John McCall337ec3d2010-10-12 23:13:28 +00009691 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00009692
John McCall337ec3d2010-10-12 23:13:28 +00009693 // There are four cases here.
9694 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00009695 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00009696 // there as appropriate.
9697 // Recover from invalid scope qualifiers as if they just weren't there.
9698 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00009699 // C++0x [namespace.memdef]p3:
9700 // If the name in a friend declaration is neither qualified nor
9701 // a template-id and the declaration is a function or an
9702 // elaborated-type-specifier, the lookup to determine whether
9703 // the entity has been previously declared shall not consider
9704 // any scopes outside the innermost enclosing namespace.
9705 // C++0x [class.friend]p11:
9706 // If a friend declaration appears in a local class and the name
9707 // specified is an unqualified name, a prior declaration is
9708 // looked up without considering scopes that are outside the
9709 // innermost enclosing non-class scope. For a friend function
9710 // declaration, if there is no prior declaration, the program is
9711 // ill-formed.
9712 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00009713 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00009714
John McCall29ae6e52010-10-13 05:45:15 +00009715 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00009716 DC = CurContext;
9717 while (true) {
9718 // Skip class contexts. If someone can cite chapter and verse
9719 // for this behavior, that would be nice --- it's what GCC and
9720 // EDG do, and it seems like a reasonable intent, but the spec
9721 // really only says that checks for unqualified existing
9722 // declarations should stop at the nearest enclosing namespace,
9723 // not that they should only consider the nearest enclosing
9724 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00009725 while (DC->isRecord())
9726 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00009727
John McCall68263142009-11-18 22:49:29 +00009728 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00009729
9730 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00009731 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00009732 break;
John McCall29ae6e52010-10-13 05:45:15 +00009733
John McCall8a407372010-10-14 22:22:28 +00009734 if (isTemplateId) {
9735 if (isa<TranslationUnitDecl>(DC)) break;
9736 } else {
9737 if (DC->isFileContext()) break;
9738 }
John McCall67d1a672009-08-06 02:15:43 +00009739 DC = DC->getParent();
9740 }
9741
9742 // C++ [class.friend]p1: A friend of a class is a function or
9743 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00009744 // C++0x changes this for both friend types and functions.
9745 // Most C++ 98 compilers do seem to give an error here, so
9746 // we do, too.
John McCall68263142009-11-18 22:49:29 +00009747 if (!Previous.empty() && DC->Equals(CurContext)
9748 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00009749 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00009750
John McCall380aaa42010-10-13 06:22:15 +00009751 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00009752
John McCall337ec3d2010-10-12 23:13:28 +00009753 // - There's a non-dependent scope specifier, in which case we
9754 // compute it and do a previous lookup there for a function
9755 // or function template.
9756 } else if (!SS.getScopeRep()->isDependent()) {
9757 DC = computeDeclContext(SS);
9758 if (!DC) return 0;
9759
9760 if (RequireCompleteDeclContext(SS, DC)) return 0;
9761
9762 LookupQualifiedName(Previous, DC);
9763
9764 // Ignore things found implicitly in the wrong scope.
9765 // TODO: better diagnostics for this case. Suggesting the right
9766 // qualified scope would be nice...
9767 LookupResult::Filter F = Previous.makeFilter();
9768 while (F.hasNext()) {
9769 NamedDecl *D = F.next();
9770 if (!DC->InEnclosingNamespaceSetOf(
9771 D->getDeclContext()->getRedeclContext()))
9772 F.erase();
9773 }
9774 F.done();
9775
9776 if (Previous.empty()) {
9777 D.setInvalidType();
9778 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
9779 return 0;
9780 }
9781
9782 // C++ [class.friend]p1: A friend of a class is a function or
9783 // class that is not a member of the class . . .
9784 if (DC->Equals(CurContext))
9785 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
9786
9787 // - There's a scope specifier that does not match any template
9788 // parameter lists, in which case we use some arbitrary context,
9789 // create a method or method template, and wait for instantiation.
9790 // - There's a scope specifier that does match some template
9791 // parameter lists, which we don't handle right now.
9792 } else {
9793 DC = CurContext;
9794 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00009795 }
9796
John McCall29ae6e52010-10-13 05:45:15 +00009797 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00009798 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00009799 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
9800 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
9801 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00009802 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00009803 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
9804 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00009805 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009806 }
John McCall67d1a672009-08-06 02:15:43 +00009807 }
9808
Douglas Gregor182ddf02009-09-28 00:08:27 +00009809 bool Redeclaration = false;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00009810 bool AddToScope = true;
John McCall380aaa42010-10-13 06:22:15 +00009811 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00009812 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00009813 IsDefinition,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00009814 Redeclaration, AddToScope);
John McCalld226f652010-08-21 09:40:31 +00009815 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00009816
Douglas Gregor182ddf02009-09-28 00:08:27 +00009817 assert(ND->getDeclContext() == DC);
9818 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00009819
John McCallab88d972009-08-31 22:39:49 +00009820 // Add the function declaration to the appropriate lookup tables,
9821 // adjusting the redeclarations list as necessary. We don't
9822 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00009823 //
John McCallab88d972009-08-31 22:39:49 +00009824 // Also update the scope-based lookup if the target context's
9825 // lookup context is in lexical scope.
9826 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009827 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00009828 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00009829 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00009830 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00009831 }
John McCall02cace72009-08-28 07:59:38 +00009832
9833 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00009834 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00009835 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00009836 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00009837 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00009838
John McCall337ec3d2010-10-12 23:13:28 +00009839 if (ND->isInvalidDecl())
9840 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00009841 else {
9842 FunctionDecl *FD;
9843 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9844 FD = FTD->getTemplatedDecl();
9845 else
9846 FD = cast<FunctionDecl>(ND);
9847
9848 // Mark templated-scope function declarations as unsupported.
9849 if (FD->getNumTemplateParameterLists())
9850 FrD->setUnsupportedFriend(true);
9851 }
John McCall337ec3d2010-10-12 23:13:28 +00009852
John McCalld226f652010-08-21 09:40:31 +00009853 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00009854}
9855
John McCalld226f652010-08-21 09:40:31 +00009856void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
9857 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00009858
Sebastian Redl50de12f2009-03-24 22:27:57 +00009859 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
9860 if (!Fn) {
9861 Diag(DelLoc, diag::err_deleted_non_function);
9862 return;
9863 }
9864 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
9865 Diag(DelLoc, diag::err_deleted_decl_not_first);
9866 Diag(Prev->getLocation(), diag::note_previous_declaration);
9867 // If the declaration wasn't the first, we delete the function anyway for
9868 // recovery.
9869 }
Sean Hunt10620eb2011-05-06 20:44:56 +00009870 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +00009871}
Sebastian Redl13e88542009-04-27 21:33:24 +00009872
Sean Hunte4246a62011-05-12 06:15:49 +00009873void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
9874 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
9875
9876 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +00009877 if (MD->getParent()->isDependentType()) {
9878 MD->setDefaulted();
9879 MD->setExplicitlyDefaulted();
9880 return;
9881 }
9882
Sean Hunte4246a62011-05-12 06:15:49 +00009883 CXXSpecialMember Member = getSpecialMember(MD);
9884 if (Member == CXXInvalid) {
9885 Diag(DefaultLoc, diag::err_default_special_members);
9886 return;
9887 }
9888
9889 MD->setDefaulted();
9890 MD->setExplicitlyDefaulted();
9891
Sean Huntcd10dec2011-05-23 23:14:04 +00009892 // If this definition appears within the record, do the checking when
9893 // the record is complete.
9894 const FunctionDecl *Primary = MD;
9895 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
9896 // Find the uninstantiated declaration that actually had the '= default'
9897 // on it.
9898 MD->getTemplateInstantiationPattern()->isDefined(Primary);
9899
9900 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +00009901 return;
9902
9903 switch (Member) {
9904 case CXXDefaultConstructor: {
9905 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9906 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +00009907 if (!CD->isInvalidDecl())
9908 DefineImplicitDefaultConstructor(DefaultLoc, CD);
9909 break;
9910 }
9911
9912 case CXXCopyConstructor: {
9913 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9914 CheckExplicitlyDefaultedCopyConstructor(CD);
9915 if (!CD->isInvalidDecl())
9916 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +00009917 break;
9918 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00009919
Sean Hunt2b188082011-05-14 05:23:28 +00009920 case CXXCopyAssignment: {
9921 CheckExplicitlyDefaultedCopyAssignment(MD);
9922 if (!MD->isInvalidDecl())
9923 DefineImplicitCopyAssignment(DefaultLoc, MD);
9924 break;
9925 }
9926
Sean Huntcb45a0f2011-05-12 22:46:25 +00009927 case CXXDestructor: {
9928 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
9929 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +00009930 if (!DD->isInvalidDecl())
9931 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +00009932 break;
9933 }
9934
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009935 case CXXMoveConstructor: {
9936 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9937 CheckExplicitlyDefaultedMoveConstructor(CD);
9938 if (!CD->isInvalidDecl())
9939 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +00009940 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009941 }
Sean Hunt82713172011-05-25 23:16:36 +00009942
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009943 case CXXMoveAssignment: {
9944 CheckExplicitlyDefaultedMoveAssignment(MD);
9945 if (!MD->isInvalidDecl())
9946 DefineImplicitMoveAssignment(DefaultLoc, MD);
9947 break;
9948 }
9949
9950 case CXXInvalid:
9951 assert(false && "Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +00009952 break;
9953 }
9954 } else {
9955 Diag(DefaultLoc, diag::err_default_special_members);
9956 }
9957}
9958
Sebastian Redl13e88542009-04-27 21:33:24 +00009959static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00009960 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00009961 Stmt *SubStmt = *CI;
9962 if (!SubStmt)
9963 continue;
9964 if (isa<ReturnStmt>(SubStmt))
9965 Self.Diag(SubStmt->getSourceRange().getBegin(),
9966 diag::err_return_in_constructor_handler);
9967 if (!isa<Expr>(SubStmt))
9968 SearchForReturnInStmt(Self, SubStmt);
9969 }
9970}
9971
9972void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
9973 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
9974 CXXCatchStmt *Handler = TryBlock->getHandler(I);
9975 SearchForReturnInStmt(*this, Handler);
9976 }
9977}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009978
Mike Stump1eb44332009-09-09 15:08:12 +00009979bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009980 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00009981 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
9982 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009983
Chandler Carruth73857792010-02-15 11:53:20 +00009984 if (Context.hasSameType(NewTy, OldTy) ||
9985 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009986 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00009987
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009988 // Check if the return types are covariant
9989 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00009990
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009991 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00009992 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
9993 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009994 NewClassTy = NewPT->getPointeeType();
9995 OldClassTy = OldPT->getPointeeType();
9996 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00009997 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
9998 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
9999 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10000 NewClassTy = NewRT->getPointeeType();
10001 OldClassTy = OldRT->getPointeeType();
10002 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010003 }
10004 }
Mike Stump1eb44332009-09-09 15:08:12 +000010005
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010006 // The return types aren't either both pointers or references to a class type.
10007 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010008 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010009 diag::err_different_return_type_for_overriding_virtual_function)
10010 << New->getDeclName() << NewTy << OldTy;
10011 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010012
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010013 return true;
10014 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010015
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010016 // C++ [class.virtual]p6:
10017 // If the return type of D::f differs from the return type of B::f, the
10018 // class type in the return type of D::f shall be complete at the point of
10019 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010020 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10021 if (!RT->isBeingDefined() &&
10022 RequireCompleteType(New->getLocation(), NewClassTy,
10023 PDiag(diag::err_covariant_return_incomplete)
10024 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010025 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010026 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010027
Douglas Gregora4923eb2009-11-16 21:35:15 +000010028 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010029 // Check if the new class derives from the old class.
10030 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10031 Diag(New->getLocation(),
10032 diag::err_covariant_return_not_derived)
10033 << New->getDeclName() << NewTy << OldTy;
10034 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10035 return true;
10036 }
Mike Stump1eb44332009-09-09 15:08:12 +000010037
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010038 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010039 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010040 diag::err_covariant_return_inaccessible_base,
10041 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10042 // FIXME: Should this point to the return type?
10043 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010044 // FIXME: this note won't trigger for delayed access control
10045 // diagnostics, and it's impossible to get an undelayed error
10046 // here from access control during the original parse because
10047 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010048 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10049 return true;
10050 }
10051 }
Mike Stump1eb44332009-09-09 15:08:12 +000010052
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010053 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010054 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010055 Diag(New->getLocation(),
10056 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010057 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010058 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10059 return true;
10060 };
Mike Stump1eb44332009-09-09 15:08:12 +000010061
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010062
10063 // The new class type must have the same or less qualifiers as the old type.
10064 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10065 Diag(New->getLocation(),
10066 diag::err_covariant_return_type_class_type_more_qualified)
10067 << New->getDeclName() << NewTy << OldTy;
10068 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10069 return true;
10070 };
Mike Stump1eb44332009-09-09 15:08:12 +000010071
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010072 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010073}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010074
Douglas Gregor4ba31362009-12-01 17:24:26 +000010075/// \brief Mark the given method pure.
10076///
10077/// \param Method the method to be marked pure.
10078///
10079/// \param InitRange the source range that covers the "0" initializer.
10080bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010081 SourceLocation EndLoc = InitRange.getEnd();
10082 if (EndLoc.isValid())
10083 Method->setRangeEnd(EndLoc);
10084
Douglas Gregor4ba31362009-12-01 17:24:26 +000010085 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10086 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010087 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010088 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010089
10090 if (!Method->isInvalidDecl())
10091 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10092 << Method->getDeclName() << InitRange;
10093 return true;
10094}
10095
John McCall731ad842009-12-19 09:28:58 +000010096/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10097/// an initializer for the out-of-line declaration 'Dcl'. The scope
10098/// is a fresh scope pushed for just this purpose.
10099///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010100/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10101/// static data member of class X, names should be looked up in the scope of
10102/// class X.
John McCalld226f652010-08-21 09:40:31 +000010103void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010104 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010105 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010106
John McCall731ad842009-12-19 09:28:58 +000010107 // We should only get called for declarations with scope specifiers, like:
10108 // int foo::bar;
10109 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010110 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010111}
10112
10113/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010114/// initializer for the out-of-line declaration 'D'.
10115void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010116 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010117 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010118
John McCall731ad842009-12-19 09:28:58 +000010119 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010120 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010121}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010122
10123/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10124/// C++ if/switch/while/for statement.
10125/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010126DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010127 // C++ 6.4p2:
10128 // The declarator shall not specify a function or an array.
10129 // The type-specifier-seq shall not contain typedef and shall not declare a
10130 // new class or enumeration.
10131 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10132 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010133
10134 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010135 if (!Dcl)
10136 return true;
10137
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010138 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10139 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010140 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010141 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010142 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010143
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010144 return Dcl;
10145}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010146
Douglas Gregordfe65432011-07-28 19:11:31 +000010147void Sema::LoadExternalVTableUses() {
10148 if (!ExternalSource)
10149 return;
10150
10151 SmallVector<ExternalVTableUse, 4> VTables;
10152 ExternalSource->ReadUsedVTables(VTables);
10153 SmallVector<VTableUse, 4> NewUses;
10154 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10155 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10156 = VTablesUsed.find(VTables[I].Record);
10157 // Even if a definition wasn't required before, it may be required now.
10158 if (Pos != VTablesUsed.end()) {
10159 if (!Pos->second && VTables[I].DefinitionRequired)
10160 Pos->second = true;
10161 continue;
10162 }
10163
10164 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10165 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10166 }
10167
10168 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10169}
10170
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010171void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10172 bool DefinitionRequired) {
10173 // Ignore any vtable uses in unevaluated operands or for classes that do
10174 // not have a vtable.
10175 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10176 CurContext->isDependentContext() ||
10177 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010178 return;
10179
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010180 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010181 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010182 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10183 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10184 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10185 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010186 // If we already had an entry, check to see if we are promoting this vtable
10187 // to required a definition. If so, we need to reappend to the VTableUses
10188 // list, since we may have already processed the first entry.
10189 if (DefinitionRequired && !Pos.first->second) {
10190 Pos.first->second = true;
10191 } else {
10192 // Otherwise, we can early exit.
10193 return;
10194 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010195 }
10196
10197 // Local classes need to have their virtual members marked
10198 // immediately. For all other classes, we mark their virtual members
10199 // at the end of the translation unit.
10200 if (Class->isLocalClass())
10201 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010202 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010203 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010204}
10205
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010206bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010207 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010208 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010209 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010210
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010211 // Note: The VTableUses vector could grow as a result of marking
10212 // the members of a class as "used", so we check the size each
10213 // time through the loop and prefer indices (with are stable) to
10214 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010215 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010216 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010217 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010218 if (!Class)
10219 continue;
10220
10221 SourceLocation Loc = VTableUses[I].second;
10222
10223 // If this class has a key function, but that key function is
10224 // defined in another translation unit, we don't need to emit the
10225 // vtable even though we're using it.
10226 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010227 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010228 switch (KeyFunction->getTemplateSpecializationKind()) {
10229 case TSK_Undeclared:
10230 case TSK_ExplicitSpecialization:
10231 case TSK_ExplicitInstantiationDeclaration:
10232 // The key function is in another translation unit.
10233 continue;
10234
10235 case TSK_ExplicitInstantiationDefinition:
10236 case TSK_ImplicitInstantiation:
10237 // We will be instantiating the key function.
10238 break;
10239 }
10240 } else if (!KeyFunction) {
10241 // If we have a class with no key function that is the subject
10242 // of an explicit instantiation declaration, suppress the
10243 // vtable; it will live with the explicit instantiation
10244 // definition.
10245 bool IsExplicitInstantiationDeclaration
10246 = Class->getTemplateSpecializationKind()
10247 == TSK_ExplicitInstantiationDeclaration;
10248 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10249 REnd = Class->redecls_end();
10250 R != REnd; ++R) {
10251 TemplateSpecializationKind TSK
10252 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10253 if (TSK == TSK_ExplicitInstantiationDeclaration)
10254 IsExplicitInstantiationDeclaration = true;
10255 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10256 IsExplicitInstantiationDeclaration = false;
10257 break;
10258 }
10259 }
10260
10261 if (IsExplicitInstantiationDeclaration)
10262 continue;
10263 }
10264
10265 // Mark all of the virtual members of this class as referenced, so
10266 // that we can build a vtable. Then, tell the AST consumer that a
10267 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010268 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010269 MarkVirtualMembersReferenced(Loc, Class);
10270 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10271 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10272
10273 // Optionally warn if we're emitting a weak vtable.
10274 if (Class->getLinkage() == ExternalLinkage &&
10275 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010276 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010277 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10278 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010279 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010280 VTableUses.clear();
10281
Douglas Gregor78844032011-04-22 22:25:37 +000010282 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010283}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010284
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010285void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10286 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010287 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10288 e = RD->method_end(); i != e; ++i) {
10289 CXXMethodDecl *MD = *i;
10290
10291 // C++ [basic.def.odr]p2:
10292 // [...] A virtual member function is used if it is not pure. [...]
10293 if (MD->isVirtual() && !MD->isPure())
10294 MarkDeclarationReferenced(Loc, MD);
10295 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010296
10297 // Only classes that have virtual bases need a VTT.
10298 if (RD->getNumVBases() == 0)
10299 return;
10300
10301 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10302 e = RD->bases_end(); i != e; ++i) {
10303 const CXXRecordDecl *Base =
10304 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010305 if (Base->getNumVBases() == 0)
10306 continue;
10307 MarkVirtualMembersReferenced(Loc, Base);
10308 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010309}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010310
10311/// SetIvarInitializers - This routine builds initialization ASTs for the
10312/// Objective-C implementation whose ivars need be initialized.
10313void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10314 if (!getLangOptions().CPlusPlus)
10315 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010316 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010317 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010318 CollectIvarsToConstructOrDestruct(OID, ivars);
10319 if (ivars.empty())
10320 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010321 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010322 for (unsigned i = 0; i < ivars.size(); i++) {
10323 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010324 if (Field->isInvalidDecl())
10325 continue;
10326
Sean Huntcbb67482011-01-08 20:30:50 +000010327 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010328 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10329 InitializationKind InitKind =
10330 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10331
10332 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010333 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010334 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010335 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010336 // Note, MemberInit could actually come back empty if no initialization
10337 // is required (e.g., because it would call a trivial default constructor)
10338 if (!MemberInit.get() || MemberInit.isInvalid())
10339 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010340
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010341 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010342 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10343 SourceLocation(),
10344 MemberInit.takeAs<Expr>(),
10345 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010346 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010347
10348 // Be sure that the destructor is accessible and is marked as referenced.
10349 if (const RecordType *RecordTy
10350 = Context.getBaseElementType(Field->getType())
10351 ->getAs<RecordType>()) {
10352 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010353 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010354 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10355 CheckDestructorAccess(Field->getLocation(), Destructor,
10356 PDiag(diag::err_access_dtor_ivar)
10357 << Context.getBaseElementType(Field->getType()));
10358 }
10359 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010360 }
10361 ObjCImplementation->setIvarInitializers(Context,
10362 AllToInit.data(), AllToInit.size());
10363 }
10364}
Sean Huntfe57eef2011-05-04 05:57:24 +000010365
Sean Huntebcbe1d2011-05-04 23:29:54 +000010366static
10367void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10368 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10369 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10370 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10371 Sema &S) {
10372 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10373 CE = Current.end();
10374 if (Ctor->isInvalidDecl())
10375 return;
10376
10377 const FunctionDecl *FNTarget = 0;
10378 CXXConstructorDecl *Target;
10379
10380 // We ignore the result here since if we don't have a body, Target will be
10381 // null below.
10382 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10383 Target
10384= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10385
10386 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10387 // Avoid dereferencing a null pointer here.
10388 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10389
10390 if (!Current.insert(Canonical))
10391 return;
10392
10393 // We know that beyond here, we aren't chaining into a cycle.
10394 if (!Target || !Target->isDelegatingConstructor() ||
10395 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10396 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10397 Valid.insert(*CI);
10398 Current.clear();
10399 // We've hit a cycle.
10400 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10401 Current.count(TCanonical)) {
10402 // If we haven't diagnosed this cycle yet, do so now.
10403 if (!Invalid.count(TCanonical)) {
10404 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010405 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010406 << Ctor;
10407
10408 // Don't add a note for a function delegating directo to itself.
10409 if (TCanonical != Canonical)
10410 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10411
10412 CXXConstructorDecl *C = Target;
10413 while (C->getCanonicalDecl() != Canonical) {
10414 (void)C->getTargetConstructor()->hasBody(FNTarget);
10415 assert(FNTarget && "Ctor cycle through bodiless function");
10416
10417 C
10418 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10419 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10420 }
10421 }
10422
10423 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10424 Invalid.insert(*CI);
10425 Current.clear();
10426 } else {
10427 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10428 }
10429}
10430
10431
Sean Huntfe57eef2011-05-04 05:57:24 +000010432void Sema::CheckDelegatingCtorCycles() {
10433 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10434
Sean Huntebcbe1d2011-05-04 23:29:54 +000010435 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10436 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010437
Douglas Gregor0129b562011-07-27 21:57:17 +000010438 for (DelegatingCtorDeclsType::iterator
10439 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010440 E = DelegatingCtorDecls.end();
10441 I != E; ++I) {
10442 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010443 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010444
10445 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10446 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010447}